使用蒙版获取图像的平均值 [英] Getting mean of an image using a mask

查看:23
本文介绍了使用蒙版获取图像的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列同心矩形,并希望获得外部矩形排除内部矩形的手段.见附图,我需要得到阴影区域的平均值.

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.

所以我使用内部矩形的掩码传递给 cv2.mean 方法,但我不确定如何设置掩码.我有以下代码:

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

means_2 出现此错误(means_3 工作正常).:

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

错误:/Users/jenkins/miniconda/0/2.7/conda-bld/work/opencv-2.4.11/modules/core/src/arithm.cpp:1021:错误:(-209)该操作既不是数组操作数组"(其中数组具有相同的大小和类型),也不是数组操作标量",也不是标量操作"函数 binary_op 中的数组'

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

推荐答案

这里的掩码是指以0为背景,255为前景的二进制掩码,所以您需要创建一个默认颜色 = 0 的空蒙版,然后使用 255 绘制要查找均值的感兴趣区域.假设我有输入图像 [512 x 512]:

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]:

让我们假设 2 个同心矩形为:

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)

现在你可以调用 cv2.mean() 来获取前景区域的平均值,用 255 标记为:

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)

这篇关于使用蒙版获取图像的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