Rabani Ahmad Tasman
Rabani Ahmad Tasman

Reputation: 43

Count the percentage number of colours in an image

I have completed a programming that can count up to 8 colors in images by using the RGB method from 000 up to 111. I need to do some modification to it. So far I declare the number if above 128 will equal to 1 & below 128 will be 0. It will count the 8 colours. How to increase the number of colours count? Here is an example of code for count up to 8 colours:

rgbImage = imread('football.jpg');
imshow(rgbImage);
[w,h,d] = size(rgbImage)
redChannel = rgbImage(:,:, 1);
greenChannel = rgbImage(:,:, 2);
blueChannel = rgbImage(:,:, 3);
quantizedImage=zeros(size(rgbImage));
count=zeros(1,8);
for i = 1:w 
    for j = 1:h        
      if redChannel(i,j) > 128,
          aredChannel2 = 1;
      else
          aredChannel2=0;
      end
      quantizedImage(i,j,1)=aredChannel2*255;
      if greenChannel(i,j) > 128,
        agreenChannel2 = 1;
      else
        agreenChannel2=0;
      end
      quantizedImage(i,j,2)=agreenChannel2*255;
      if blueChannel(i,j) > 128,
        ablueChannel2 = 1;
      else
        ablueChannel2=0;
      end
      quantizedImage(i,j,3)=ablueChannel2*255;
      bin=4*aredChannel2+2*agreenChannel2+ablueChannel2+1;
      count(bin)=count(bin)+1;
    end
end
figure, imshow(uint8(quantizedImage));

Upvotes: 2

Views: 471

Answers (1)

Shai
Shai

Reputation: 114786

You should use rgb2ind to help you achieve your goal.
First, create a colormap with 64 colors. This colormap is created by dividing each color channel (R,G and B) into 4 bins total 4*4*4 = 64 possible colors. The range of each color channel is between 0 and 1, therefore the centers of the bins are 0.1250, 0.3750, 0.6250 and 0.8750. Or in a more Matlab-ish language: (0:.25:.75)+0.125.
I am using meshgrid to create the cartesian product between all possible bins:

[C{1:3}] = meshgrid( (0:.25:.75)+0.125 );
cmp = [C{1}(:) C{2}(:) C{3}(:)];

Once you have the 64-colors colormap you can quantize the image

qImg = rgb2ind( rgbImage, cmp, 'nodither');

That's it!

Here's your output

figure;imagesc(qImg);colormap(cmp);

enter image description here

If you want to count the number of pixels in each of the 64 bins, you can simply use hist

count = hist( double(qImg(:)), 64 );

Upvotes: 2

Related Questions