在圖片中選取roi並用鼠標畫出矩形框python


 1 # 在圖片中選取roi並用鼠標畫出矩形框
 2 import cv2
 3 img = cv2.imread("left0.jpg")
 4 
 5 
 6 drawing = False
 7 ix, iy = -1, -1
 8 tempFlag = False
 9 def draw_circle(event, x, y, flags, param):
10     global ix, iy, drawing, mode, cap, template, tempFlag
11     if event == cv2.EVENT_LBUTTONDOWN:
12         tempFlag = True
13         drawing = True
14         ix, iy = x, y                        #按下鼠標左鍵,用全局變量ix,iy記錄下當前坐標點
15     elif event == cv2.EVENT_LBUTTONUP:
16         if drawing == True:
17             drawing = False                  #鼠標左鍵抬起,畫出矩形框
18             cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 1)
19             template = img[iy:y, ix:x, :]  #截取框中的目標圖像
20             print(ix,iy,x,y)
21             #cap = cv2.VideoCapture(-1)       #打開攝像頭
22             cv2.imshow('img', img)         #顯示畫框后的圖像
23             cv2.imshow('template',template)
24 
25 
26 cv2.namedWindow("image")
27 cv2.setMouseCallback("image", draw_circle)
28 cv2.imshow("image", img)
29 
30 while (True):
31     try:
32         cv2.waitKey(100)
33     except Exception:
34         cv2.destroyAllWindows()
35         break
36 
37 cv2.waitKey(0)
38 cv2.destroyAllWindows()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM