Summing specific pixel values

1 次查看(过去 30 天)
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

采纳的回答

Image Analyst
Image Analyst 2014-10-22
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 个评论
Jason
Jason 2014-10-22
Thanks, I will need to work out boundary issues.
Bjorn Gustavsson
Bjorn Gustavsson 2014-10-22
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by