Discussion:
Pixel counts on matlab image analysis
(too old to reply)
JordanPainter Painter
2010-04-13 13:18:05 UTC
Permalink
Hiya, I'm trying to set a threshold to reduce my values to 1's and 0's then get a total of these 0's and 1's so i can work out a ratio of black to white? My image is a a large jpeg file.

I've tried this so far:

im = 'image.jpg';
im = uint8(im);

level = graythresh(im);
BW = im2bw(im,level);

x = imread(BW);

blackcount = sum(BW(1,:))
whitecount = sum(BW(:,1))

I used the sum code at the bottom for just the standard image but it only pulled up the completely white and completely black pixels i think. So i added the threshold but i can't get it to work. Any help is welcome, thanks a lot!
ImageAnalyst
2010-04-13 16:14:19 UTC
Permalink
blackCount = sum(sum(BW == 0));
whiteCount = sum(sum(BW));

That x=imread(BW) line is unneeded and wrong, as well as your indices
in your count lines. Also, make sure im is 2D monochrome, not 3D RGB
image.
JordanPainter Painter
2010-04-13 16:44:22 UTC
Permalink
Post by ImageAnalyst
blackCount = sum(sum(BW == 0));
whiteCount = sum(sum(BW));
That x=imread(BW) line is unneeded and wrong, as well as your indices
in your count lines. Also, make sure im is 2D monochrome, not 3D RGB
image.
Ah right, i tried your values instead. It seems to only view one line of 9 pixels instead of the entire matrix. Other than that i think this works. Any ideas on how to get it analyse the entire image. Thanks :)
JordanPainter Painter
2010-04-13 17:15:27 UTC
Permalink
This is my latest code:

im = 'crack.jpg';
im = uint8(im);
% imshow(im);
level = graythresh(im);
BW = im2bw(im,level);
imwrite(BW,'black.jpg');
img = 'black.jpg';
imread(img);

blackcount = sum(sum(img == 0))
whitecount = sum(sum(img))

It gives me the answer:

blackcount = 0
whitecount = 876

I'm not sure if saving the output black and white file and then using imread on that is the right idea?
Steven Lord
2010-04-13 17:33:31 UTC
Permalink
Post by JordanPainter Painter
im = 'crack.jpg';
im = uint8(im);
% imshow(im);
level = graythresh(im);
BW = im2bw(im,level);
imwrite(BW,'black.jpg');
img = 'black.jpg';
imread(img);
blackcount = sum(sum(img == 0))
whitecount = sum(sum(img))
blackcount = 0
whitecount = 876
I'm not sure if saving the output black and white file and then using
imread on that is the right idea?
Those answers are correct for the code as written.

Hint 1: When you execute the lines when you compute blackcount and
whitecount, what does the variable img contain?

Hint 2: Call IMREAD with an output argument.
--
Steve Lord
***@mathworks.com
comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ
ImageAnalyst
2010-04-13 17:44:54 UTC
Permalink
Well . . . you're doing it wrong. You're summing the original image,
not the binary image, like you said in your first post. So you're
only getting the number of pixels that are exactly zero in your
original image, not the number of pixels on one side of your
threshold.

Study this demo code and I think you'll understand better.
Be sure to join any lines where the newsreader splits it into two (or
more) lines (i.e., the sprintf line).

% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear all; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;

% Read in standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
[rows columns numberOfColorBands] = size(grayImage);
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', 20);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.

% Just for fun, let's get its histogram.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.

binaryImage = grayImage > 25;
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);

