MATLAB: Counting the number of black pixels in an image

image processingImage Processing Toolboxmask

Hello, I need help counting the number of black pixels in an image that was just taken through a camera. My current program is able to take an image and then convert the image into a black and white image based on the colors in the first image. I need to count the amount of black pixels in the processed image that was just taken that only contains black and white pixels. If it helps, here is my code so far (P.S. This includes some code that I have commented out to get the program working to this point):
clc
clear
clear all
images= []
webcamlist()
cam= webcam(1)
preview(cam)
pause(2);
images= snapshot(cam)
imshow(images)
r_channel= images(:,:,1);
g_channel= images(:,:,2);
b_channel= images(:,:,3);
images(:,:,1) =0;
images(:,:,3) = 0;
image(images);
mask= g_channel > 100, b_channel > 800, r_channel < 800, b_channel < 0, r_channel < 0;
imshow(mask)
gr_ratio = double(g_channel)./double(r_channel);
gb_ratio = double(g_channel)./double(b_channel);
rb_ratio = double(r_channel)./double(b_channel);
% gr_ratio(isnan(g_ratio))=0;
% grayImage = rgb2gray(image);
% binaryImage = grayImage > 20;
% binaryImage = bwareaopen(binaryImage, 50);
% binaryImage = imfill(binaryImage, 'holes');
% grayImage(~binaryImage) = 0;
falseMatrix= zeros(7,7);
targetMatrix= ones(7,7);
checkMatrix= ones(7,7);
if targetMatrix == checkMatrix
% cam = camStop;
return
end

Best Answer

If "mask" is the image you want to count black pixels in, you can either do it like this:
numBlackPixels = numel(mask) - nnz(mask)
or like this:
numBlackPixels = sum(~mask(:))