在OpenCV里实现不规则ROI的选取

有时候处理图像时,需要像画图软件一样,可以点击鼠标来选择不同的区域,这样选择的区域往往是不规则的图像,那么怎么样才可以在OpenCV里实现这样的功能呢?在这里要采用一点技巧,就是图像的像素与白色像素的与关系运算,任何颜色像素与白色像素作与运算都会只有这个像素的颜色,而与黑色像素运算就只剩下黑色。不规则的图形填充可以使用drawContours函数来实现。演示的例子如下:

#python 3.7.4,opencv4.1
#蔡军生 https://blog.csdn.net/caimouse/article/details/51749579
#[email protected]
#
import numpy as np
import cv2
from matplotlib import pyplot as plt

#读取图片
img = cv2.imread('szsj.jpg')
img1 = cv2.resize(img, (600, 400))
cv2.imshow("Original", img1)

#创建ROI图
roi = np.zeros(img1.shape, np.uint8)
#设置选择范围
contour = np.array([(30,30),(300,30),(200,300)])
#填充为白色
cv2.drawContours(roi, [contour], 0, (255,255,255),thickness=cv2.FILLED)
cv2.imshow('roi', roi)
#进行与操作,留下白色区域像素
res = cv2.bitwise_and(img1, roi)
cv2.imshow('res', res)

#
cv2.waitKey(0)
cv2.destroyAllWindows()
 

结果输出如下:

猜你喜欢

转载自blog.csdn.net/caimouse/article/details/103287318