numpy: unique list of colors in the image

前端 未结 5 1123
眼角桃花
眼角桃花 2020-12-16 15:54

I have an image img:

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

On pixel (100, 100) I have a nice color:

>>>         


        
相关标签:
5条回答
  • 2020-12-16 16:17

    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.

    0 讨论(0)
  • 2020-12-16 16:26

    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])
    
    0 讨论(0)
  • 2020-12-16 16:31

    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):

    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))
    
    0 讨论(0)
  • 2020-12-16 16:33

    You could do this:

    set( tuple(v) for m2d in img for v in m2d )
    
    0 讨论(0)
  • 2020-12-16 16:39

    Your initial idea to use numpy.unique() actually can do the job perfectly with the best performance:

    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.

    0 讨论(0)
提交回复
热议问题