如何将所有黑色像素更改为白色(OpenCV)?

时间:2020-10-13 13:50:39

标签: python opencv colors rgb

我是OpenCV的新手,我不了解如何遍历并将颜色代码为RGB(0,0,0)的黑色所有像素更改为白色RGB(255,255,255)。 是否有任何功能或方法可以检查所有像素,并且是否将RGB(0,0,0)设置为RGB(255,255,255)

1 个答案:

答案 0 :(得分:1)

假设您的图像表示为numpy形状的(height, width, channels)数组(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]
相关问题