opencv 图片去抖
时间: 2023-12-06 09:03:22 浏览: 78
以下是使用OpenCV进行图片去抖的步骤:
1.导入必要的库和模块
```python
import cv2
import numpy as np
```
2.读取视频并获取第一帧
```python
cap = cv2.VideoCapture('video.mp4')
ret, frame = cap.read()
```
3.将第一帧转换为灰度图像并进行高斯模糊
```python
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
```
4.循环读取视频中的每一帧并进行去抖处理
```python
while True:
ret, frame = cap.read()
if not ret:
break
# 将当前帧转换为灰度图像并进行高斯模糊
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
# 计算当前帧与上一帧的差异,并进行阈值处理
frame_diff = cv2.absdiff(gray, prev_gray)
thresh = cv2.threshold(frame_diff, 25, 255, cv2.THRESH_BINARY)[1]
# 对阈值图像进行膨胀操作
thresh = cv2.dilate(thresh, None, iterations=2)
# 找到轮廓并绘制矩形框
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
if cv2.contourArea(contour) < 1000:
continue
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 显示当前帧
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 更新上一帧
prev_gray = gray.copy()
```
5.释放资源并关闭窗口
```python
cap.release()
cv2.destroyAllWindows()
```
阅读全文