Python Opencv实践 - 车辆识别(1)读取视频,移除背景,做预处理

示例中的图像的腐蚀、膨胀和闭运算等需要根据具体视频进行实验得到最佳效果。代码仅供参考。

import cv2 as cv
import numpy as np

#读取视频文件
video = cv.VideoCapture("../../SampleVideos/Traffic.mp4")
FPS = 10
DELAY = int(1000 / FPS)
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5,5))

#while True:
#    ret,frame = video.read()
#    if ret == False:
#        break;
#    cv.imshow("Traffic", frame)
#    if cv.waitKey(DELAY) == 27:
#        break;
#video.release()
#cv.destroyAllWindows()


#移除背景
#参考资料:https://blog.csdn.net/u014737138/article/details/80389977
#mog = cv.bgsegm.createBackgroundSubtractorMOG()
mog = cv.createBackgroundSubtractorMOG2()
while True:
    ret,frame = video.read()
    if ret == False:
        break;
    #变为灰度图做高斯滤波
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    #blur = cv.GaussianBlur(gray, (3,3), 5)
    foreground_mask = mog.apply(gray)

    #腐蚀
    #erode = cv.erode(foreground_mask, kernel)
    #膨胀
    #dilate = cv.dilate(foreground_mask, kernel, iterations=2)
    #闭运算
    close = cv.morphologyEx(foreground_mask, cv.MORPH_CLOSE, kernel)
    close = cv.GaussianBlur(close, (3,3), 5)
    cv.imshow("Traffic Original", frame)
    cv.imshow("Traffic Background Removed", foreground_mask)
    #cv.imshow("Traffic erode", erode)
    #cv.imshow("Traffic dilate", dilate)
    cv.imshow("Traffic close", close)
    if cv.waitKey(DELAY) == 27:
        break;
video.release()
cv.destroyAllWindows();
相关推荐
belldeep16 分钟前
python:reportlab 将多个图片合并成一个PDF文件
python·pdf·reportlab
CV-King2 小时前
opencv实战项目(三十):使用傅里叶变换进行图像边缘检测
人工智能·opencv·算法·计算机视觉
兔云程序2 小时前
字节跳动收购Oladance耳机:强化音频技术,加速VR/AR生态布局
ar·音视频·vr
FreakStudio3 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
丶21363 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
jndingxin4 小时前
OpenCV视频I/O(14)创建和写入视频文件的类:VideoWriter介绍
人工智能·opencv·音视频
_.Switch4 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一个闪现必杀技4 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
小鹿( ﹡ˆoˆ﹡ )4 小时前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
卷心菜小温5 小时前
【BUG】P-tuningv2微调ChatGLM2-6B时所踩的坑
python·深度学习·语言模型·nlp·bug