简体   繁体   中英

calculating mean gray level

I have a lot of images in IM{} . I want to calculate mean graylevel of non-black pixels. When I run my code sum has 255 as a maximum value. I don't understand the reason. Why doesn't sum get higher values?

for i=1: length(IM)
[L,W,z]=size( IM{i});
k=1;
sum=0;
for L=1:L
    for W=1: W
        if IM{i}(L,W)~=0;
      sum=IM{i}(L,W)+sum;
      k=k+1;
        end
    end    
end
Mean(i)=sum/k

end

That's probably because IM is of type uint8 . This data type can't hold values larger than 255. Example:

>> uint8(200) + uint8(200)
ans =
  255

To avoid this, you should convert IM to double :

IM = double(IM);

Anyway, your code could be reduced to a single line (including the conversion):

result = mean(double(IM(IM>0)));

With this approach, you could even dispense with double , because mean (actually sum , which is called by mean ) converts to double automatically:

result = mean(IM(IM>0));    

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