OpenCV-Python实现物体追踪(附源码)

2021/5/24 12:27:24

本文主要是介绍OpenCV-Python实现物体追踪(附源码),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

OpenCV杂谈_08


一. 需要做的前期准备

  1. 环境配置:
    Python版本:3.9.0
    功能包:opencv-python(4.5.2.52)、math(自带)
  2. 一段提前录制好的用于物体检测、追踪的视频(要求:摄像头是保持静止不动的)
  3. 一个用的顺手的IDE(本人推荐Pycharm)

二. 源码如下

  1. main.py 文件
import cv2
from tracker import *

# 进行追踪
tracker = EuclideanDistTracker()  # 这个函数通过获取同一物体不同时刻的boundingbox的坐标从而实现对其的追踪

# 导入想要进行tracking的视频,要求拍摄视频的过程中摄像头是保持静止状态的
cap = cv2.VideoCapture("highway.mp4")

# 从导入的视频中找到正在移动的物体
object_detector = cv2.createBackgroundSubtractorMOG2(history=100, varThreshold=40)  # 对参数进行调整则会改变捕捉移动物体的精准性

while True:
    ret, frame = cap.read()
    height, width, _ =frame.shape  # 得出视频画面的大小,从而去方便计算出感兴趣区域所在的位置
    print(height, width)  # 720,1280

    # 设置一个感兴趣区域,让处理(对物体的detection和tracking)只关注于感兴趣区域,从而减少一些计算量也让检测变得简单一些
    roi = frame[340: 720, 500: 800]

    # 物体检测
    mask = object_detector.apply(roi)  # 通过加一个蒙版,更加清晰的显示出移动中的物体,即只留下白色的移动的物体。
    _, mask = cv2.threshold(mask, 254, 255, cv2.THRESH_BINARY)  # 去除移动物体被检测到的时候所附带的阴影(阴影为灰色)
    contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)  # 找到视频中物体的轮廓
    detections = []  # 用于存放boundingbox的起始点坐标、宽、高
    for cnt in contours:
        # 计算出每个轮廓内部的面积,并根据面积的大小去除那些不必要的噪声(比如树、草等等)
        area = cv2.contourArea(cnt)
        if area > 100:
            # cv2.drawContours(roi, [cnt], -1, (0, 255, 0), 2)  # 画出移动物体的轮廓
            x, y, w, h = cv2.boundingRect(cnt)
            detections.append([x, y, w, h])


    # 物体追踪
    boxer_ids = tracker.update(detections)  # 同一个物体会有相同的ID
    # print(boxer_ids)
    for box_id in boxer_ids:
        x, y, w, h, id = box_id
        cv2.putText(roi, "Obj" + str(id), (x, y - 15), cv2.FONT_ITALIC, 0.7, (255, 0, 0), 2)
        cv2.rectangle(roi, (x, y), (x + w, y + h), (0, 255, 0), 2)  # 根据移动物体的轮廓添加boundingbox

    print(detections)
    cv2.imshow("Frame", frame)  # 打印结果
    # cv2.imshow("Mask", mask)  # 打印出蒙版
    # cv2.imshow("ROI", roi)  # 打印出你想要的ROI在哪
    key = cv2.waitKey(30)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()
  1. tracker.py文件
import math


class EuclideanDistTracker:
    def __init__(self):
        # Store the center positions of the objects
        self.center_points = {}
        # Keep the count of the IDs
        # each time a new object id detected, the count will increase by one
        self.id_count = 0


    def update(self, objects_rect):
        # Objects boxes and ids
        objects_bbs_ids = []

        # Get center point of new object
        for rect in objects_rect:
            x, y, w, h = rect
            cx = (x + x + w) // 2
            cy = (y + y + h) // 2

            # Find out if that object was detected already
            same_object_detected = False
            for id, pt in self.center_points.items():
                dist = math.hypot(cx - pt[0], cy - pt[1])

                if dist < 25:
                    self.center_points[id] = (cx, cy)
                    print(self.center_points)
                    objects_bbs_ids.append([x, y, w, h, id])
                    same_object_detected = True
                    break

            # New object is detected we assign the ID to that object
            if same_object_detected is False:
                self.center_points[self.id_count] = (cx, cy)
                objects_bbs_ids.append([x, y, w, h, self.id_count])
                self.id_count += 1

        # Clean the dictionary by center points to remove IDS not used anymore
        new_center_points = {}
        for obj_bb_id in objects_bbs_ids:
            _, _, _, _, object_id = obj_bb_id
            center = self.center_points[object_id]
            new_center_points[object_id] = center

        # Update dictionary with IDs not used removed
        self.center_points = new_center_points.copy()
        return objects_bbs_ids

三. 结果展示

四. 感悟与分享

  1. 可以看出来由于物体的检测方法是根据视频中谁在运动而进行挑选的,因此在准确度上有些许问题且无法获得物体的分类信息,而且为了减少计算量而设置了ROI区域,而并非是全画面的物体检测与追踪。未来如果想实现相对高精度的检测与追踪,则需要调用Cascade文件来进行物体检测,从而实现较高精度的且附带分类信息的识别、追踪结果。
  2. 参考课程及推荐:https://www.youtube.com/watch?v=O3b8lVF93jU(内容为英文,且需要翻墙)

如有问题,敬请指正。欢迎转载,但请注明出处。


这篇关于OpenCV-Python实现物体追踪(附源码)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程