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

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

image_gray = cv2.imread(image,cv2.IMREAD_GRAYSCALE)

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

np.unique(image_gray.flatten())

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

jllykg 回答:在图像处理中澄清np.unique()值

使用cv2.IMREAD_GRAYSCALE在OpenCV 2中加载图片时,您指定要使用灰度值加载图像。这样,图像的每个像素将采用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)

现在,如果要在将图片加载为灰度图像后想要具有相应的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)

现在,请注意,如果要获取给定图片中像素所获取的所有唯一RGB值,则需要执行

np.unique(image.reshape(-1,image.shape[2]),axis=0)

这是因为展平数组也会展平RGB值。在这里,我们调整图片的形状以仅使数组的行和列变平。

本文链接:https://www.f2er.com/3163224.html

大家都在问