项目要点
- 读取文件: cap = cv2.VideoCapture('./video.mp4')
- 读取视频帧: ret, frame = cap.read() # 第一个为状态值, 读到帧为True, 第二个值为视频帧
- 灰度化处理: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
- 高斯滤波, 去噪: blur = cv2.GaussianBlur(gray, (5, 5), 5)
- 腐蚀操作: erode = cv2.erode(mask, kernel)
- 膨胀操作: dialte = cv2.dilate(erode, kernel, iterations = 2)
- 闭运算: close = cv2.morphologyEx(dialte, cv2.MORPH_CLOSE, kernel) # 消除内部方块
- 间隔时间设置: key = cv2.waitKey(1) # 单位是毫秒
- 创建背景减除视频: mog = cv2.createBackgroundSubtractorKNN()
- 显示背景减除视频: fgmask = mog.apply(frame) # 判断哪些是前景和背景
- OpenCV借助pillow来实现绘制中文: from PIL import ImageFont, ImageDraw, Image
- 画检测线: cv2.line(frame, (10, line_high), (1270, line_high), (250, 100,20), 3)
- 画过线车辆中心点: cv2.circle(frame, (cpoint), 5, (0, 0, 255), -1) # 画圆
- 文字显示: cv2.putText()
cv2.putText(frame, 'Vehicle Count:' + str(carno), (500, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 5)
- contours, h = cv2.findContours(close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 查找所有轮廓和层级.
- 根据检测轮廓画出所有移动目标的外接矩形: cv2.rectangle(frame, (int(x), int(y)), (int(x + w), int(y + h)), (0, 0, 255), 2) # 画外接矩形时注意将数据转换为整数.
- BackgroundSubtractorMOG 背景减除(Background Subtraction)是许多基于计算机视觉的任务中的主要预处理步骤。 如果我们有完整的静止的背景帧,那么我们可以通过帧差法来计算像素差从而获取到前景对象。但是在大多数情况下,我们可能没有这样的图像,所以我们需要从我们拥有的任何图像中提取背景。当运动物体有阴影时,由于阴影也在移动,情况会变的变得更加复杂。为此引入了背景减除算法,通过这一方法我们能够从视频中分离出运动的物体前景,从而达到目标检测的目的。
-
这是一个以混合高斯模型为基础的前景/背景分割算法。它是 P.KadewTraKuPong 和 R.Bowden 在 2001 年提出的。
-
它使用 K(K=3 或 5)个高斯分布混合对背景像素进行建模。使用这些颜色(在整个视频中)存在时间的长短作为混合的权重。背景的颜色一般持续的时间最长,而且更加静止。
-
在编写代码时,我们需要使用函数:cv2.createBackgroundSubtractorMOG() 创建一个背景对象。这个函数有些可选参数,比如要进行建模场景的时间长度,高斯混合成分的数量,阈值等。将他们全部设置为默认值。然后在整个视频中我们是需要使用backgroundsubtractor.apply() 就可以得到前景的掩模了.
-
移动的物体会被标记为白色,背景会被标记为黑色的
-
-
项目存在的问题: 该检测方式与车辆移速有关,如果车速过快会漏掉,车速过慢会重复.车辆较大时也容易造成重复计数 .
移动车辆识别统计项目
1 涉及到的内容
-
窗口的展示
-
图像/视频的加载
-
基本图像的绘制
-
车辆识别
-
基本图像运算与处理
-
形态学
-
轮廓查找
-
2 整体流程
-
加载视频
-
通过形态学识别车辆
-
对车辆进行统计
-
显示车辆统计信息
3 测试背景减除功能
# 加载视频
import cv2
import numpy as np
cap = cv2.VideoCapture('./video.mp4')
# 循环读取视频帧
while True:
ret, frame = cap.read()
if ret == True:
cv2.imshow('video', frame)
key = cv2.waitKey(1)
# 用户按esc退出
if key == 27:
break
# 最后别忘了, 释放资源
cap.release()
cv2.destroyAllWindows()
4 去除背景
import cv2
import numpy as np
cap = cv2.VideoCapture('./video.mp4')
mog = cv2.createBackgroundSubtractorKNN() # 创建mog对象
while True:
ret, frame = cap.read()
if ret == True:
fgmask = mog.apply(frame) # 判断哪些是前景和背景
cv2.imshow('video', fgmask)
key = cv2.waitKey(1) # 时间记录为1ms
if key == 27: # 用户按esc 进行退出
break
# 记得释放资源
cap.release() # 注意该位置为 cap
cv2.destroyAllWindows()
5 形态学识别车辆 (项目实操)
# 加载视频
import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
cap = cv2.VideoCapture('./video.mp4')
# 创建mog对象
mog = cv2.createBackgroundSubtractorKNN()
# 统计通过车数量
cars = []
carno = 0
# 计算外接矩形的中心点
def center(x, y , w, j):
x1 = int(w / 2)
y1 = int(h/2)
cx = int(x) + x1
cy = int(y) + y1
return cx, cy
while True:
ret, frame = cap.read()
if ret == True:
# 将原始帧进行灰度化处理, 然后去噪
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 去噪, 高斯滤波
blur = cv2.GaussianBlur(gray, (5, 5), 5)
mask = mog.apply(blur) # 判断哪些是前景和背景
# 腐蚀操作
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
erode = cv2.erode(mask, kernel)
dialte = cv2.dilate(erode, kernel, iterations = 2) # 膨胀
# 闭运算,消除内部的小方块
close = cv2.morphologyEx(dialte, cv2.MORPH_CLOSE, kernel)
# cv2.imshow('close', close)
# 查找所有轮廓
contours, h = cv2.findContours(close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# 画出检测线 # 颜色序列: BGR
line_high = 600
cv2.line(frame, (10, line_high), (1270, line_high), (250, 100,20), 3)
# 画出所有轮廓
for contour in contours:
# 最大外接矩形
(x, y, w, h) = cv2.boundingRect(contour)
min_w, min_h = 90, 90 # 最小外接矩形大小设置
is_valid = (w >= min_w) & (h >= min_h) # 最小值设置需要多次调整后得知
if not is_valid:
continue # 跳出进入下一个循环
# 能进入该步骤为满足要求的矩形
# 过滤小框,通过宽高大小过滤小矩形
# 要求都是整数
cv2.rectangle(frame, (int(x), int(y)), (int(x + w), int(y + h)),
(0, 0, 255), 2)
# 把车抽象为一个点即外接矩形的中心点
# 要求是整数
cpoint = center(x, y ,w, h)
cars.append(cpoint)
cv2.circle(frame, (cpoint), 4, (0, 0, 255), -1)
# 判断是否过检测线
offset = 7 # 偏移量,与车辆移速有关,如果车速过快会漏掉,车速过慢会重复
for (x, y) in cars:
if y > (line_high - offset) and y < (line_high + offset):
# 落入有效区间, 计数+1
carno += 1
cars.remove((x, y))
print(carno)
# 英文显示通过车辆数
# cv2.putText(frame, 'Vehicle Count:' + str(carno), (500, 60),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 5)
# 中文显示
font_path = 'simhei.ttf'
font = ImageFont.truetype(font_path, 36)
img_pil = Image.fromarray(frame)
draw = ImageDraw.Draw(img_pil)
row, col, channel = frame.shape
draw.text((col- 720, row- 650), '通过车辆数:'+str(carno), font=font,
fill=(0, 0, 255, 255))
frame = np.array(img_pil)
cv2.imshow('img_logo', frame)
key = cv2.waitKey(1) # 时间记录为1ms
# 用户按esc 进行退出
if key == 27:
break
# 记得释放资源
cap.release() # 注意该位置为 cap
cv2.destroyAllWindows()