【问题标题】:How to change all the black pixels to white (OpenCV)?如何将所有黑色像素更改为白色(OpenCV)?
【发布时间】:2021-01-27 20:50:39
【问题描述】:

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

【问题讨论】:

    标签: python opencv colors rgb


    【解决方案1】:

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

    【讨论】:

    • 虽然正确,但我认为这会非常缓慢,但您应该使用 numpy,例如:img[np.where((img==[0,0,0]).all(axis=2))] = [255,255,255]。啊,你做到了,对不起
    猜你喜欢
    • 2015-02-04
    • 1970-01-01
    • 2023-01-13
    • 2019-12-13
    • 1970-01-01
    • 2018-12-23
    • 2020-05-25
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多