简体   繁体   English

如何使用 opencv 在图像上动态绘制一条线? [提供的代码,无法找出错误]

[英]How to dynamically draw a line on image using opencv? [code provided, can't figure out error]

In an attempt to draw dynamically on the image, I have written this script.为了尝试在图像上动态绘制,我编写了这个脚本。

  • Line should start when left mouse button is clicked.单击鼠标左键时应该开始行。
  • (With the left button clicked) as mouse is dragged the coordinates should be saved in real-time thus drawing a line (单击左键)拖动鼠标时,应实时保存坐标,从而绘制一条线

Following is the code I have written:以下是我编写的代码:

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)

Points are being printed correctly but I see no line being drawn.点正在正确打印,但我没有看到任何线条被绘制。 Can someone please figure out mistake?有人可以找出错误吗?

The problem seems to be in waitkey.问题似乎出在waitkey上。

You are calling cv2.imshow repeatedly but您正在反复调用 cv2.imshow 但

cv2.waitKey(0) looks for a keypress after which image will be updated. cv2.waitKey(0)查找将更新图像的按键。 so you are waiting indefinitely所以你无限期地等待

waitKey(1) will update image every 1 ms waitKey(1)将每 1 毫秒更新一次图像

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM