【Python】监控视频中运动目标检测的代码实现及效果展示

0、介绍

基于python,使用opencv库函数,实现监控视频中的运动目标检测,Mark一下!

干扰性和灵敏度的权衡,可通过调节代码中的参数(高斯模糊核、面积阈值、帧差间隔等)进行设置。

 

1、代码

以下代码亲测可直接运行。 

import cv2

vc = cv2.VideoCapture("C:\\Users\\jason\\Desktop\\video.MP4")  # 读入视频文件
# vc = cv2.VideoCapture("C:/Users/jason/Desktop/152821AA.MP4")

rval, firstFrame = vc.read()
firstFrame = cv2.resize(firstFrame, (640, 360), interpolation=cv2.INTER_CUBIC)
gray_firstFrame = cv2.cvtColor(firstFrame, cv2.COLOR_BGR2GRAY)   # 灰度化
firstFrame = cv2.GaussianBlur(gray_firstFrame, (21, 21), 0)      #高斯模糊,用于去噪
prveFrame = firstFrame.copy()


#遍历视频的每一帧
while True:
    (ret, frame) = vc.read()

    # 如果没有获取到数据,则结束循环
    if not ret:
        break

    # 对获取到的数据进行预处理
    frame = cv2.resize(frame, (640, 360), interpolation=cv2.INTER_CUBIC)
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray_frame = cv2.GaussianBlur(gray_frame, (3, 3), 0)
    cv2.imshow("current_frame", gray_frame)
    cv2.imshow("prveFrame", prveFrame)

    # 计算当前帧与上一帧的差别
    frameDiff = cv2.absdiff(prveFrame, gray_frame)
    cv2.imshow("frameDiff", frameDiff)
    prveFrame = gray_frame.copy()


    # 忽略较小的差别
    retVal, thresh = cv2.threshold(frameDiff, 25, 255, cv2.THRESH_BINARY)


    # 对阈值图像进行填充补洞
    thresh = cv2.dilate(thresh, None, iterations=2)
    image, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    text = "Unoccupied"
    # 遍历轮廓
    for contour in contours:
        # if contour is too small, just ignore it
        if cv2.contourArea(contour) < 50:   #面积阈值
            continue

        # 计算最小外接矩形(非旋转)
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        text = "Occupied!"

    # cv2.putText(frame, "Room Status: {}".format(text), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    cv2.putText(frame, "F{}".format(frameCount), (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    cv2.imshow('frame_with_result', frame)
    cv2.imshow('thresh', thresh)
    cv2.imshow('frameDiff', frameDiff)

    # 处理按键效果
    key = cv2.waitKey(60) & 0xff
    if key == 27:  # 按下ESC时,退出
        break
    elif key == ord(' '):  # 按下空格键时,暂停
        cv2.waitKey(0)

    cv2.waitKey(0)

vc.release()

 

3、效果展示

①、前后两帧的灰度图:

【Python】监控视频中运动目标检测的代码实现及效果展示_第1张图片

 

②、帧差法结果:

【Python】监控视频中运动目标检测的代码实现及效果展示_第2张图片

 

③、运动目标检测结果:

【Python】监控视频中运动目标检测的代码实现及效果展示_第3张图片

 

参考资料:

http://python.jobbole.com/81593/ 

https://www.cnblogs.com/gxcdream/p/7531744.html

你可能感兴趣的:(运动目标检测,Python,计算机视觉,OpenCv,Python,计算机视觉)