Counting the number of black pixels in an image
15 views (last 30 days)
Show older comments
Jonathan Maness
on 3 Apr 2020
Commented: Jonathan Maness
on 4 Apr 2020
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
0 Comments
Accepted Answer
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
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);
More Answers (0)
See Also
Categories
Find more on Image Data Workflows in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!