opencv python 三帧差法
时间: 2023-10-04 19:08:44 浏览: 234
三帧差法是一种基于连续帧之间像素差异的运动检测算法,可以用于视频监控、行人检测等应用场景。在OpenCV中,可以通过以下步骤实现三帧差法:
1. 读取视频帧序列,并将其转化为灰度图像。
```python
import cv2
cap = cv2.VideoCapture('video.mp4')
ret, frame1 = cap.read()
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
ret, frame2 = cap.read()
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
while True:
ret, frame3 = cap.read()
gray3 = cv2.cvtColor(frame3, cv2.COLOR_BGR2GRAY)
```
2. 计算当前帧与前两帧之间的差值,并进行二值化处理。
```python
d1 = cv2.absdiff(gray2, gray1)
d2 = cv2.absdiff(gray3, gray2)
diff = cv2.bitwise_and(d1, d2)
_, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)
```
3. 对二值化后的图像进行形态学操作,去除噪声。
```python
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=2)
```
4. 绘制运动物体的轮廓,并标记出运动方向。
```python
contours, _ = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 500:
continue
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame3, (x, y), (x + w, y + h), (0, 255, 0), 2)
cx, cy = x + w // 2, y + h // 2
cv2.arrowedLine(frame3, (cx, cy), (cx + 50, cy), (0, 0, 255), 2)
```
完整代码如下:
```python
import cv2
cap = cv2.VideoCapture('video.mp4')
ret, frame1 = cap.read()
gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY)
ret, frame2 = cap.read()
gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
while True:
ret, frame3 = cap.read()
gray3 = cv2.cvtColor(frame3, cv2.COLOR_BGR2GRAY)
d1 = cv2.absdiff(gray2, gray1)
d2 = cv2.absdiff(gray3, gray2)
diff = cv2.bitwise_and(d1, d2)
_, thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=2)
contours, _ = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 500:
continue
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame3, (x, y), (x + w, y + h), (0, 255, 0), 2)
cx, cy = x + w // 2, y + h // 2
cv2.arrowedLine(frame3, (cx, cy), (cx + 50, cy), (0, 0, 255), 2)
cv2.imshow('frame', frame3)
gray1 = gray2
gray2 = gray3
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
阅读全文