我建议使用Contours提取您感兴趣的区域(您想要的任何形状).
请参阅此文档:
Drawing Contours
您的方法应如下:
>通过将MouseEventListener附加到Window,在图像本身上标记构成坐标的点.
>使用创建蒙版图像. (全零)
>使用这些坐标集,使用cv2.drawContours()方法绘制蒙版图像所需的形状,并用白色填充(255).
>使用原始灰度图像执行Bitwise_And操作.
示例代码:
#Function
def on_mouse(event, x, y, flags,(cPts,overlayImage,resetImage)):
if event==cv.CV_EVENT_LBUTTONUP:
cPts[0].append([x,y])
cv2.circle(overlayImage,(x,y),5,(255),-1)
elif event==cv.CV_EVENT_RBUTTONUP:
cPts[0]=[]
print cPts
overlayImage[:]=resetImage[:]
#Main Program
cvImage=cv2.imread(inputImageFilePath)
grayscaleImage=cv2.cvtColor(cvImage,cv.CV_BGR2GRAY)
overlayImage=np.copy(grayscaleImage)
cv2.namedWindow('preview')
cPts=[[]]
cv2.setMouseCallback('preview',on_mouse,(cPts,overlayImage,grayscaleImage))
opacity=0.4
while True:
displayImage=cv2.addWeighted(overlayImage,opacity,grayscaleImage,1-opacity,0)
cv2.imshow('preview',displayImage)
keyPressed=cv2.waitKey(5)
if keyPressed==27:
break
elif keyPressed==32:
print cPts
cv2.drawContours(overlayImage,np.array(cPts),0,255)
maskImage=np.zeros_like(grayscaleImage)
cv2.drawContours(maskImage,np.array(cPts),0,255,-1)
extractedImage=np.bitwise_and(grayscaleImage,maskImage)
cv2.imshow('extractedImage',extractedImage)
cv2.destroyAllWindows()