有几种方法可以做到这一点,所以我将从最简单和最快,到更灵活和更慢......
最简单和最快的,如果你的蒙面区域和你一样简单:
import cv2
import numpy as np
# Load Paddington as greyscale
img = cv2.imread('paddington.png',0)
# Define a region of interest, in this case entire rows 100-300
ROI = slice(100,300)
# Threshold the region of interest, and reinsert back into image
ret,img[ROI] = cv2.threshold(img[ROI],127,255,cv2.THRESH_BINARY)
请注意,我仅在一个地方将 ROI 声明为变量,因此如果您更改掩码的大小,等号的两边都保持正确 - 避免维护问题!
如果您的遮罩区域不是整行,您可以创建一个切片元组:
# Declare ROI
ROI = slice(100,300),slice(10,390)
# Threshold with mask
ret,img[ROI] = cv2.threshold(img[ROI],127,255,cv2.THRESH_BINARY)
如果您的蒙版区域更复杂,例如复合形状、轮廓或圆形,您仍然可以只对感兴趣的蒙版区域设置阈值!首先,您创建一个相同大小的填充黑色的蒙版,然后用白色绘制您的形状,然后将阈值应用于蒙版的感兴趣区域:
# Make a mask the same size as the image and fill with black
mask = np.zeros_like(img)
# Draw a filled white circle onto the black mask to define a region of interest
mask = cv2.circle(mask,(200,100),100,255,-1) # -1 to fill inside circle
ROI = np.nonzero(mask)
# Threshold the region of interest, and reinsert back into image
ret, mask_thresholded = cv2.threshold(img[ROI],127,255,cv2.THRESH_BINARY)
img[ROI] = mask_thresholded.reshape(-1)
这是年轻流氓的原始图像:
关键词:Python、OpenCV、Numpy、图像、图像处理、掩码、掩码、阈值、过滤器、ROI、感兴趣区域