Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mean of an image using a mask

I have a series of concentric rectangles and wish to obtain the means of the outer rectangle excluding the inner rectangle. See the attached diagram , I need to get the mean for the shaded area. enter image description here

So I am using a mask of the inner rectangle to pass into the cv2.mean method, but I am not sure how to set the mask. I have the following code:

for i in xrange(0,len(wins)-2,1):
    means_1 = cv2.mean(wins[i])[0]
    msk = cv2.bitwise_and(np.ones_like((wins[i+1]), np.uint8),np.zeros_like((wins[i]), np.uint8))
    means_2 = cv2.mean(wins[i+1],mask=msk)
    means_3 = cv2.mean(wins[i+1])[0]
    print means_1,means_2,means_3

I get this error for the means_2 (means_3 works fine).:

error: /Users/jenkins/miniconda/0/2.7/conda-bld/work/opencv-2.4.11/modules/core/src/arithm.cpp:1021: error: (-209) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function binary_op

like image 524
Santino Avatar asked Dec 26 '16 14:12

Santino


People also ask

What does mask image mean?

A mask image is simply an image where some of the pixel intensity values are zero, and others are non-zero. Wherever the pixel intensity value is zero in the mask image, then the pixel intensity of the resulting masked image will be set to the background value (normally zero).


1 Answers

The mask here refers to a binary mask which has 0 as background and 255 as foreground, So You need to create an empty mask with default color = 0 and then paint the Region of Interest where you want to find the mean with 255. Suppose I have input image [512 x 512]:

enter image description here

Lets's assume 2 concentric rectangles as:

outer_rect = [100, 100, 400, 400] # top, left, bottom, right
inner_rect = [200, 200, 300, 300]

Now create the binary mask using these rectangles as:

mask = np.zeros(image.shape[:2], dtype=np.uint8)
cv2.rectangle(mask, (outer_rect[0], outer_rect[1]), (outer_rect[2], outer_rect[3]), 255, -1)
cv2.rectangle(mask, (inner_rect[0], inner_rect[1]), (inner_rect[2], inner_rect[3]), 0, -1)

enter image description here

Now you may call the cv2.mean() to get the mean of foreground area, labelled with 255 as:

lena_mean = cv2.mean(image, mask)
>>> (109.98813432835821, 96.60768656716418, 173.57567164179105, 0.0)
like image 53
ZdaR Avatar answered Sep 19 '22 12:09

ZdaR