gpt4 book ai didi

python - OpenCV:如何用鼠标连续绘制?

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:31 24 4
gpt4 key购买 nike

我修改了一个取自 OpenCV 文档的简单程序。

我只是想连续使用鼠标指针绘图。目前我成功绘制了,但不是连续绘制,除非我移动鼠标光标的速度太慢。

代码:

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 interactive_drawing(event,x,y,flags,param):
global ix,iy,drawing, mode

if event==cv2.EVENT_LBUTTONDOWN:
drawing=True
ix,iy=x,y

elif event==cv2.EVENT_MOUSEMOVE:
if drawing==True:
if mode==True:
cv2.circle(img,(x,y),1,(0,0,255),-1)
elif event==cv2.EVENT_LBUTTONUP:
drawing=False
if mode==True:
cv2.circle(img,(x,y),1,(0,0,255),-1)


img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('Window')
cv2.setMouseCallback('Window',interactive_drawing)
while(1):
cv2.imshow('Window',img)
k=cv2.waitKey(1)&0xFF
if k==27:
break
cv2.destroyAllWindows()

希望这张截图能解释我的问题:细线看起来是连续的,因为我必须移动鼠标光标太慢。较长的线不是连续的,因为我必须以正常速度移动光标:

enter image description here

我希望能够像这样连续画画:

enter image description here

任何人都可以展示如何解决这个问题?提前谢谢你。

最佳答案

试试这个:

import cv2
import numpy as np

drawing = False # true if mouse is pressed
pt1_x , pt1_y = None , None

# mouse callback function
def line_drawing(event,x,y,flags,param):
global pt1_x,pt1_y,drawing

if event==cv2.EVENT_LBUTTONDOWN:
drawing=True
pt1_x,pt1_y=x,y

elif event==cv2.EVENT_MOUSEMOVE:
if drawing==True:
cv2.line(img,(pt1_x,pt1_y),(x,y),color=(255,255,255),thickness=3)
pt1_x,pt1_y=x,y
elif event==cv2.EVENT_LBUTTONUP:
drawing=False
cv2.line(img,(pt1_x,pt1_y),(x,y),color=(255,255,255),thickness=3)


img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('test draw')
cv2.setMouseCallback('test draw',line_drawing)

while(1):
cv2.imshow('test draw',img)
if cv2.waitKey(1) & 0xFF == 27:
break
cv2.destroyAllWindows()

关于python - OpenCV:如何用鼠标连续绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28340950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com