numberOfBlackPixels = sum(sum(binaryImage == 0));
numberOfWhitePixels = sum(sum(binaryImage));
totalNumberOfPixels = rows * columns;
percentBlackPixels = 100.0 * numberOfBlackPixels /
totalNumberOfPixels;
percentWhitePixels = 100.0 * numberOfWhitePixels /
totalNumberOfPixels;
message = sprintf('Done!\nTotal number of pixels = %d\nBlack pixels =
%d = %.1f%%\nWhite pixels = %d = %.1f%%', ...
totalNumberOfPixels, numberOfBlackPixels, percentBlackPixels, ...
numberOfWhitePixels, percentWhitePixels);
msgbox(message);
JordanPainter Painter
2010-04-14 11:40:23 UTC
Permalink
Post by ImageAnalyst
Well . . . you're doing it wrong. You're summing the original image,
not the binary image, like you said in your first post. So you're
only getting the number of pixels that are exactly zero in your
original image, not the number of pixels on one side of your
threshold.
Study this demo code and I think you'll understand better.
Be sure to join any lines where the newsreader splits it into two (or
more) lines (i.e., the sprintf line).
% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear all; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
% Read in standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
[rows columns numberOfColorBands] = size(grayImage);
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', 20);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% Just for fun, let's get its histogram.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
binaryImage = grayImage > 25;
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
numberOfBlackPixels = sum(sum(binaryImage == 0));
numberOfWhitePixels = sum(sum(binaryImage));
totalNumberOfPixels = rows * columns;
percentBlackPixels = 100.0 * numberOfBlackPixels /
totalNumberOfPixels;
percentWhitePixels = 100.0 * numberOfWhitePixels /
totalNumberOfPixels;
message = sprintf('Done!\nTotal number of pixels = %d\nBlack pixels =
%d = %.1f%%\nWhite pixels = %d = %.1f%%', ...
totalNumberOfPixels, numberOfBlackPixels, percentBlackPixels, ...
numberOfWhitePixels, percentWhitePixels);
msgbox(message);
Thanks for all the help. I've used the code above but cropped out the stuff i didn't need. So i'm left with just counting the percentage of black and white pixels. I'm confused by how it's counting the black and white pixels though. This is just out of interest really because it's part of a project and i need to understand it fully before i feel confident using it. How do i alter where it decides which pixels are black and white? I can't see a threshold in there that's all. Sorry for these basic questions, this is the first time i've used matlab for image analysis.
Jordan.
ImageAnalyst
2010-04-14 11:47:45 UTC
Permalink
I think you understand it, you just don't think you do. Yes, in this
example, it's simply the threshold that divides foreground and
background. Change the treshold from 25 to something else in
binaryImage = grayImage > 25;
and you'll change the pixels that are considered foreground (white)
and background (black), which, of course, changes the number of those
pixels also. For example, if your array is [10 20 30 40 50] and I set
a threshold of 25 and am looking to call pixels brighter than 25 as my
foreground then I will have 3 foreground pixels and 2 background
pixels. If I now change the foreground to be 15, I will have 4
foreground pixels and 1 background pixel. If instead I use
binaryImage = grayImage < 25;
then now my foreground is the dark things and I will have 2 foreground
pixels (the 10 and the 20) and 3 background pixels (the 30, the 40,
and the 50).

You might like to run and study my image processing demo:
http://www.mathworks.com/matlabcentral/fileexchange/25157
for more fancy things that you can do. But it's well documented so I
think you should be able to follow along very well.
JordanPainter Painter
2010-04-14 13:32:04 UTC
Permalink
Yeah it's all working fine now. I've just got to figure out how to analyse 50 photos at once and then plot the white pixel count for each one. Just a quick question though, since counting the pixels for a new image i've got the pixel count in three stages:

percentBlackPixels(:,:,1) =67.6205


percentBlackPixels(:,:,2) = 97.2661


percentBlackPixels(:,:,3) = 99.9580

