gpt4 book ai didi

Python Opencv 仅将颜色减少为 RGB

转载 作者:行者123 更新时间:2023-12-02 16:19:47 25 4
gpt4 key购买 nike

我正在尝试拍摄 RGB 图像并将其中的颜色减少为仅包含红色 (255, 0, 0) 绿色 (0, 255, 0) 和蓝色 (0, 0, 255)。我已经为我编写了一个简单的函数来执行此操作,但它似乎效率很低。

def colorReduce(image):
h, w = image.shape[:2]
for x in range(h):
for y in range(w):
px = image[x][y]
c = np.argmax(px)
px = [0, 0, 0]
px[c]=255
image[x][y] = px
你们中有人对此有更快的方法吗?我知道opencv有cv2.kmeans,但这也不是很有效,因为它比我需要的强大得多。

最佳答案

请注意,在答案末尾有一个比这更快的方法,它使用 np.searchsorted() .
如果您运行 argmax(),您应该能够为此使用矢量化 Numpy。跨越三维,即跨越颜色 channel 。
像这样的东西:

# Make array of brightest colour index
m = np.argmax(im, axis=2)

# Make empty results array same shape as original image
res = np.zeros_like(im)

# Where blue is the brightest, make result blue
res[m==0] = [255,0,0]

# Where green is the brightest, make result green
res[m==1] = [0,255,0]

# Where blue is the brightest, make result blue
res[m==2] = [0,0,255]

我认为这更简洁:
import cv2
import numpy as np

# Load image
im = cv2.imread('colorwheel.jpg')

# Find index of brightest channel at each point
m = np.argmax(im,axis=2)

# Set up possible choices for output colour
choices = [[255,0,0],[0,255,0],[0,0,255]]

# Choose one of the 3 colours based on whichever was brightest
res = np.choose(m[...,np.newaxis],choices)

# Save
cv2.imwrite('result.png',res)
输入图像:
enter image description here
结果:
enter image description here

请注意,使用 np.searchsorted() 实际上快 3-6 倍比 np.choose() :
#!/usr/bin/env python3

import numpy as np

def palette2RGB(image, palette):
indices = np.arange(0, len(palette))
out = palette[np.searchsorted(indices, image)]
return out


palette = np.array([
[255, 0, 0], # red
[ 0, 255, 0], # green
[ 0, 0, 255], # blue
[255, 255, 255], # white
[ 0, 0, 0]]) # black

# Make a repeatable random image 2 rows, 4 columns of palette indices
np.random.seed(0)
image = np.random.randint(0, len(palette), (2,4))

print(image)
# array([[4, 0, 3, 3],
# [3, 1, 3, 2]])

res = palette2RGB(image,palette)
print(res)
#array([[[ 0, 0, 0],
# [255, 0, 0],
# [255, 255, 255],
# [255, 255, 255]],
#
# [[255, 255, 255],
# [ 0, 255, 0],
# [255, 255, 255],
# [ 0, 0, 255]]])
关键词 :Python、图像处理、简单量化、应用颜色图、调色板、LUT、查找、np.choose、np.searchsorted。

关于Python Opencv 仅将颜色减少为 RGB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61065358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com