python选择摄像头目标实时跟踪效果代码

代码语言:python

所属分类:其他

代码描述:python选择摄像头目标实时跟踪效果代码,先框选摄像头中指定的目标,然后就会自动跟踪了。

代码标签: python 选择 摄像头 目标 实时 跟踪

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

#!/usr/local/python3/bin/python3
# -*- coding: utf-8 -*
import cv2
import numpy as np
import time

def create_tracker(tracker_type):
    tracker_types = {
        'KCF': cv2.TrackerKCF_create,
        'CSRT': cv2.TrackerCSRT_create,
        'MOSSE': cv2.legacy.TrackerMOSSE_create,
    }
    return tracker_types[tracker_type]()

class ObjectTracker:
    def __init__(self):
        self.cap = cv2.VideoCapture(0)
        self.tracker_type = 'KCF'
        self.tracker = None
        self.bbox = None
        self.fps = 0
        self.prev_time = 0
        
    def select_roi(self, frame):
        cv2.putText(frame, "Select target ROI and press SPACE or ENTER", 
                    (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
        self.bbox = cv2.selectROI("Tracking", frame, False)
        self.tracker = create_tracker(self.tracker_type)
        self.tracker.init(frame, self.bbox)
        
    def calculate_fps(self):
        current_time = time.time()
        self.fps = 1 / (current_time - self.prev_time)
        self.prev_time = current_time
        return self.fps
        
    def draw_info(self, frame, tracking_success):
        # 显示FPS
        cv2.putText(frame, f"FPS: {int(self.fps)}", 
                    (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
        
        # 显示跟踪器类型
        cv2.putText(frame, f"Tracker: {self.tracker_type}", 
                    (20, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
        
        # 显示操作提示
        cv2.putText(frame, "Press 'r': Reset ROI", 
                    (20, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
        cv2.putText(frame, "Press 't': Change Tracker", 
                    (20, 120), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2)
        
        if not tracking_success:
            cv2.putText(frame, "Tracking failure detected", 
                        (20, 150), .........完整代码请登录后点击上方下载按钮下载查看

网友评论0