0

I am trying to sum up all the values in a 400 x 640 image that are within a masked region using the roifilt2 function. I created a mask using roipoly and it is also stored as a 400 x 640 matrix with 0's in the cells I am uninterested in and 1's in the cells that I wish to sum up.

I was wondering how you would go about this, I have looked at the mathworks page for roifilt2 but I don't understand how to pass the sum function into this properly. This is what I'm trying:

fh = @(I)(sum(I,2));
I2 = roifilt2(I, mask, fh);

where I is my image and mask is my mask. I also keep getting the following error, even though my I and my mask are DEFINITELY the same size:

Error using roifilt2 (line 79) The filtered image is not the same size as the original image.

Any help would be appreciated, Thanks!

James Baker
  • 331
  • 3
  • 8
  • 26
  • why not just do `sum(sum(I.*mask))` or `sum(I(:).*mask(:))`? mask will zero all locations you don't care about. – Raab70 May 07 '14 at 21:07
  • I still get `The filtered image is not the same size as the original image.` as an error, sorry I forgot to mention I was also having that issue. – James Baker May 07 '14 at 21:15
  • My function above does not require the use of `roifilt2`. The return will be the sum of the pixels in the masked region, which is what you requested. – Raab70 May 07 '14 at 21:20
  • I get `ans = NaN` when trying that function? I think it's because my mask is <400x640 logical> and my I is <400x640 double> any ideas? – James Baker May 07 '14 at 21:49
  • Changing the matrix flags didn't help, both equations still return `NaN` as output. – James Baker May 07 '14 at 21:58
  • try running `sum(isnan(I(:)))` and `sum(isnan(mask(:)))`. Not sure how else you would get NaN from that. The type shouldn't matter, a logical times a double will have a result of a double. – Raab70 May 08 '14 at 02:17

1 Answers1

0

The problem is that the sum changes the size of the output image, try by clearing all the values outside of the region then summing up

% Define the function you want to use as a filter. 
% This function, named f, passes the input image x to the imsharpen 
% function and specifies the strength of the sharpening effect
% by using the 'Amount' name-value pair argument.
% f simply puts the values to 0
f = @(x)x-x;

% Filter the ROI using the roifilt2 function and specifying the image, mask, and filtering function.
% This filter clears all the values which are not in the region of interest  
interest_region = roifilt2(img, ~mask, f);

So the final sum of the values in your region will be:

img_sum = sum(interest_region,'all');

Anyway, as Raab70 wrote, you could multiply by the mask to obtain the same result without using roifilt2:

img_sum = sum(img.*mask,'all');
enrico_ay
  • 76
  • 6