如何使用opencv在python中对图像进行自由形状(随机)

时间:2016-04-03 04:41:30

标签: python opencv

要在区域中应用边界填充,我需要在python-opencv中使用鼠标绘制一个自由形状(随机)

2 个答案:

答案 0 :(得分:8)

您询问如何使用计算机的鼠标在图片上绘制任何给予者随机形状。这是一个简单的解决方案:

首先,您需要设计一个可以绘制的方法。因此,让我们从OpenCV: Mouse as a Paint-Brush启发自己,使用方法来使用鼠标绘制常见的常规形状,如圆形或矩形。在您的情况下,您将需要随意绘图,就像您可以用手一样。

因此,使用该方法,您可以使用鼠标绘制点,并使用interpolation方法在它们之间执行cv2.line()

cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)

im是您阅读的图像,而您必须始终记住鼠标位置的前坐标:

current_former_x = former_x
current_former_y = former_y

完整的OpenCV程序:

这是代码。不要犹豫,评论你不会理解的任何内容:

'''
Created on Apr 3, 2016

@author: Bill BEGUERADJ
'''
import cv2
import numpy as np 

drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve

# mouse callback function
def begueradj_draw(event,former_x,former_y,flags,param):
    global current_former_x,current_former_y,drawing, mode

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        current_former_x,current_former_y=former_x,former_y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
                current_former_x = former_x
                current_former_y = former_y
                #print former_x,former_y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
            current_former_x = former_x
            current_former_y = former_y
    return former_x,former_y    



im = cv2.imread("darwin.jpg")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',begueradj_draw)
while(1):
    cv2.imshow('Bill BEGUERADJ OpenCV',im)
    k=cv2.waitKey(1)&0xFF
    if k==27:
        break
cv2.destroyAllWindows()

演示:

enter image description here

答案 1 :(得分:2)

opencv示例目录中的此示例允许您在图像中绘制任意矩形并选择ROI:

https://github.com/Itseez/opencv/blob/master/samples/python/mouse_and_match.py

您可以轻松添加绘制圆或多边形的替代方法,例如先写一封信。