python - 在openCV中使用鼠标动态绘制圆圈
问题描述
我一直在尝试制作一个 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):
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 行,在 draw_circle 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() argument must be a string, a类似字节的对象或数字,而不是“元组”
解决方案
要使用 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()
推荐阅读
- php - 如何在没有 .php 文件扩展名的情况下使用 wordpress 获取 get_page_template_slug()?
- vb.net - VB.NET:C 中的指针和地址运算符 / 将 C 转换为 VB.NET
- c# - C# WFA - 将耗时的工作委托给另一个线程
- java - 使用杰克逊时,System.out.println(new ObjectMapper().readTree(jsonStringObject)); 在键和值之间打印带有随机空格的 JSON
- php - 使用 NoRewindIterator 实现 foreach 的正确方法
- django - Django可以在应用程序而不是模型上设置权限吗
- python - 我的素性检验的时间复杂度是多少?
- python - 在 python 中有效地连接许多大型 3 维数组
- oracle - Oracle - 从字符串值中删除起始零
- javascript - 节点流绕过管道