python 鼠标 画框 打印坐标位置 高宽
1 #!/usr/bin/python 2 # -*- coding: utf-8 -*- 3 # @Time : 2021/8/22 22:28 4 # @Author : yangdj 553849374@qq.com 5 # @File : img_draw_rectangle.py 6 # @Software: PyCharm 7 # 在图片中选取roi并用鼠标画出矩形框 8 9 import cv2 10 11 img = cv2.imread(r"F:\python\pytool-httpapi\static\upload\temp_files\2021-08-21\0a5f89c640124aa4b1659ade7a5e0c29.jpg") 12 13 drawing = False 14 ix, iy = -1, -1 15 tempFlag = False 16 17 18 def draw_circle(event, x, y, flags, param): 19 global ix, iy, drawing, mode, cap, template, tempFlag 20 if event == cv2.EVENT_LBUTTONDOWN: 21 tempFlag = True 22 drawing = True 23 ix, iy = x, y # 按下鼠标左键,用全局变量ix,iy记录下当前坐标点 24 elif event == cv2.EVENT_LBUTTONUP: 25 if drawing == True: 26 drawing = False # 鼠标左键抬起,画出矩形框 27 cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 1) 28 template = img[iy:y, ix:x, :] # 截取框中的目标图像 29 # 打印两个点的坐标,和最终原点+宽和高 30 print((ix, iy), (x, y), f'{ix},{iy},{x - ix},{y - iy}') 31 # cap = cv2.VideoCapture(-1) #打开摄像头 32 # cv2.imshow('img', img) # 显示画框后的图像 33 cv2.imshow('template', template) 34 35 36 cv2.namedWindow("image") 37 cv2.setMouseCallback("image", draw_circle) 38 cv2.imshow("image", img) 39 40 while (True): 41 try: 42 cv2.waitKey(100) 43 except Exception: 44 cv2.destroyAllWindows() 45 break 46 47 cv2.waitKey(0) 48 cv2.destroyAllWindows()