目标追踪中解决cv2.selectROI不能实时框选的问题

在做目标追踪过程中,有时间我们需要对视频流中的某一帧进行ROI的选择,这时间就要利用到cv2.selectROI,但是在框选过程中,背景图片并不会实时变化,这点目前还没有找到用opencv内置函数解决的方案,就自己写了一段鼠标监控的程序,可以供大家参考,以下就是opencv实现摄像头捕捉视频并进行实时追踪的例子。

import os
import glob
import cv2

cap = cv2.VideoCapture(0)
ret,img = cap.read()
print(img.shape)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter("out.avi",fourcc, 24, (img.shape[1],img.shape[0]))
if not cap.isOpened():
    print("Could not open video");exit(-1)
tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'GOTURN','MOSSE']
tracker_type=tracker_types[2]
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(minor_ver) < 3:
    tracker1 = cv2.Tracker_create(tracker_type)
else:
    if tracker_type == 'BOOSTING':
        tracker1 = cv2.TrackerBoosting_create()
    if tracker_type == 'MIL':
        tracker1 = cv2.TrackerMIL_create()
    if tracker_type == 'KCF':
        tracker1 = cv2.TrackerKCF_create()
    if tracker_type == 'TLD':
        tracker1 = cv2.TrackerTLD_create()
    if tracker_type == 'MEDIANFLOW':
        tracker1 = cv2.TrackerMedianFlow_create()
    if tracker_type == 'GOTURN':
        tracker1 = cv2.TrackerGOTURN_create()
    if tracker_type == 'MOSSE':
        tracker1 = cv2.TrackerGOTURN_create()

selection = None
track_window = None
drag_start = None

# 鼠标选框(做目标跟踪框)
def onmouse(event, x, y, flags, param):
    global selection,track_window,drag_start
    if event == cv2.EVENT_LBUTTONDOWN:
        drag_start = (x, y)
        track_window = None
    if drag_start:
        xmin = min(x, drag_start[0])
        ymin = min(y, drag_start[1])
        xmax = max(x, drag_start[0])
        ymax = max(y, drag_start[1])
        selection = (xmin, ymin, xmax, ymax)
    if event == cv2.EVENT_LBUTTONUP:
        drag_start = None
        track_window = selection
        selection = None

def main():
    track_window1 = ()
    cv2.namedWindow('image',1)
    cv2.setMouseCallback('image',onmouse)
    # We will track the frames as we load them off of disk
    # for k, f in enumerate(sorted(glob.glob(os.path.join(video_folder, "*.jpg")))):
    k=0
    while(1):
        ret, frame = cap.read()
        if not ret:
            print("Game over!")
            break
        print("Processing Frame {}".format(k))
        img_raw =frame #cv2.imread(f)
        image = img_raw.copy()

        # We need to initialize the tracker on the first frame
        if k == 0:
            # Start a track on the object you want. box the object using the mouse and press 'Enter' to start tracking
            while True:
                ret, image = cap.read()
                img_first = image.copy()
                if track_window:
                    cv2.rectangle(img_first,(track_window[0],track_window[1]),(track_window[2],track_window[3]),(0,0,255),1)
                elif selection:
                    cv2.rectangle(img_first,(selection[0],selection[1]),(selection[2],selection[3]),(0,0,255),1)
                if track_window1:
                    cv2.rectangle(img_first, (track_window1[0], track_window1[1]), (track_window1[2], track_window1[3]),
                                  (0, 255, 255), 1)

                cv2.imshow('image', img_first)
                if cv2.waitKey(10) == 32: # space
                    track_window1=list(track_window)
                    track_window1[2]=track_window1[2]-track_window1[0]
                    track_window1[3]=track_window1[3]-track_window1[1]
                    track_window1=tuple(track_window1)
                    k=2
                    tracker1.init(image,track_window1)
                    break


        else:
            # Else we just attempt to track from the previous frame
            status,box1_predict=tracker1.update(image)

            # Get previous box and draw on showing image
            cv2.rectangle(image, (int(box1_predict[0]), int(box1_predict[1])),
                          (int(box1_predict[0]+box1_predict[2]), int(box1_predict[1]+box1_predict[3])), (0, 255, 255), 3)
            cv2.putText(image, tracker_type, (150, 20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 255), 2)
            #cv2.putText(image, "standard", (5, 20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)
            cv2.imshow('image', image)
            out.write(image)
            # cv2.waitKey(10)
            c = cv2.waitKey(10) & 0xff
            if c == 27: break # ESC
            k+=1
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
import cv2 # 创建跟踪器对象 tracker = cv2.TrackerCSRT_create() # 打开视频文件 video = cv2.VideoCapture('plane.mp4') # 读取第一帧 ok, frame = video.read() # 选择要跟踪的目标区域 bbox = cv2.selectROI(frame, False) # 初始化跟踪器 ok = tracker.init(frame, bbox) while True: # 读取当前帧 ok, frame = video.read() if not ok: break # 跟踪目标 ok, bbox = tracker.update(frame) # 如果跟踪成功,绘制跟踪框和心点 if ok: # 获取跟踪框坐标 x, y, w, h = [int(i) for i in bbox] # 绘制跟踪框 cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # 计算心点坐标 center_x = x + w/2 center_y = y + h/2 # 绘制心点 cv2.circle(frame, (int(center_x), int(center_y)), 5, (0, 0, 255), -1) # 显示心点坐标 text = 'Center: ({:.1f}, {:.1f})'.format(center_x, center_y) cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2) # 特征点检测 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) detector = cv2.ORB_create() keypoints = detector.detect(gray, None) for kp in keypoints: x, y = kp.pt cv2.circle(frame, (int(x), int(y)), 3, (255, 0, 0), -1) cv2.putText(frame, 'Head', (int(x)-10, int(y)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) cv2.putText(frame, '({:.1f}, {:.1f})'.format(x, y), (int(x)-50, int(y)-30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) # 显示视频帧 cv2.imshow('Airplane Tracking', frame) # 等待按下 ESC 键退出 if cv2.waitKey(1) == 27: break # 释放资源 video.release() cv2.destroyAllWindows()将这段代码的特征点改为实时追踪画出飞机机头坐标并显示机头坐标
06-03
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值