Trying to count pixels in a mask

2 views (last 30 days)
Sam
Sam on 5 Aug 2011
I have a variable called MASK2 and want to count the pixels in it using the following layout that has been given to me
function number=pixcount(BLANK)
number=0;
for n=BLANK:BLANK
for m=BLANK:BLANK
if BLANK(n,m)==1
number=number+1;
BLANK
BLANK
BLANK
So I have written the following
function number=pixcount(MASK2)
number=0;
for n=1:1500
for m=1:977
if MASK2(n,m)==1
number=number+1;
end
end
end
but get an error message on line 5 saying Input argument "MASK2" is undefined.
Error in ==> maskloop at 5 if MASK2(n,m)==1
What am I doing wrong? Thanks.

Answers (2)

Friedrich
Friedrich on 5 Aug 2011
Hi,
sounds like you are calling your function without an input like pixcount(). Try to pass something, like pixcount(rand(1500,997)).
But in general you can count 1 a bit faster, e.g.
number = sum(sum(Mask2==1))
If Mask2 is a logical matrix than you can do
number = sum(sum(Mask2))
  1 Comment
Image Analyst
Image Analyst on 5 Aug 2011
rand(1500,997) will never = 1 so the number will always = 0.

Sign in to comment.


Image Analyst
Image Analyst on 5 Aug 2011
You can't just run that function without calling it with a defined matrix. You need to call it from another function (if it's in the same file) or from a separate script. For example in script1.m:
m = rand(100);
mask2 = m > 0.7;
% Now call the function:
pixelCount = pixcount(mask2);
Then in pixcount.m:
function number=pixcount(MASK2)
number=0;
[rows columns numberOfColorChannels] = size(MASK2)
for n=1:rows
for m=1:columns
if MASK2(n,m)==1
number=number+1;
end
end
end
And, like Frederich said, that's not an efficient way to do what it ends up doing.

Categories

Find more on Get Started with MATLAB 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!