如何使用opencv在图像上动态画一条线? [提供的代码,无法找出错误]
Posted
技术标签:
【中文标题】如何使用opencv在图像上动态画一条线? [提供的代码,无法找出错误]【英文标题】:How to dynamically draw a line on image using opencv? [code provided, can't figure out error] 【发布时间】:2021-05-18 03:10:34 【问题描述】:为了尝试在图像上动态绘制,我编写了这个脚本。
点击鼠标左键时应该开始行。 (单击左键)鼠标拖动时,坐标应实时保存,从而绘制一条线以下是我写的代码:
import numpy as np
import cv2
from absl import app, flags
import imutils
FLAGS = flags.FLAGS
flags.DEFINE_string('img', './image.jpg',
'PATH TO THE IMAGE ON WHICH LINES NEED TO BE DRAWN')
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
def main(argv):
def draw_line(event, x, y, flags, param):
global ix, iy, DRAW, xx, yy
# DRAW = False
if event == cv2.EVENT_LBUTTONDOWN:
DRAW = True
# save the coordinates of start
ix , iy = x , y
print(f"CLICKED AT X->ix,Y->iy")
elif event == cv2.EVENT_MOUSEMOVE:
#if DRAW != None:
if DRAW == True:
# if mouse moves, previous coodinates have been saved in ix, iy
# new dynamic coordinates will be in x,y
print(f"LINE : X->ix,Y->iy---------------->X->x,Y->y")
cv2.line(img, (ix, iy), (x, y), color=(0,0,255),thickness= 15, lineType=cv2.LINE_AA )
xx = x
yy = y
elif event == cv2.EVENT_LBUTTONUP:
# discard the previous coordinates
DRAW = False
print(f"PTS were : ix,iy--->xx,yy")
img = cv2.imread(FLAGS.img)
img = imutils.resize(img, width=1500)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_line)
while True:
cv2.imshow('image', img)
k = cv2.waitKey(0) & 0xFF
if k ==ord('q'):
break
cv2.destroyAllWindows()
if __name__=='__main__':
app.run(main)
点打印正确,但我没有看到任何线条。有人可以找出错误吗?
【问题讨论】:
【参考方案1】:问题似乎出在waitkey上。
您正在反复调用 cv2.imshow,但是
cv2.waitKey(0)
查找将更新图像的按键。所以你无限期地等待
waitKey(1)
将每 1 毫秒更新一次图像
【讨论】:
以上是关于如何使用opencv在图像上动态画一条线? [提供的代码,无法找出错误]的主要内容,如果未能解决你的问题,请参考以下文章