Originally this didn't happen so i don't know what i've done to change anything. I was just wondering what it meant. At first i ignored the first two values because they originally came back as zero, but now i'm getting actual values for them it's worried me a bit. Sorry to keep hassling and thanks a lot for the help already. It's been really helpful :)
JordanPainter Painter
2010-04-14 14:13:02 UTC
Permalink
I think i've cracked it actually, it's giving me 3 samples per pixel because the new image i am reading is a 24 bit depth image rather than 8 on the old image. I think that's right anyways.
JordanPainter Painter
2010-04-14 14:18:05 UTC
Permalink
Post by JordanPainter Painter
I think i've cracked it actually, it's giving me 3 samples per pixel because the new image i am reading is a 24 bit depth image rather than 8 on the old image. I think that's right anyways.
Saying this, how would i go about changing the bit depth of an image? Or can i take an average of all 3 of these values and use that as my percentage?
ImageAnalyst
2010-04-14 16:18:19 UTC
Permalink
Depends on what color you define as "white." Maybe you'd like to see
my color detection demo:
http://www.mathworks.com/matlabcentral/fileexchange/26420-simplecolordetection
JordanPainter Painter
2010-04-14 18:39:04 UTC
Permalink
Post by ImageAnalyst
Depends on what color you define as "white." Maybe you'd like to see
http://www.mathworks.com/matlabcentral/fileexchange/26420-simplecolordetection
Thanks for that, these demos are really helpful. What i've done now is just used matlab to manually convert all my images to black and white 8 bit jpeg files. It got the job done. I just need to figure out this loop for multiple images. I want to pull out their whitepixel counts and plot them accordingly but all the for loops i've made so far don't seem to work. It has trouble with the imread function.
ImageAnalyst
2010-04-14 20:10:32 UTC
Permalink
"JordanPainter Painter" <***@hotmail.co.uk>:
I don't know why imread should have a problem. What is the problem?
Can't find the image? Are you passing it the full filename (folder +
base filename)? Is the image is corrupted? What is the error message?
JordanPainter Painter
2010-04-14 22:07:03 UTC
Permalink
Post by ImageAnalyst
I don't know why imread should have a problem. What is the problem?
Can't find the image? Are you passing it the full filename (folder +
base filename)? Is the image is corrupted? What is the error message?
I get a filename error. But i'm not doing the loop properly. I'm not sure how to 'list' all the individual files in a sense and then call them all individually to be analysed. I've not done a loop like this before so i'm struggling. I'm not sure how to just input all the images originally so they can be called.
ImageAnalyst
2010-04-14 22:21:49 UTC
Permalink
Well why don't you take a look at this:
http://www.mathworks.com/matlabcentral/fileexchange/24224
It shows you how to load up listboxes, select some files from the
listbox, and click "Process images" to batch process the selected
images one by one in a loop. It also shows you how to save results
and write them out to an Excel workbook, plus some other things.
Francesco Montemurro
2010-09-15 15:06:20 UTC
Permalink
Hi JordanPainter Painter have you write the code used to find black pixels?

If you writed that code please send me a copy at my email

thanks so much,

regards,

Francesco.
ImageAnalyst
2010-09-15 15:28:19 UTC
Permalink
On Sep 15, 11:06 am, "Francesco Montemurro"
Post by Francesco Montemurro
Hi JordanPainter Painter have you write the code used to find black pixels?
If you writed that code please send me a copy at my email
thanks so much,
regards,
Francesco.
------------------------------------------------------------------------------------
Francesco Montemurro:
You'd have better luck just posting your image to http://drop.io and
asking your question, and showing any code that you already have.
Start a brand new thread for this, don't tack it on to JordanPainter's
(who may be long gone).
Ambadas Shinde
2014-06-16 09:53:13 UTC
Permalink
Image Analyst,

