MATLAB: Counting pixels of colored objects in an image

image processingimage segmentation

Hi everyone. I have an image (attached) with three different colors as blue, white and yellow. I need to count the number of pixels for each color so that I am able to find the percentage of the associated color in my image. I used two following codes. In the first code which I obtained from the foroum, only the red color has been specified and I dont know how to apply it for blue, white and yellow colors. In the second code, surprisingly, the calculated number of blue color' pixel becomes equal to zero and I am sure something wrong. your help would be appreciated.
first code:
%Load image
rgb = imread('pic1.png');
figure(1)
imshow(rgb)
%%Find red points
redPoints = rgb(:,:,1)>=130 & rgb(:,:,2)<=60 & rgb(:,:,3)<=100;
percentRed = 100*(sum(sum(redPoints))/(size(rgb,1)*size(rgb,2)));
fprintf('Image has %d red pixels\n',sum(sum(redPoints)))
fprintf('Image is %.2f percent red\n',percentRed)
%%Highlight red on image
rgbRed = uint8(cat(3,redPoints,redPoints,redPoints)).*rgb;
figure(2)
imshow(rgbRed)
second attempt (code):
c
lc;clear all;close all;
A=imread('pic1.png');
yellowPixels = A(:,:,1) == 255 & A(:,:,2) == 255 & A(:,:,3) == 0;
numYellowPixels = sum(yellowPixels(:));
bluePixels = A(:,:,1) == 0 & A(:,:,2) == 0 & A(:,:,3) == 255;
numBluePixels = sum(bluePixels(:));
whitePixels = A(:,:,1) == 255 & A(:,:,2) == 255 & A(:,:,3) == 255;
numWhitePixels = sum(whitePixels(:));
counts = imhist(A);

Best Answer

The reason why the 2nd attempt doesn't work is because you're trying to match exact color values but your image clearly has many shades of blue so there needs to be a tolerance where you accept a range of blue values.
That's what the first attempt does with red colors.
rgb is an m x n x 3 array where the 3rd dimension specifies the amount of [red, green, blue] in each pixel on a scale from 0:255. The current code accepts values where the 'red' values are >= 130, green values are <= 60, and blue values are <= 100. To select a range of blue colors, you could start by just switching these thresholds around to favor the blue part of the specturm:
bluePoints = rgb(:,:,1)<=60 & rgb(:,:,2)<=60 & rgb(:,:,3)>=130;
% [red ] [green] [blue ]
I didn't test those values but you can play around with it to get the results you want. You can check out the links below to get a feel of what 'blue' looks like in terms of rgb values.