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()