简体   繁体   中英

count and average certain pixels in image with MATLAB

I have one image in bmp format, with size of 512*512. I want to count the number of pixels with values more than 11 and then find the average of these pixels. Here is my code. I don't know what is the problem but the sum of pixel values is wrong and it is always 255. I tried with different images.

Could you please help me to figure it out?

A=imread('....bmp');

sum=0; count=0;

for i=1:512    
   for j=1:512
      if (A(i,j)>=11)
        sum=sum+A(i,j);
        count=count+1;
      end
   end
end

disp('Number of pixels grater than or equal to 11')
disp(count)

disp('sum')
disp(sum)

disp('Average')
Avrg=sum/count;
disp(Avrg)

Why doesn't your code work

Difficult to tell, could you display a portion of your matrix and the size using something like

disp(A(1:10,1:10))
disp(size(A))
% possibly also the min and max...
disp(min(A(:))
disp(max(A(:))

just to be sure the format of A is as you expect - imread could have given you a 512x512x3 matrix if the image was read in color, or the image may be in the interval [0,1].

Better approach

Once you're sure that the matrix is indeed 512x512, and has values above 11, you're best off by generating a mask, ie

mask = A > 11;
numabove11 = sum(mask(:));
avabove11 = mean(A(mask));

Also in your code you use >= ie greater than or equal to, but you say 'greater than' - pick which you want and be consistent.

Explanation

So what do these 3 lines do?

  1. Generate a logical matrix, same size as A that is true wherever A > 11 , else false .
  2. Sum the logical matrix, which means sum values that are 1 everywhere that A > 11 , else 0 (boolean values are converted to floats for this summation).
  3. Index in to matrix A using logical indexing , and take the mean of those values.

Avoid shadowing builtins

In your code you use the variable sum - this is bad practice as there is a builtin matlab function with the same name, which becomes unusable if you use a variable of the same name.

I also faced a similar problem and actually the solution lies in the fact that matlab stores A(i,j) in uint8 format whose maximum value is 255, so, just change the statement:

sum=sum+A(i,j);

to

sum=sum+double(A(i,j));

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM