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();
相关推荐
databook17 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室18 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三19 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python