opencv 在视频/流播放时选择ROI

bweufnob  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(82)

如果有人能帮我在视频流播放时选择一个ROI,我将不胜感激(我不希望它暂停或捕获第一帧)。我错过了什么吗?我试着把框架设置为相同的名称。

cv2.selectROI('Frame', frame, False)
cv2.imshow('Frame',frame)

字符串

ruoxqz4g

ruoxqz4g1#

在这种情况下不能使用cv2.selectROI(),因为函数是阻塞的,即它会停止执行你的程序,直到你选择了你感兴趣的区域(或取消它)。
为了实现您想要的目标,您需要自己处理ROI的选择。这里有一个简短的例子,你可以如何做到这一点,使用两个左键单击定义ROI和右键单击删除它。

import cv2, sys

cap = cv2.VideoCapture(sys.argv[1])
cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)

# Our ROI, defined by two points
p1, p2 = None, None
state = 0

# Called every time a mouse event happen
def on_mouse(event, x, y, flags, userdata):
    global state, p1, p2
    
    # Left click
    if event == cv2.EVENT_LBUTTONUP:
        # Select first point
        if state == 0:
            p1 = (x,y)
            state += 1
        # Select second point
        elif state == 1:
            p2 = (x,y)
            state += 1
    # Right click (erase current ROI)
    if event == cv2.EVENT_RBUTTONUP:
        p1, p2 = None, None
        state = 0

# Register the mouse callback
cv2.setMouseCallback('Frame', on_mouse)

while cap.isOpened():
    val, frame = cap.read()
    
    # If a ROI is selected, draw it
    if state > 1:
        cv2.rectangle(frame, p1, p2, (255, 0, 0), 10)
    # Show image
    cv2.imshow('Frame', frame)
    
    # Let OpenCV manage window events
    key = cv2.waitKey(50)
    # If ESCAPE key pressed, stop
    if key == 27:
        cap.release()

字符串

相关问题