【发布时间】:2021-01-27 20:50:39
【问题描述】:
我是 OpenCV 的新手,我不明白如何遍历并将所有颜色代码精确的黑色像素 RGB(0,0,0) 更改为白色 RGB(255,255,255)。
是否有任何功能或方法可以检查所有像素,如果RGB(0,0,0) 则使其成为RGB(255,255,255)。
【问题讨论】:
我是 OpenCV 的新手,我不明白如何遍历并将所有颜色代码精确的黑色像素 RGB(0,0,0) 更改为白色 RGB(255,255,255)。
是否有任何功能或方法可以检查所有像素,如果RGB(0,0,0) 则使其成为RGB(255,255,255)。
【问题讨论】:
假设您的图像表示为形状为(height, width, channels) 的numpy 数组(cv2.imread 返回的内容),您可以这样做:
height, width, _ = img.shape
for i in range(height):
for j in range(width):
# img[i,j] is the RGB pixel at position (i, j)
# check if it's [0, 0, 0] and replace with [255, 255, 255] if so
if img[i,j].sum() == 0:
img[i, j] = [255, 255, 255]
一种更快、基于掩码的方法如下所示:
# get (i, j) positions of all RGB pixels that are black (i.e. [0, 0, 0])
black_pixels = np.where(
(img[:, :, 0] == 0) &
(img[:, :, 1] == 0) &
(img[:, :, 2] == 0)
)
# set those pixels to white
img[black_pixels] = [255, 255, 255]
【讨论】:
img[np.where((img==[0,0,0]).all(axis=2))] = [255,255,255]。啊,你做到了,对不起