python+opencv实时视频目标检测

时间:2022-07-26
本文章向大家介绍python+opencv实时视频目标检测,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

python+opencv实时视频目标检测

opencv环境

1、访问Python Extension Packages for Windows,下载python对应版本的opencv。

比如小编下载的是opencv_python-3.3.0+contrib-cp36-cp36m-win_amd64.whl,cp36表示Python是3.6版本,win_amd64是表示安装的python是64bit的,+contrib表示包括contrib包。

2、下载好后,把它放到C盘中,执行安装命令:

pip install C:opencv_python-3.3.0+contrib-cp36-cp36m-win_amd64.whl

运行代码

修改

从本地获取。

# vs = VideoStream(src=0).start()
# vs =cv2.VideoCapture('C:\Users\voidking\Desktop\real-time-object-detection\test_video.flv')
vs =cv2.VideoCapture('./test_video.flv')


# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
# frame = vs.read()
# frame = imutils.resize(frame, width=400)

# grab the frame from the threaded video file stream
(grabbed,frame) = vs.read()
# if the frame was not grabbed, then we have reached the end
# of the stream
if not grabbed:
    break
frame = imutils.resize(frame, width=800)

运行

推荐使用命令:

python real_time_object_detection.py -p ./MobileNetSSD_deploy.prototxt.txt -m ./MobileNetSSD_deploy.caffemodel

或者,指定绝对路径,假设项目目录为C:UsersvoidkingDesktopreal-time-object-detection,那么命令如下:

python real_time_object_detection.py -p "C:UsersvoidkingDesktopreal-time-object-detectionMobileNetSSD_deploy.prototxt.txt" -m "C:UsersvoidkingDesktopreal-time-object-detectionMobileNetSSD_deploy.caffemodel"

进阶修改

我们看到,prototxt和model都是指定的,那我们的视频文件也用这种方式指定,就更加友好一点。

# construct the argument parse and parse the arguments
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("-c", "--confidence", type=float, default=0.2,
    help="minimum probability to filter weak detections")
args = vars(ap.parse_args())

我们插入一行:

ap.add_argument("-v", "--video", required=True,
    help="path to Caffe video file")

然后在初始化视频流时,修改为:

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

运行命令修改为

python real_time_object_detection.py -p ./MobileNetSSD_deploy.prototxt.txt -m ./MobileNetSSD_deploy.caffemodel -v ./test_video.flv

运行效果

源码分享

https://gitee.com/lyc96/real-time_video_target_detection