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();
相关推荐
IVEN_15 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang16 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮16 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling16 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮19 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽20 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers