简体   繁体   中英

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.

You are calling cv2.imshow repeatedly but

cv2.waitKey(0) looks for a keypress after which image will be updated. so you are waiting indefinitely

waitKey(1) will update image every 1 ms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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