【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 = size(firstFrame, (640, 360), interpolation=cv2.INTER_CUBIC)
gray_firstFrame = cv2.cvtColor(firstFrame, cv2.COLOR_BGR2GRAY) # 灰度化
firstFrame = cv2.GaussianBlur(gray_firstFrame, (21, 21), 0) #⾼斯模糊,⽤于去噪
prveFrame = py()
#遍历视频的每⼀帧
while True:
(ret, frame) = vc.read()
# 如果没有获取到数据,则结束循环
if not ret:
break
# 对获取到的数据进⾏预处理
frame = size(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)
rectangle函数opencvprveFrame = py()
# 忽略较⼩的差别
retVal, thresh = cv2.threshold(frameDiff, 25, 255, cv2.THRESH_BINARY)
# 对阈值图像进⾏填充补洞
thresh = cv2.dilate(thresh, None, iterations=2)
image, contours, hierarchy = cv2.py(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
text = "Unoccupied"
# 遍历轮廓
for contour in contours:
# if contour is too small, just ignore it
urArea(contour) < 50: #⾯积阈值
continue
# 计算最⼩外接矩形(⾮旋转)
(x, y, w, h) = cv2.boundingRect(contour)
(x, y, w, h) = cv2.boundingRect(contour)
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)
3、效果展⽰
①、前后两帧的灰度图:
②、帧差法结果:
③、运动⽬标检测结果:
参考资料:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论