opencv学习打卡02

opencv学习笔记

今天进一步学习了OpenCV中提供的函数,实现了识别车辆的一个小程序

话不多说,上代码

#created by walker 2022/12/14


import cv2
import numpy as np

cap = cv2.VideoCapture('./video.mp4')

bgsubmog = cv2.createBackgroundSubtractorMOG2()

#形态学kernel
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))

while True:
    ret, frame = cap.read()
    if(ret== True):
        #灰度
        cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #去噪,高斯
        blur = cv2.GaussianBlur(frame, (3,3), 5)

        #去背影
        mask = bgsubmog.apply(blur)

        #腐蚀
        erode = cv2.erode(mask, kernel)

        #膨胀
        dilate = cv2.dilate(erode, kernel, iterations=3)

        #闭操作
        close = cv2.morphologyEx(dilate, cv2.MORPH_CLOSE, kernel)
        close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, kernel)

        cnts, h = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        for (i, c) in enumerate(cnts):
            (x, y, w,h) = cv2.boundingRect(c)
            cv2.rectangle(frame,(x, y), (x+w, y+h), (0,0,255),2)

        cv2.imshow('video',frame)
        #cv2.imshow('erode', dilate)
    


    key = cv2.waitKey(1)
    if(key == 27):
        break
    
cap.release()
cv2.destroyAllWindows()

浙ICP备19012682号