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();
相关推荐
橡晟4 小时前
深度学习入门:让神经网络变得“深不可测“⚡(二)
人工智能·python·深度学习·机器学习·计算机视觉
墨尘游子4 小时前
神经网络的层与块
人工智能·python·深度学习·机器学习
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
企鹅与蟒蛇5 小时前
Ubuntu-25.04 Wayland桌面环境安装Anaconda3之后无法启动anaconda-navigator问题解决
linux·运维·python·ubuntu·anaconda
autobaba5 小时前
编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
chrome·python·selenium·rpa
Rvelamen6 小时前
LLM-SECURITY-PROMPTS大模型提示词攻击测评基准
人工智能·python·安全
【本人】6 小时前
Django基础(一)———创建与启动
后端·python·django
AI technophile6 小时前
OpenCV计算机视觉实战(15)——霍夫变换详解
人工智能·opencv·计算机视觉
SHIPKING3938 小时前
【python】基于pygame实现动态粒子爱心
开发语言·python·pygame
kk_stoper9 小时前
如何通过API查询实时能源期货价格
java·开发语言·javascript·数据结构·python·能源