MATLAB: How to calculate the mean value of a region given the mask from ROIPOLY

Image Processing Toolbox

I have an image and I want to calculate the mean pixel value in a region of interest. I have defined the polygon and ROIPOLY returns a mask. The mask is a filled polygon with value 1;s and all 0's outside.

Best Answer

The attached file calculates the mean pixel value from a region of interest. The ROIPOLY function creates a mask, BW, where the region defined by the polygon is of value 1 and the rest are of value 0.
Convert the mask, BW, to type 'double' and the zero portions into NaN entries. Also, convert the original image to type 'double'. These two tasks are performed in order to calculate the mean.
By converting the mask into the datatype of the image and multiplying, the region of interest is isolated by the polygon. As a result, the image left, filter_I, is the original image surrounded by NaN values.
Calculating the mean is then an issue of selecting the non-NaN values, which can be done as shown below:
mean(filter_I(~isnan(filter_I)))
NaN values are used because if the original mask is multiplied into the original image, then the resulting would be the region of interest surrounded by zeros.
Calculating the mean would then involve selecting the image values that are not equal to zero; however, if there are zero values in the region of interest, calculating the mean in this fashion will give an incorrect mean; as a result, NaN values are a convenient workaround.