Counting the number of black pixels in an image

15 views (last 30 days)
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

Accepted Answer

Image Analyst
Image Analyst on 4 Apr 2020
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(:))
  4 Comments
Image Analyst
Image Analyst on 4 Apr 2020
For others, he probably did:
fprintf('mask has %d black pixels.\n', numBlackPixels);
[rows, columns, numberOfColorChannels] = size(mask);
fprintf('mask has %d rows and %d columns.\n', rows, columns);
Jonathan Maness
Jonathan Maness on 4 Apr 2020
The If statement at the end of my original code was messing it up, so all I had to do was get rid of the entire if statement and then add in the line of code that you have me.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!