澄清图像处理中的 np.unique() 值

Dar*_*r34 3 python opencv image-processing python-3.x

愚蠢的问题。我有一个图像,我正在使用cv2如下库通过 python 以灰度读取它:

image_gray = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
Run Code Online (Sandbox Code Playgroud)

当我尝试查找此图像中的不同颜色值时,我使用以下内容:

np.unique(image_gray.flatten())
Run Code Online (Sandbox Code Playgroud)

这将返回 [58, 255]。这些数字代表什么?如何获得等效的 RGB 值?

The*_*nce 5

当使用 OpenCV 2 加载图片时cv2.IMREAD_GRAYSCALE,您指定要加载具有灰度值的图像。这样,图像的每个像素将采用 0(黑色)和 255(白色)之间的值

在这里,np.unique(image_gray.flatten())您可以得到图像中找到的所有唯一像素值。从你的结果来看,图片中只有两种颜色,因为它[58, 255]是长度为 2 的列表。

为了直接用RGB值而不是灰度值加载图片,你可以做的是:

# this will load the picture with colors
image = cv2.imread("input.png", cv2.IMREAD_COLOR)
Run Code Online (Sandbox Code Playgroud)

现在,如果您想在将图片加载为灰度图像后获得相应的 RGB 值,您可以执行以下操作:

# this would only convert the grayscale image to a color one
# if the image was loaded with cv2.IMREAD_GRAYSCALE, it will remain gray
# but the array will have RGB values instead of grayscale values
image_rgb = cv2.cvtColor(image_gray,cv2.COLOR_GRAY2RGB)
Run Code Online (Sandbox Code Playgroud)

现在,请注意,如果您想获取给定图片中像素所采用的所有唯一 RGB 值,您需要执行以下操作

np.unique(image.reshape(-1, image.shape[2]), axis=0)
Run Code Online (Sandbox Code Playgroud)

这是因为展平数组也会展平 RGB 值。在这里,我们重塑图片以仅展平数组的行和列。