我一直试图制作一个OpenCV-Py程序,在鼠标点击和拖动时绘制矩形,直线和圆。我可以成功地为直线和矩形做这个但是圆圈的代码是错误的我需要帮助。


 import numpy as np
 import cv2 as cv
 import math
 drawing = False#true如果按下鼠标
 ix,iy = -1,-1
 #mouse callback function
 def draw_circle(event,x,y ,旗帜,PARAM):
全球ix,iy,drawing
 if event == cv.EVENT_LBUTTONDOWN:
 drawing = True
 ix,iy = x,y
 elif event == cv.EVENT_MOUSEMOVE:
如果drawing == True:
 k = cv.waitKey(33)

如果k == ord('r'):
 cv.rectangle(IMG,(IX,IY),(X,Y),(0,255,0), - 1)
 elif k == ord('c'):
 cv.circle(img,int(((ix + x)/ 2,(iy + y)/ 2)),int(math.sqrt(((ix-x)** 2)+((iy-y) ** 2))),(0,0,255), - 1)
 elif k == ord('l'):
 cv.line(IMG,(IX,IY),(X,Y),(255,0,0),5)
 elif event == cv.EVENT_LBUTTONUP:
 drawing = False
 img = np.zeros((512,512,3),np.uint8)
 cv.namedWindow('image')
 cv.setMouseCallback('image',draw_circle)&# XA;而(1):
 cv.imshow( '图像',张图片)
 k = cv.waitKey(1)&为0xFF
如果k == 27:
打破
 cv.destroyAllWindows()
 代码>


 

错误:回溯(最近一次呼叫最后):
在draw_circle
中输入第19行“mouse.py”。 cv.circle(img,int(((ix + x)/ 2,(iy + y)/ 2)),int(math.sqrt(((ix-x)** 2)+((iy-y) ** 2))),(0,0,255), - 1)
 TypeError:int()参数必须是字符串,类字节对象或数字,而不是'tuple'


答案 0 :(得分:0)
使用 OpenCV 动态绘制圆,
import numpy as np
import cv2
import math
drawing = False # true if mouse is pressed
ix,iy = -1,-1
# Create a function based on a CV2 Event (Left button click)
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
# we take note of where that mouse was located
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
drawing == True
elif event == cv2.EVENT_LBUTTONUP:
radius = int(math.sqrt( ((ix-x)**2)+((iy-y)**2)))
cv2.circle(img,(ix,iy),radius,(0,0,255), thickness=1)
drawing = False
# Create a black image
img = np.zeros((512,512,3), np.uint8)
# This names the window so we can reference it
cv2.namedWindow('image')
# Connects the mouse button to our callback function
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
# EXPLANATION FOR THIS LINE OF CODE:
# https://stackoverflow.com/questions/35372700/whats-0xff-for-in-cv2-waitkey1/39201163
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# Once script is done, its usually good practice to call this line
# It closes all windows (just in case you have multiple windows called)
cv2.destroyAllWindows()