简体   繁体   English

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

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

I am new to OpenCV and I do not understand how to traverse and change all the pixels of black with colour code exact RGB(0,0,0) to white colour RGB(255,255,255) .我是 OpenCV 的新手,我不明白如何遍历并将颜色代码精确RGB(0,0,0)的所有黑色像素更改为白色RGB(255,255,255) Is there any function or way to check all the pixel and if RGB(0,0,0) the make it to RGB(255,255,255) .是否有任何功能或方法来检查所有像素,如果RGB(0,0,0)使其变为RGB(255,255,255)

Assuming that your image is represented as a numpy array of shape (height, width, channels) (what cv2.imread returns), you can do:假设您的图像表示为形状(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]

A faster, mask-based approach looks like this:一种更快的基于掩码的方法如下所示:

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

Subtract 255 from each Pixel and get the positive values only从每个像素中减去 255 并仅获得正值

For grayscale and black and white images适用于灰度和黑白图像

sub_array = 255*np.ones(28, dtype = int) img_Invert = np.abs(np.subtract(img,sub_array)) 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM