简体   繁体   English

numpy:图像中唯一的颜色列表

[英]numpy: unique list of colors in the image

I have an image img :我有一个图像img

>>> img.shape
(200, 200, 3)

On pixel (100, 100) I have a nice color:在像素 (100, 100) 上,我有一个漂亮的颜色:

>>> img[100,100]
array([ 0.90980393,  0.27450982,  0.27450982], dtype=float32)

Now my question is: How many different colors are there in this image, and how do I enumerate them?现在我的问题是:这张图片中有多少种不同的颜色,我该如何枚举它们?

My first idea was numpy.unique() , but somehow I am using this wrong.我的第一个想法是numpy.unique() ,但不知何故我用错了。

Your initial idea to use numpy.unique() actually can do the job perfectly with the best performance:您最初使用numpy.unique()想法实际上可以以最佳性能完美地完成工作:

numpy.unique(img.reshape(-1, img.shape[2]), axis=0)

At first, we flatten rows and columns of matrix.首先,我们展平矩阵的行和列。 Now the matrix has as much rows as there're pixels in the image.现在矩阵的行数与图像中的像素数一样多。 Columns are color components of each pixels.列是每个像素的颜色分量。

Then we count unique rows of flattened matrix.然后我们计算扁平矩阵的唯一行。

你可以这样做:

set( tuple(v) for m2d in img for v in m2d )

One straightforward way to do this is to leverage the de-duplication that occurs when casting a list of all pixels as a set:一种直接的方法是利用在将所有像素列表投射为一组时发生的重复数据删除:

unique_pixels = np.vstack({tuple(r) for r in img.reshape(-1,3)})

Another way that might be of practical use, depending on your reasons for extracting unique pixels, would be to use Numpy's histogramdd function to bin image pixels to some pre-specified fidelity as follows (where it is assumed pixel values range from 0 to 1 for a given image channel):根据您提取唯一像素的原因,另一种可能有实际用途的方法是使用 Numpy 的histogramdd函数将图像像素分箱为一些预先指定的保真度,如下所示(假设像素值范围从 0 到 1给定的图像通道):

n_bins = 10
bin_edges = np.linspace(0, 1, n_bins + 1)
bin_centres = (bin_edges[0:-1] + bin_edges[1::]) / 2.
hist, _ = np.histogramdd(img.reshape(-1, 3), bins=np.vstack(3 * [bin_edges]))
unique_pixels = np.column_stack(bin_centres[dim] for dim in np.where(hist))

If for any reason you will need to count the number of times each unique color appears, you can use this:如果出于任何原因您需要计算每种独特颜色出现的次数,您可以使用以下命令:

from collections import Counter
Counter([tuple(colors) for i in img for colors in i])

The question about unique colors (or more generally unique values along a given axis) has been also asked here (in particular, see this answer ). 此处还询问有关独特颜色(或更普遍地沿给定轴的独特值)的问题(特别是,请参阅此答案)。 If you're seeking for the fastest available option then "void view" would be your weapon of choice:如果您正在寻找最快的可用选项,那么“无效视图”将是您的首选武器:

axis=2
np.unique(
        img.view(np.dtype((np.void, img.dtype.itemsize*img.shape[axis])))
        ).view(img.dtype).reshape(-1, img.shape[axis])

For any questions related to what the script actually does, I refer the reader to the links above.对于与脚本实际作用相关的任何问题,我建议读者参考上面的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM