You have two errors in your code. These errors are easy to make because, in my opinion, a) the documentation of regionprops does a poor job of explaining the coordinate system it uses and b) matlab coordinate system is not consistent.
Your first error is that you assume that regionprops return integer coordinates for the upper left point of the bounding box. It does not. It's all explained under <https://www.mathworks.com/help/images/image-coordinate-systems.html#brcu_cr Image Coordinates System - Spatial Coordinates). In short, the corder of pixel centered at (1,1) is (0.5,0.5). In my opinion, it's bonkers. I've complained to matlab about it. It's not going to change. So if you want to use the coordinates returned by regionprops as indices into your image you need to add 0.5 to them or round them up with ceil.
The second error you have made is that regionprops returns coordinates as (x, y) pairs but indexing in matlab uses (row, column) where row <==> y and column <==> x, so you need to swap the pair elements.
Also note, that your first g loop is not needed.
In short, to solve:
props = regionprops(image, 'BoundingBox');
boundingboxes = vertcat(props.BoundingBox);
boundingboxes(:, [1 2]) = ceil(boundingboxes(:, [1 2]);
boundingboxes(:, [3 4]) = boundingboxes(:, [3 4]) + boundingboxes(:, [1 2]);
sumnn = zeros(size(boundingbox, 1), 1);
for g = 1:size(boundingbox, 1)
sumnn(g) = sum(sum(image(boundingboxes(g, 2):boundingboxes(g, 4), boundingboxes(g, 1):boundingboxes(g, 4))));
end
Or you can do it all in just two lines if you don't need all these intermediary variables:
props = regionprops(image, 'BoundingBox');
sumnn = arrayfun(@(p) sum(sum(image(floor(p.BoundingBox(2))+(1:p.BoundingBox(4)), floor(p.BoundingBox(1))+(1:p.BoundingBox(3))))), props);
Another option is to request SubarrayIdx rather than BoundingBox since SubarrayIdx is the list of all pixels in the bounding box. This leads to much simpler code:
props = regionprops(image, 'SubarrayIdx');
sumnn = arrayfun(@(p) sum(sum(image(p.SubarrayIdx{:}))), props);
Best Answer