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

标签 python opencv colors rgb

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

最佳答案

假设您的图像表示为形状为 (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]

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

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

关于python - 如何将所有黑色像素更改为白色(OpenCV)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64336516/

相关文章:

python - 从图像和标签中高效地提取补丁

android - OpenCV Python 安卓

python-3.x - 轮廓-OpenCV错误:诸如船体,矩形等不同特征的输出相同

opencv - 筛选描述符提取器

flutter - 如何更改 CircularProgressIndicator 的颜色

python - 鼠兔,stop_consuming 不起作用

python - OpenCV + Python + GigE 视觉相机

c++ - 如何生成 cv::Mat 类型的代码?

javascript - 颜色阴影响应 div 的数量

javascript - Highcharts 线单一数据集但多种颜色,不是渐变颜色