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

问题描述

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

解决方法

假设您的图像表示为numpy形状的(height,width,channels)数组(cv2.imread返回的结果),您可以执行以下操作:

height,_ = 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] and replace with [255,255,255] if so
        if img[i,j].sum() == 0:
            img[i,j] = [255,255]

一种更快的基于蒙版的方法如下:

# get (i,j) positions of all RGB pixels that are black (i.e. [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]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...