Summing specific pixel values

4 views (last 30 days)
Jason
Jason on 22 Oct 2014
Commented: Bjorn Gustavsson on 22 Oct 2014
Hi. I am wanting to find the sum of all the positons xi, yi of an image IM. I thought the following would do it - but it doesn't.
sum(im (xi,yi));
Also, If I want to take this a step further and find the sum of all pixels at locations xi, yi but this time include the surrounding 8 pixels (so its a 3x3 centred on xi,yi), how do I do that?
thanks

Accepted Answer

Image Analyst
Image Analyst on 22 Oct 2014
You can use a for loop:
m=magic(5) % Whatever...
xi=[2,3,4]
yi = [2,3,4]
theSum = 0;
the8Sum = 0;
for k = 1 : length(xi)
row = yi(k);
col = xi(k);
theSum = theSum + m(row, col);
the8Sum =the8Sum + ...
m(row-1, col-1) + ...
m(row-1, col) + ...
m(row-1, col+1) + ...
m(row, col-1) + ...
m(row, col) + ...
m(row, col+1) + ...
m(row+1, col-1) + ...
m(row+1, col) + ...
m(row+1, col+1);
end
theSum
the8Sum
  2 Comments
Jason
Jason on 22 Oct 2014
Thanks, I will need to work out boundary issues.
Bjorn Gustavsson
Bjorn Gustavsson on 22 Oct 2014
I suggest you do something like this instead:
ind1D = sub2ind(size(im),xi,yi);
sumPixxiyi = sum(im(ind1D));
Then for the nearest Neighbour you'd have to make arrays for them too. In my opinion such a solution is so much easier to maintain since it will be so many fewer lines of code that potential speed losses might be preferable.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!