MATLAB: How to count the number of pixels from an image for specifies colors

counting number of pixels of particular color

I have used the code stated below.
if true
% code

imread color.jpg
load color.jpg
redChannel = color(:, :, 1);
greenChannel = color(:, :, 2);
blueChannel = color(:, :, 3);
whitePixels = redChannel == 255 & ...
greenChannel == 255 & ...
blueChannel == 255;
count = sum(whitePixels(:));
Red1Pixels = redChannel == 255 & ...
greenChannel == 166 & ...
blueChannel == 166;
count = sum(Red1Pixels(:));
Red2Pixels = redChannel == 254 & ...
greenChannel == 85 & ...
blueChannel == 82;
count = sum(Red2Pixels(:))
Blue1Pixels = redChannel == 179 & ...
greenChannel == 169 & ...
blueChannel == 250;
count = sum(Blue1Pixels(:))
Blue2Pixels = redChannel == 255 & ...
greenChannel == 255 & ...
blueChannel == 255;
count = sum(Blue2Pixels(:))
end
and I am getting error as below.
if true
% code
Index exceeds matrix dimensions.
Error in Try_03_07_2018 (line 17) greenChannel = color(:, :, 2); and Try_03_07_2018 is the file name.
Kindly help me out of this.
Regards,
Jotheeshwar V

Best Answer

Neither
imread color.jpg
nor
load color.jpg
import the pixels of the image to th variable color. Use this instead:
color = imread('color.jpg');
By the way: I'd expect load color.jpg to show an error already. So are you sure that your code run at all?