Trying to count pixels in a mask

2 次查看(过去 30 天)
Sam
Sam 2011-8-5
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.

回答(2 个)

Friedrich
Friedrich 2011-8-5
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))

Image Analyst
Image Analyst 2011-8-5
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.

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by