OpenCV(七)实现对视频中任意目标的追踪

一、目标

给定一段视频,实现对视频中一个或者多个目标的追踪。

二、利用OpenCV的kcf算法实现

配置需要的参数:video和tracker追踪算法

ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", type=str,
	help="path to input video file")
ap.add_argument("-t", "--tracker", type=str, default="kcf",
	help="OpenCV object tracker type")
args = vars(ap.parse_args())

将一些算法写入字典方便调用

OPENCV_OBJECT_TRACKERS = {
	"csrt": cv2.TrackerCSRT_create,
	"kcf": cv2.TrackerKCF_create,
	"boosting": cv2.TrackerBoosting_create,
	"mil": cv2.TrackerMIL_create,
	"tld": cv2.TrackerTLD_create,
	"medianflow": cv2.TrackerMedianFlow_create,
	"mosse": cv2.TrackerMOSSE_create
}

实例化OpenCV’s multi-object tracker多目标追踪方法,读入视频

trackers = cv2.MultiTracker_create()
vs = cv2.VideoCapture(args["video"])

处理视频流

  • 取当前帧
  • 调整帧的尺寸(如果不大也可以不调整)
  • 按"s"键让视频暂停
  • 绘制方框将想要追踪的东西圈出来
  • 创建一个新的追踪器
  • 返回追踪结果
  • 在追踪结果中绘制方框
while True:
	# 取当前帧
	frame = vs.read()
	# (true, data)
	frame = frame[1]
	# 到头了就结束
	if frame is None:
		break

	# resize每一帧
	(h, w) = frame.shape[:2]
	width=600
	r = width / float(w)
	dim = (width, int(h * r))
	frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)

	# 追踪结果
	(success, boxes) = trackers.update(frame)

	# 绘制区域
	for box in boxes:
		(x, y, w, h) = [int(v) for v in box]
		cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

	# 显示
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(100) & 0xFF

	if key == ord("s"):
		# 选择一个区域,按s,暂停,开始选择区域
		box = cv2.selectROI("Frame", frame, fromCenter=False,
			showCrosshair=True)

		# 创建一个新的追踪器
		tracker = OPENCV_OBJECT_TRACKERS['kcf']()
		trackers.add(tracker, frame, box)

	# 退出
	elif key == 27:
		break
vs.release()
cv2.destroyAllWindows()

三、用SSD目标检测模型与dlib库实现的对视频中多目标的追踪

1 思路

dlib是一个机器学期的开源库,包含很多算法,这里主要用到目标追踪相关的功能,需要安装。安装

SSD是一种非常优秀的one-stage方法,one-stage算法就是目标检测和分类是同时完成的,其主要思路是均匀地在图片的不同位置进行密集抽样,抽样时可以采用不同尺度和长宽比,然后利用CNN提取特征后直接进行分类与回归,整个过程只需要一步,所以其优势是速度快。
SSD模型讲解

本次实验利用caffe框架使用深度学习模型对图像视频的处理,预测。
大致的步骤为:
1传入参数:SSD模型,视频
2将SSD模型的标签写入字典,方便使用
3读入网络模型,要处理的视频
4处理视频:
① 传入第一帧图像,预处理,利用SSD模型检测出图像中物体的位置以及类别,筛选出我们需要追踪的物体(人)
② 利用dlib框架,将需要追踪的物体画个框框起来,传入这个框的四个坐标以及第一帧图像到追踪器,进行追踪(start_track)
③ 在图像中画出框,可视化结果
--------------------------------------------
① 对于不是第一帧的图像,遍历追踪器列表与标签列表,得到需要追踪的物体
② 更新每一个追踪器所对应的图像为当前帧,得到追踪对象的预测位置
③ 在图像中画出,可视化结果
5显示结果(其实每处理一帧就显示一次,是以图像流的形式展示的)
代码

#导入工具包
from utils import FPS
import numpy as np
import argparse
import dlib
import cv2
""" #需edit configuration的参数
--prototxt mobilenet_ssd/MobileNetSSD_deploy.prototxt 
--model mobilenet_ssd/MobileNetSSD_deploy.caffemodel 
--video race.mp4
"""
# 参数
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-v", "--video", required=True,
	help="path to input video file")
ap.add_argument("-o", "--output", type=str,
	help="path to optional output video file")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
	help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

# SSD标签
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor"]

# 读取网络模型
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

# 初始化
print("[INFO] starting video stream...")
vs = cv2.VideoCapture(args["video"])
writer = None

