有时我们在实际应用中会遇到要对 某个轮廓对象内的图像进行处理 时,我们需要把这部分图像单独提取出来,这是我们可以使用指定轮廓做图像剪切的 ROI
python opencv实现
def imgContoursROI():
"""使用查找到的轮廓生成ROI剪切图片中感兴趣区域"""
img = cv2.imread('GSYT01.JPG') # 载入图像
cv2.imshow("src", img)
copyImg=img.copy() #原图像的拷贝
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY) # 阈值化
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 寻找轮廓线
mask=np.zeros(img.shape, np.uint8) #原图大小的纯黑mask图像
draw=np.zeros(img.shape, np.uint8) #将原图 copyTo 到draw上,加上mask操作
temp=np.zeros(img.shape, np.uint8) #每次循环,重置mask 和 draw
i=0
for contour in contours: # 遍历所有轮廓
area = cv2.contourArea(contour) #轮廓图面积
B = 255
G = 255
R = 255 #生成颜色
mask=temp.copy()
draw=temp.copy()
if (area > 300) : #轮廓面积大于300的做 mask
cv2.drawContours(mask,[contour],-1,(B,G,R),cv2.FILLED)
ROIname='ROI{num}'.format(num=i)
ROI = cv2.bitwise_and(img, mask) #图形与mask 的 and 运算
cv2.imshow(ROIname, ROI)
i+=1
cv2.waitKey(0)
效果图: