numpy中掩膜mask的使用(转)

【时间】2019.03.23

【题目】numpy中掩膜mask的使用(转)

1、OpenCV之bitwise_and、bitwise_not等图像基本运算及掩膜 中提到了cv2.bitwise_and的使用,具体用法如下:

使用掩模
要统计图像某个局部区域的直方图只需要构建一副掩模图像。将要统计的部分设置成白色,其余部分为黑色,就构成了一副掩模图像。然后把这个掩模图像传给函数就可以了。

img = cv2.imread('home.jpg',0)

# create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv2.bitwise_and(img,img,mask = mask)

# Calculate histogram with mask and without mask
# Check third argument for mask
hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv2.calcHist([img],[0],mask,[256],[0,256])

plt.subplot(221), plt.imshow(img, 'gray')
plt.subplot(222), plt.imshow(mask,'gray')
plt.subplot(223), plt.imshow(masked_img, 'gray')
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
plt.xlim([0,256])

plt.show()

结果如下,其中蓝线是整幅图像的直方图,绿线是进行掩模之后的直方图。
    numpy中掩膜mask的使用(转)

 

2、Python(9) Numpy, mask图像的生成中提到了使用numpy.ma库进行掩膜运算