# 一会要追踪多个目标
trackers = [] #追踪器列表
labels = []

# 计算FPS
fps = FPS().start()

while True:
	# 读取一帧
	(grabbed, frame) = vs.read()

	# 是否是最后了
	if frame is None:
		break

	# 预处理操作
	(h, w) = frame.shape[:2]
	width=600
	r = width / float(w)
	dim = (width, int(h * r))
	frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
	rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) #OpenCV的颜色通道是BGR的,但是深度学习的框架是RGB的,做一个转换

	# 如果要将结果保存的话
	if args["output"] is not None and writer is None:
		fourcc = cv2.VideoWriter_fourcc(*"MJPG")
		writer = cv2.VideoWriter(args["output"], fourcc, 30,
			(frame.shape[1], frame.shape[0]), True)

	# 先检测 再追踪
	if len(trackers) == 0: #代表是第一次检测
		# 获取blob数据
		(h, w) = frame.shape[:2]
		blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5)
		#输入参数:图像,缩放因子,宽高,均值(要做一个减均值的操作)
		# 得到检测结果
		net.setInput(blob) #将输入数据传入模型
		detections = net.forward() #前向传播
		#检测到的结果有多个,不一定都是人(我们需要的东西),我已我们要对检测结果进行筛选
		# 遍历得到的检测结果
		for i in np.arange(0, detections.shape[2]):
			# 能检测到多个结果,只保留概率高的
			confidence = detections[0, 0, i, 2]
			#SSD框架是同时完成检测与分类的。检测的结果中也有概率和匹配的物体id
			#取出概率值,与阈值比较,若大于阈值就取出该概率值对应的物体id
			# 过滤
			if confidence > args["confidence"]:
				# extract the index of the class label from the
				# detections list
				idx = int(detections[0, 0, i, 1])
				label = CLASSES[idx]
				#提取出标签对应的物体名称,如果不是人的话,就舍弃
				# 只保留人的
				if CLASSES[idx] != "person":
					continue

				# 得到BBOX
				#print (detections[0, 0, i, 3:7]) #我们要得到框的位置,这个输出的是框的一个相对位置(0.2w,0.2h)之类的
				box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) #将之还原为原始坐标
				(startX, startY, endX, endY) = box.astype("int")
				#使用dlib来进行目标追踪必须满足坐标是int类型的数据
				# 使用dlib来进行目标追踪
				#http://dlib.net/python/index.html#dlib.correlation_tracker   dlib的说明文档
				t = dlib.correlation_tracker() #实例化方法
				rect = dlib.rectangle(int(startX), int(startY), int(endX), int(endY)) #将之做成一个框
				t.start_track(rgb, rect) #开始追踪,传入当前图像以及检测到的物体的框框
				#该对象将开始跟踪给定图像的边界框内的物体。也就是说,如果您对随后的视频帧调用update(),
				# 那么它将尝试跟踪边框内对象的位置。
				# 保存结果
				labels.append(label) #保存标签
				trackers.append(t) #保存追踪的结果
				#若不是第一个检测出的结果,那么就将追踪的结果保存
				# 绘图
				cv2.rectangle(frame, (startX, startY), (endX, endY),
					(0, 255, 0), 2)
				cv2.putText(frame, label, (startX, startY - 15),
					cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

	# 如果已经有了框,就可以直接追踪了
	else:
		# 每一个追踪器都要进行更新
		for (t, l) in zip(trackers, labels):
			t.update(rgb)# 这个trackers是上一帧图像检测出物体对应的追踪器,要更新对应这一帧的图像
			pos = t.get_position() #返回跟踪对象的预测位置

			# 得到位置
			startX = int(pos.left())
			startY = int(pos.top())
			endX = int(pos.right())
			endY = int(pos.bottom())

			# 画出来
			cv2.rectangle(frame, (startX, startY), (endX, endY),
				(0, 255, 0), 2)
			cv2.putText(frame, l, (startX, startY - 15),
				cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)

	# 也可以把结果保存下来
	if writer is not None:
		writer.write(frame)

	# 显示
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF

	# 退出
	if key == 27:
		break

	# 计算FPS
	fps.update()


fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

if writer is not None:
	writer.release()

cv2.destroyAllWindows()
vs.release()

四、利用多进程改善

步骤与上面的方法相同,就是在处理一帧图像的n个需要追踪的对象时使用多进程处理。
在这里插入图片描述

from utils import FPS
import multiprocessing
import numpy as np
import argparse
import dlib
import cv2
#perfmon

def start_tracker(box, label, rgb, inputQueue, outputQueue):
	t = dlib.correlation_tracker() #实例化方法
	rect = dlib.rectangle(int(box[0]), int(box[1]), int(box[2]), int(box[3])) #画框
	t.start_track(rgb, rect)#开始追踪,传入当前图像以及检测到的物体的框框

	while True:
		# 获取下一帧
		rgb = inputQueue.get() #得到下一帧图像

		# 非空就开始处理
		if rgb is not None:
			# 更新追踪器
			t.update(rgb)
			pos = t.get_position()

			startX = int(pos.left())
			startY = int(pos.top())
			endX = int(pos.right())
			endY = int(pos.bottom())
			#得到预测结果的四个坐标后,不是return而是将之存入输出队列,等到四个进程的结果得到之后就get出来
			# 把结果放到输出q
			outputQueue.put((label, (startX, startY, endX, endY)))

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-v", "--video", required=True,
	help="path to input video file")
ap.add_argument("-o", "--output", type=str,
	help="path to optional output video file")
ap.add_argument("-c", "--confidence", type=float, default=0.2,
	help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

# 一会要放多个追踪器
    inputQueues = []
    outputQueues = []

CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor"]

print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

print("[INFO] starting video stream...")
vs = cv2.VideoCapture(args["video"])
writer = None

fps = FPS().start()

if __name__ == '__main__':
	
	while True:
		(grabbed, frame) = vs.read()
	
		if frame is None:
			break
	
		(h, w) = frame.shape[:2]
		width=600
		r = width / float(w)
		dim = (width, int(h * r))
		frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
		rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
	
		if args["output"] is not None and writer is None:
			fourcc = cv2.VideoWriter_fourcc(*"MJPG")
			writer = cv2.VideoWriter(args["output"], fourcc, 30,
				(frame.shape[1], frame.shape[0]), True)
	
		#首先检测位置
		if len(inputQueues) == 0: #没有检测物体之前,我先用SSD模型检测出我们需要的物体(人)
			(h, w) = frame.shape[:2]
			blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5)
			net.setInput(blob)
			detections = net.forward()
			for i in np.arange(0, detections.shape[2]):
				confidence = detections[0, 0, i, 2]
				if confidence > args["confidence"]:
					idx = int(detections[0, 0, i, 1])
					label = CLASSES[idx]
					if CLASSES[idx] != "person":
						continue
					box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
					(startX, startY, endX, endY) = box.astype("int")
					bb = (startX, startY, endX, endY)
					#对于每个进程来说都有一个iq和oq,多进程并发的Queue队列,用于解决多进程间的通信问题
					# 创建输入q和输出q
					iq = multiprocessing.Queue() #iq为了去当前帧的图像
					oq = multiprocessing.Queue() #oq为了将预测后的位置,两个点的坐标返回
					inputQueues.append(iq)
					outputQueues.append(oq)
					
					# 多核
					#创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动
					p = multiprocessing.Process(
						target=start_tracker, #指定创建的子进程要执行的任务函数
						args=(bb, label, rgb, iq, oq)) #args为执行函数的参数,可以是元组,也可以是列表
					p.daemon = True
					p.start() #启动进程实例(创建子进程)
					
					cv2.rectangle(frame, (startX, startY), (endX, endY),
						(0, 255, 0), 2)
					cv2.putText(frame, label, (startX, startY - 15),
						cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)
	
		else:
			# 多个追踪器处理的都是相同输入
			for iq in inputQueues:
				iq.put(rgb)
	
			for oq in outputQueues:
				# 得到更新结果
				(label, (startX, startY, endX, endY)) = oq.get()
	
				# 绘图
				cv2.rectangle(frame, (startX, startY), (endX, endY),
					(0, 255, 0), 2)
				cv2.putText(frame, label, (startX, startY - 15),
					cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)
	
		if writer is not None:
			writer.write(frame)
	
		cv2.imshow("Frame", frame)
		key = cv2.waitKey(1) & 0xFF
	
		if key == 27:
			break

		fps.update()
	fps.stop()
	print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
	print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
	
	if writer is not None:
		writer.release()

	cv2.destroyAllWindows()
	vs.release()

CPU使用情况对比:
在这里插入图片描述
Process语法结构和常用方法

结果图
在这里插入图片描述

四、不足的地方

1 当检测的目标从没有重合的状态到有重合状态的时候(就是被什么东西遮住了的时候),检测结果不准确。
2 当背景发生大规模变化的时候,检测效果不好。

  • 10
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值