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

How to change all the black pixels to white (OpenCV)?

我是 OpenCV 的新手,我不明白如何遍历并将颜色代码完全 RGB(0,0,0) 的黑色的所有像素更改为白色 RGB(255,255,255)。 是否有任何功能或方法来检查所有像素,如果 RGB(0,0,0) 则使其变为 RGB(255,255,255).

假设您的图像表示为 numpy 形状数组 (height, width, channels)cv2.imread returns),您可以:

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]

更快的 mask-based 方法如下所示:

# 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]

从每个像素中减去 255,只得到正值

对于灰度和黑白图像

sub_array = 255*np.ones(28, dtype = int) img_Invert = np.abs(np.subtract(img,sub_array))

cv.rectangle(img,(0,0),(img.shape[1],img.shape[0],(255,255,255),thickness=-1)
cv.imshow('img',img)