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

Rag*_*tia 2 python rgb opencv colors

我是 OpenCV 的新手,我不明白如何遍历和更改所有黑色像素,颜色代码精确RGB(0,0,0)为白色RGB(255,255,255)。是否有任何功能或方法可以检查所有像素以及是否RGB(0,0,0)使其达到RGB(255,255,255).

Ale*_*inu 7

假设您的图像表示为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]
Run Code Online (Sandbox Code Playgroud)

更快的、基于掩码的方法如下所示:

# 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]
Run Code Online (Sandbox Code Playgroud)

  • 虽然正确,但我认为这会非常慢,您应该使用 numpy 例如: `img[np.where((img==[0,0,0]).all(axis=2))] = [255,255,255] `。啊,你已经做到了,抱歉 (5认同)