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();
相关推荐
ebiobiz36 分钟前
极海 APM32 使用 Nimmake 编译指南
c++·python·单片机·嵌入式硬件·mcu
慢云智慧空间1 小时前
从智能终端到空间AI,慢云科技如何重新定义智慧建筑的核心能力?
人工智能·python·科技
2601_962885721 小时前
如何用 Python 做股价历史分位选股?(筛出处于历史低位的股票)
开发语言·python
倔强的石头1061 小时前
【Linux指南】动静态库系列(十一):PLT 与延迟绑定:第一次调用动态库函数时发生了什么
linux·人工智能·python
梦帮科技1 小时前
vLLM / TensorRT-LLM 极限推理:PagedAttention 细粒度物理页表管理与连续批处理(Continuous Batching)实战
数据结构·人工智能·分布式·python·深度学习·算法·vllm
言乐62 小时前
Python概括后端原理
开发语言·python·django·virtualenv·pygame
Y3815326622 小时前
搜索 API 响应模块:featured_snippet、PAA 与 knowledge_graph 怎么用
python·搜索引擎
10年前端老司机3 小时前
实战分享:基于 PyMuPDF+Qwen-VL 实现图文兼容的 PDF RAG 方案
人工智能·python·agent
2601_962885723 小时前
如何用 Python 回测定投策略(定期定额 DCA)?(和一次性买入对比)
开发语言·人工智能·python
蜗牛互联网3 小时前
Python接入Gemini 3.8 Flash实现票据视觉抽取与规则校验
java·javascript·网络·人工智能·python