天天看點

opencv-python 視訊滑鼠動态選擇矩形區域ROI

opencv-python本身有個cv2.selectROI函數用于選擇矩形區域ROI,但在隻能用于靜态圖像中,在視訊中會卡死。隻能自定義實作了。

opencv-python 視訊滑鼠動态選擇矩形區域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()