opencv-python本身有个cv2.selectROI函数用于选择矩形区域ROI,但在只能用于静态图像中,在视频中会卡死。只能自定义实现了。
import cv2
def OnMouseAction(event, x, y, flags, param):
global img, position1, position2
if event == cv2.EVENT_LBUTTONDOWN: #按下左键
position1 = (x,y)
position2 = None
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON: #按住左键拖曳不放开
position2 = (x,y)
elif event == cv2.EVENT_LBUTTONUP: #放开左键
position2 = (x,y)
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
cv2.namedWindow('image')
cv2.setMouseCallback('image', OnMouseAction)
position1 = None
position2 = None
img = None
while(1):
ret, img = cap.read()
if ret:
if position1 != None and position2 != None:
cv2.rectangle(img, position1, position2, (0,0,255), 1,4)
cv2.imshow('image', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()