python实现单目标、多目标、多尺度、自定义特征的实现单目标、多目标、多尺度、自定义特征的KCF跟踪跟踪
算法算法(实例代码实例代码)
主要介绍了python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法,本文通过实例代码给大家介绍的
非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
单目标跟踪:
直接调用opencv中封装的tracker即可。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 5 17:50:47 2020
第四章 kcf跟踪
@author: youxinlin
"""
import cv2
from items import MessageItem
import time
import numpy as np
'''
监视者模块,负责入侵检测,目标跟踪
'''
class WatchDog(object):
#入侵检测者模块,用于入侵检测
def __init__(self,frame=None):
#运动检测器构造函数
self._background = None
if frame is not None:
self._background = cv2.GaussianBlur(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY),(21,21),0)
self.es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
def isWorking(self):
#运动检测器是否工作
return self._background is not None
def startWorking(self,frame):
#运动检测器开始工作
if frame is not None:
self._background = cv2.GaussianBlur(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), (21, 21), 0)
def stopWorking(self):
#运动检测器结束工作
self._background = None
def analyze(self,frame):
#运动检测
if frame is None or self._background is None:
return
sample_frame = cv2.GaussianBlur(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY),(21,21),0)
diff = cv2.absdiff(self._background,sample_frame)
diff = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
diff = cv2.dilate(diff, self.es, iterations=2)
image, cnts, hierarchy = cv2.findContours(diff.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
coordinate = []
bigC = None
bigMulti = 0
for c in cnts:
if cv2.contourArea(c) < 1500:
continue
(x,y,w,h) = cv2.boundingRect(c)
if w * h > bigMulti:
bigMulti = w * h
bigC = ((x,y),(x+w,y+h))
if bigC:
cv2.rectangle(frame, bigC[0],bigC[1], (255,0,0), 2, 1)
coordinate.append(bigC)
message = {"coord":coordinate}
message['msg'] = None
return MessageItem(frame,message)
class Tracker(object):
'''
追踪者模块,用于追踪指定目标
'''
def __init__(self,tracker_type = "BOOSTING",draw_coord = True):
'''
初始化追踪器种类
'''
#获得opencv版本
(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
评论1