MATLAB: Binary Image: Count number of pixels that are 1.

binary imagecount pixelsImage Processing Toolbox

The code below is a simplified version of the one part of a longer code that I am running into an error. In the code below, I successfully convert the gray scale image into a binary image. Then I try to count the number of pixels in the image that are 1 (by using the for loop and bin()). However, MATLAB says, "Undefined function or variable 'rows'." Then if I type a number instead of saying rows columns, I get the error, "if bin(i,j) == 1."
I've looked at the syntax of the bin command, and I have tried problem solving this. However, I don't know if the for loop knows to apply itself to the image. Please let me know how I can fix this for loop to work properly.
Code:
I = imread('rice.png');
figure; imshow(I);
bw = imbinarize(I);
figure; imshow(bw);
ctr= 0;
for i = 1 : rows
for j = 1 : columns
if bin(i,j) == 1
ctr = ctr + 1;
end
end
end

Best Answer

May be so:
I = imread('rice.png');
figure; imshow(I);
bw = imbinarize(I);
figure; imshow(bw);
ctr= 0;
for i = 1 : rows
for j = 1 : columns
if bw(i,j) == 1
ctr = ctr + 1;
end
end
end