在Python OpenCV

时间:2016-08-31 08:31:22

标签: python opencv drawing

我的问题是参考this tutorial。 在上面的教程中,每当我们拖动鼠标指针时,都会绘制一个恒定半径的圆(即5个像素)。

我想绘制一个圆,半径等于鼠标左键拖动的距离。还想在左按钮关闭后移动鼠标指针时显示预览。与MS Paint中发生的情况类似。

import cv2
import numpy as np

drawing=False
mode=True   # True--> Rectangle , False --> Circle

ix,iy=-1,-1

def draw_fig(event,x,y,flags,param):
    global ix,iy,drawing,mode,img

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        ix,iy=x,y
        if(not mode):#ie. Drawing Mode==Circle
            backup=img

    elif event==cv2.EVENT_MOUSEMOVE:
        if (drawing):
            if(mode):
                cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1)
            else:
                #Resetting Canvas
                #img=np.zeros((512,512,3),np.uint8)
                #cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
                #Showing Circle Preview
                cv2.circle(backup,(x,y),max(abs(ix-x),abs(iy-y)),(0,0,255),-1)

    elif event==cv2.EVENT_LBUTTONUP:
        if(drawing):
            drawing=False
            if(mode):
                cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1)
            else:
                #Resetting Canvas
                img=np.zeros((512,512,3),np.uint8)
                cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
                #Showing Circle Preview
                cv2.circle(backup,(x,y),max(abs(ix-x),abs(iy-y)),(0,0,255),-1)
                img=backup

img=np.zeros((512,512,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_fig)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)

while(1):
    cv2.imshow('image',img)
    k=cv2.waitKey(1)
    if(k==ord('m')):
        mode=not mode
    elif k==27:
        break
    elif k==ord('r'):
        img=np.zeros((512,512,3),np.uint8)
        cv2.putText(img,'Sankalp',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)

cv2.destroyAllWindows()

但是它显示了一个错误:

  

UnboundLocalError:之前引用的局部变量'backup'   分配

任何人都可以告诉我我做错了什么以及任何其他方法来实现这个目标吗?

0 个答案:

没有答案