Practical Python and OpenCV,3rd Edition 07
MASKING
接下来我们看一下masking technique。
使用mask可以让我们只关注我们感兴趣的图像部分。
例如,假设我们正在建立一个识别面部的计算机视觉系统。我们有兴趣查找和描述的图像的唯一部分是包含面部的图像部分——我们根本不关心图像的其余内容。如果我们可以在图像中找到面部,我们可以构造一个mask来仅显示图像中的面部。
新建一个masking.py
# Import the necessary packages
import numpy as np
import argparse
import cv2
# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
help = "Path to the image")
args = vars(ap.parse_args())
# Load the image and show it
image = cv2.imread(args["image"])
cv2.imshow("Original", image)
上面读取并显示原始图片,接下来我们构造一个NumPy数组,填充零,与我们的图像具有相同的宽度和高度。为了绘制白色矩形,我们首先通过划分宽度和高度来计算图像的中心,使用//运算符表示整数除法。最后,我们使用cv2.rectangle函数画出白色矩形。
# Masking allows us to focus only on parts of an image that
# interest us. A mask is the same size as our image, but has
# only two pixel values, 0 and 255. Pixels with a value of 0
# are ignored in the orignal image, and mask pixels with a
# value of 255 are allowed to be kept. For example, let's
# construct a mask with a 150x150 square at the center of it
# and mask our image.
mask = np.zeros(image.shape[:2], dtype = "uint8")
(cX, cY) = (image.shape[1] // 2, image.shape[0] // 2)
cv2.rectangle(mask, (cX - 75, cY - 75), (cX + 75 , cY + 75), 255, -1)
cv2.imshow("Mask", mask)
我们使用cv2.bitwise_and函数应用我们的mask。前两个参数是图像本身。显然,对于图像中的所有像素,AND功能将为True。但是,此函数的重要部分是mask关键字参数。通过提供mask,cv2.bitwise_and函数仅检查mask中“on”的像素。在这种情况下,只有矩形白色区域是显示出来的。
# Apply out mask -- notice how only the center rectangular
# region of the pill is shown
masked = cv2.bitwise_and(image, image, mask = mask)
cv2.imshow("Mask Applied to Image", masked)
cv2.waitKey(0)
接下来,我们重新初始化我们的蒙版,用零填充与图像相同的尺寸。然后,我们在mask image上绘制一个白色圆圈,从图像的中心开始,半径为100像素。然后再次使用cv2.bitwise_and函数应用圆形mask。
# Now, let's make a circular mask with a radius of 100 pixels
mask = np.zeros(image.shape[:2],dtype="uint8")
cv2.circle(mask,(cX,cY),100,255,-1)
masked = cv2.bitwise_and(image,image,mask=mask)
cv2.imshow("Mask",mask)
cv2.imshow("Mask Applied to Image",masked)
cv2.waitKey(0)
显示效果:


用到的函数
cv2.bitwise_and
cv2.ractangle
cv2.circle
更多的参考:
PPaO Chapter 6 – Image Processing
;