2016-12-26 139 views
1

我有一系列同心矩形,並希望獲得外部矩形(不包括內部矩形)的平均值。請參閱附圖,我需要了解陰影區域的含義。 enter image description here使用蒙版獲取圖像的平均值

所以我使用內部矩形的掩碼進入cv2.mean方法,但我不知道如何設置掩碼。我有以下代碼:

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_2means_3正常工作):

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

做一些調試即可。你傳遞給'bitwise_and'的兩個數組的大小是多少? (我認爲這是錯誤的來源,因爲你切斷了堆棧跟蹤)如果你沒有提供一個完整的,可重現的例子,沒有人可以爲你做。 –

回答

3

這裏的屏蔽是指具有0爲背景,255作爲二進制掩碼因此,您需要使用默認顏色= 0創建一個空白麪具,然後在255上繪製您想要查找平均值的感興趣區域。假設我有輸入圖像[512×512]:

enter image description here

讓我們假設2個同心矩形爲:

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

現在創建使用這些矩形作爲二元掩模:

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您可致電cv2.mean()得到前景區域的均值,標有255爲:

lena_mean = cv2.mean(image, mask) 
>>> (109.98813432835821, 96.60768656716418, 173.57567164179105, 0.0)