Can you suggest me, how to count white pixels row wise, actually i want to check which row has maximum white pixels in foreground...
the rows having maximum white pixels I need to subtract from binary image
Post by ImageAnalyst
Well . . . you're doing it wrong. You're summing the original image,
not the binary image, like you said in your first post. So you're
only getting the number of pixels that are exactly zero in your
original image, not the number of pixels on one side of your
threshold.
Study this demo code and I think you'll understand better.
Be sure to join any lines where the newsreader splits it into two (or
more) lines (i.e., the sprintf line).
% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear all; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
% Read in standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
[rows columns numberOfColorBands] = size(grayImage);
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', 20);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% Just for fun, let's get its histogram.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 2);
bar(pixelCount);
title('Histogram of original image', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.
binaryImage = grayImage > 25;
subplot(2, 2, 3);
imshow(binaryImage, []);
title('Binary Image', 'FontSize', fontSize);
numberOfBlackPixels = sum(sum(binaryImage == 0));
numberOfWhitePixels = sum(sum(binaryImage));
totalNumberOfPixels = rows * columns;
percentBlackPixels = 100.0 * numberOfBlackPixels /
totalNumberOfPixels;
percentWhitePixels = 100.0 * numberOfWhitePixels /
totalNumberOfPixels;
message = sprintf('Done!\nTotal number of pixels = %d\nBlack pixels =
%d = %.1f%%\nWhite pixels = %d = %.1f%%', ...
totalNumberOfPixels, numberOfBlackPixels, percentBlackPixels, ...
numberOfWhitePixels, percentWhitePixels);
msgbox(message);
Bruno Luong
2014-06-16 10:29:09 UTC
Permalink
Post by Ambadas Shinde
Image Analyst,
Can you suggest me, how to count white pixels row wise, actually i want to check which row has maximum white pixels in foreground...
the rows having maximum white pixels I need to subtract from binary image
% Pseudo binary image
Image = rand(10)>0.3

NbWhitePixelsPerRow = sum(Image == 1, 2)

% Bruno
s***@gmail.com
2017-02-12 09:29:15 UTC
Permalink
Post by Bruno Luong
Post by Ambadas Shinde
Image Analyst,
Can you suggest me, how to count white pixels row wise, actually i want to check which row has maximum white pixels in foreground...
the rows having maximum white pixels I need to subtract from binary image
% Pseudo binary image
Image = rand(10)>0.3
NbWhitePixelsPerRow = sum(Image == 1, 2)
% Bruno
what is mean by rand(10)>0.3 and sum(Image == 1, 2) for?
o***@gmail.com
2017-02-13 06:41:49 UTC
Permalink
Because the university life only into the new life, I have abandoned their studies, resulting in many serious course I fail the exam, I really don't know what to do, have difficulty graduate, get a degree certificate, my study career will end? I am not willing to, so I find a special for overseas students to solve the difficulties of the site, to help, hope they help me get what I want to get the normal quality certificate, they really have nothing to say, just do a week, high quality and quick speed, I strongly recommend. If necessary, you can contact them, although their prices are high, but the quality can pass. Now I have found a good job with these certificates. No longer worry about the difficult problem of returning to employment.
Our company focus on fake high school diploma, fake college diploma university diploma, fake associate degree, fake bachelor degree, fake doctorate degree, fake passport, fake visa, and so on. We provide highest quality and best sevice with reasonable price. buy diploma, buy college diploma,buy university diploma,buy high school diploma,buy visa, buy passport,or anything you need. There are our contact below:

Skype:Gaea7.18
QQ:372725176
http://www.buydiploma9.com
E-mail:***@yahoo.com
x***@gmail.com
2018-03-28 09:08:44 UTC
Permalink
在 2010年4月13日星期二 UTC+8下午9:18:05,JordanPainter Painter写道:
Post by JordanPainter Painter
Hiya, I'm trying to set a threshold to reduce my values to 1's and 0's then get a total of these 0's and 1's so i can work out a ratio of black to white? My image is a a large jpeg file.
im = 'image.jpg';
im = uint8(im);
level = graythresh(im);
BW = im2bw(im,level);
x = imread(BW);
blackcount = sum(BW(1,:))
whitecount = sum(BW(:,1))
I used the sum code at the bottom for just the standard image but it only pulled up the completely white and completely black pixels i think. So i added the threshold but i can't get it to work. Any help is welcome, thanks a lot!
x***@gmail.com
2018-03-28 09:11:46 UTC
Permalink
Why do so many people want to buy fake degrees online?
To be honest, I don't know why so many people want to buy fake degrees online. An online degree from the university of alberta.
Is it because they can't get scholarships from universities, or do they just want to buy a diploma to have fun? Or is it because their boss wants to see it? I can't understand. For fun, I can understand that I can understand a job. But with so many companies, how do you buy the real thing? Or is it just their price?
Web:www.buytopdegree.com
Email: ***@hotmail.com
Skype:Degree Provider
QQ:3438938163
Wechat:Alisa528

Loading...