Search code examples
imagematlabimage-processingcolorspixel

return pixel colors in MATLAB


I am trying to analyze the pixel colors of an image with extension '.png' in MATLAB. I want to return the amount of pixels that are colored within a certain range of a certain RGB value.

I am trying to use the 'imread' function to analyze the image. It returns an array of values 0-255. How do I sort these values to return an amount of pixels close to a certain numerically defined color?


Solution

  • Given a specified tolerance tol, you can determine how many colours are within a certain range by splitting up the image into its three channels and checking if each colour in each channel is within the range. Using nnz to check the total number of non-zero pixels is something to consider here. You can create logical matrices that check if each channel is within a certain tolerance for each colour, then logical ANDing them all together and checking for the number of non-zero entries that results after this computation:

    Something like this, given that your image is stored in im:

    R = 100;
    G = 128;
    B = 123; %// Example
    tol = 5; %// +/- 5 pixels
    imd = double(im); %// For precision
    num = nnz(abs(imd(:,:,1)-R) < tol & ...
              abs(imd(:,:,2)-G) < tol & ...
              abs(imd(:,:,3)-B) < tol);