Python 在openCV中使用鼠标动态绘制圆
我一直在尝试制作一个OpenCV Py程序,通过鼠标点击和拖动来绘制矩形、直线和圆。我可以成功地为直线和矩形这样做,但圆的代码是错误的,我需要帮助Python 在openCV中使用鼠标动态绘制圆,python,numpy,opencv,image-processing,Python,Numpy,Opencv,Image Processing,我一直在尝试制作一个OpenCV Py程序,通过鼠标点击和拖动来绘制矩形、直线和圆。我可以成功地为直线和矩形这样做,但圆的代码是错误的,我需要帮助 import numpy as np import cv2 as cv import math drawing = False # true if mouse is pressed ix,iy = -1,-1 # mouse callback function def draw_circle(event,x,y,flags,param): g
import numpy as np
import cv2 as cv
import math
drawing = False # true if mouse is pressed
ix,iy = -1,-1
# mouse callback function
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
k = cv.waitKey(33)
if 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)
while(1):
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
cv.destroyAllWindows()
错误:回溯(最近一次呼叫上次):
文件“mouse.py”,第19行,在画圈中
等速圆(img,int((ix+x)/2,(iy+y)/2)),int(数学sqrt((ix-x)**2)+(iy-y)**2)),(0,0255),-1)
TypeError:int()参数必须是字符串、类似字节的对象或数字,而不是“tuple”
要使用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()
试试(int((ix+x)/2),int((iy+y)/2))而不是int((ix+x)/2,(iy+y)/2)),谢谢:)它奏效了。