簡體   English   中英

如何使用 opencv 在圖像上動態繪制一條線? [提供的代碼,無法找出錯誤]

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

為了嘗試在圖像上動態繪制,我編寫了這個腳本。

  • 單擊鼠標左鍵時應該開始行。
  • (單擊左鍵)拖動鼠標時,應實時保存坐標,從而繪制一條線

以下是我編寫的代碼:

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)

點正在正確打印,但我沒有看到任何線條被繪制。 有人可以找出錯誤嗎?

問題似乎出在waitkey上。

您正在反復調用 cv2.imshow 但

cv2.waitKey(0)查找將更新圖像的按鍵。 所以你無限期地等待

waitKey(1)將每 1 毫秒更新一次圖像

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM