本篇博客使用opencv的4.2.0:
pip install opencv-python
pip install --user -i https://pypi.mirrors.ustc.edu.cn/simple/ opencv-contrib-python
文件:objection_tracking.py
# -*- coding: utf-8 -*-
"""
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 6 12:49:17 2020
@author: asus
"""
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
import cv2
#设置参数(set up parameters set params options)
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", type=str,
help="path to input video file")
ap.add_argument("-t", "--tracker", type=str, default="boosting",
help="OpenCV object tracker type")
args = vars(ap.parse_args())
(major, minor) = cv2.__version__.split(".")[:2]
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
}
tracker = OPENCV_OBJECT_TRACKERS[args["tracker"]]()
#初始化(initialization parameter)
initBB = None
#starting video stream
if not args.get("video", False):
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(1.0)
else:
vs = cv2.VideoCapture(args["video"])
fps = None
#start reading video
while True:
#Read each frame in turn
frame = vs.read()
#judge whether to use VideoStream
frame = frame[1] if args.get("video", False) else frame
if frame is None:
break
#resize frame
frame = imutils.resize(frame, width=800)
(H, W) = frame.shape[:2]
if initBB is not None:
#get success and box
(success, box) = tracker.update(frame)
#frame picture(Redraw the rectangle)
if success:
(x, y, w, h) = [int(v) for v in box]
cv2.rectangle(frame, (x, y), (x + w, y + h),
(0, 255, 0), 2)
fps.update()
fps.stop()
#save information
info = [
("Tracker", args["tracker"]),
("Success", "Yes" if success else "No"),
("FPS", "{:.2f}".format(fps.fps())),
]
#Based on the existing parameter description box information
for (i, (k, v)) in enumerate(info):
text = "{}: {}".format(k, v)
cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
#press s to frame object for initialization
if key == ord("s"):
#set initialization rectangle
initBB = cv2.selectROI("Frame", frame, fromCenter=False,
showCrosshair=True)
tracker.init(frame, initBB)
fps = FPS().start()
#exit
elif key == ord("q"):
break
time.sleep(1.0)
#starting video stream
if not args.get("video", False):
vs.stop()
else:
vs.release()
cv2.destroyAllWindows()
ps:可以调整time.sleep()调整视频速度。
网上下载了这样的gif图:
运行以下这样的命令:
python C:\Users\asus\Desktop\objection_tracking.py -v C:\Users\asus\Desktop\85cccab3gw1etdci9ok92g20ak05y7wh.gif
然后按s,开始画框:
然后enter,效果如下:
参考文献:
http://www.dataguru.cn/article-13987-1.html