python opencv获取每个颜色通道上具有完全相同值的所有像素

eli*_*r88 0 python opencv

我在 OpenCV 中有一个图像,我想将其转换为二进制数组。

我希望具有相同 BGR 颜色值的每个像素为 1,例如 #FFFFFF 将是白色但#FFE0A1 将是黑色,因为所有三个通道不共享相同的值。

有没有简单的方法来实现这一目标?

Cam*_* M. 5

您可以使用遮罩来执行此操作。例如,

import numpy as np

# random image
img = (np.random.randn(1000, 1000, 3) * 255).astype(np.uint8)

img[0, 0] = np.array([255, 255, 255]) # test value

# initialization of binary image with all zeros
binary = np.zeros((img.shape[:-1]), dtype=int)

# create boolean masks
a = img[:, :, 0] == img[:, :, 1]
b = img[:, :, 1] == img[:, :, 2]

# this will create the final mask (a and b)
mask = np.logical_and(a, b)

# make the final assignment
binary[mask] = 1
Run Code Online (Sandbox Code Playgroud)

然后,如果你检查binary

>>> binary
    array([[1, 0, 0, ..., 0, 0, 0],
           [0, 0, 0, ..., 0, 0, 0],
           [0, 0, 0, ..., 0, 0, 0],
           ...,
           [0, 0, 0, ..., 0, 0, 0],
           [0, 0, 0, ..., 0, 0, 0],
           [0, 0, 0, ..., 0, 0, 0]])
Run Code Online (Sandbox Code Playgroud)

如您所见,测试值被正确分配给1

  • @elite gamer88 数据类型应该是“uint8” (2认同)