Reduce number of colors in matlab using rgb2ind

后端 未结 2 600

I am doing some image processing and I needed to reduce the number of colors of an image. I found that rgb2ind could do that and wrote the following snippet:

<
相关标签:
2条回答
  • 2021-01-21 14:56

    It may perceptually look like there is more than 6 colours, but there is truly 6 colours. If you take a look at your map variable, it will be a 6 x 3 matrix. Each row contains a colour that you want to quantize your image to.

    To double check, convert this image into a grayscale image, then do a histogram of this image. If rgb2ind worked, you should only see 6 spikes in the histogram.

    BTW, to be able to reconstruct your problem, you used the peppers.png image that is built-in to MATLAB's system path. As such, this is what I did to describe what I'm talking about:

    RGB = imread('peppers.png');
    
    %// Your code
    [X,map] = rgb2ind(RGB,6,'nodither');
    X = rgb2ind(RGB, map);
    rgb=ind2rgb(X,map);
    rgb_uint8=uint8(rgb*255+0.5);
    imshow(rgb_uint8);
    
    %// My code - Double check colour distribution
    figure;
    imhist(rgb2gray(rgb_uint8));
    axis tight;
    

    This is the figure I get:

    enter image description here

    As you can see, there are 6 spikes in our histogram. If there are truly 6 unique colours when you ran your code, then there should be an equivalent of 6 equivalent grayscale intensities when you convert the image into grayscale, and the histogram above verifies our findings.

    As such, you are quantizing your image to 6 colours, but it doesn't look like it due to quantization noise of your image.

    0 讨论(0)
  • 2021-01-21 14:56

    Don't doubt of your result, the image contains exactly 6 colours.

    As explained in the Matlab documentation, the rgb2ind function returns an indexed matrix (X in your code) and a colormap (map in your code). So if you want to check the number of colours in X, you can simply check the size of the colormap: size(map)

    In your case the size will be 6x3: 6 colours described on 3 channels (red, greed and blue).

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