写一段利用python语言,读取悬臂梁振动冲击视频,利用圆心标靶检测算法、Gunner Farneback算法计提取测点的位移并绘制每个测点的位移时程曲线的完整算法
时间: 2023-12-14 16:18:17 浏览: 144
FEM.rar_悬臂梁_计算线性梁的位移程序
好的,以下是利用 Python 读取悬臂梁振动冲击视频,利用圆心标靶检测算法、Gunner Farneback算法提取测点的位移并绘制每个测点的位移时程曲线的完整算法:
1. 导入所需的库和模块:
```python
import cv2
import numpy as np
import matplotlib.pyplot as plt
```
2. 读取视频文件:
```python
cap = cv2.VideoCapture('video.mp4')
```
3. 定义圆心标靶检测算法,用于检测每个测点的位置:
```python
def detect_circles(frame):
# 灰度化
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 中值滤波
gray = cv2.medianBlur(gray, 5)
# 圆心标靶检测
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
if circles is not None:
# 转换为整数
circles = np.round(circles[0, :]).astype("int")
return circles
else:
return None
```
4. 定义 Ganner Farneback 算法,用于提取测点的位移:
```python
def calculate_optical_flow(prev_frame, cur_frame, prev_points):
# 灰度化
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
cur_gray = cv2.cvtColor(cur_frame, cv2.COLOR_BGR2GRAY)
# 计算光流
cur_points, status, error = cv2.calcOpticalFlowPyrLK(prev_gray, cur_gray, prev_points, None, winSize=(15, 15), maxLevel=2, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
# 筛选出良好的点
good_new = cur_points[status == 1]
good_old = prev_points[status == 1]
# 计算位移
displacement = good_new - good_old
return good_new, displacement
```
5. 定义绘制位移时程曲线的函数:
```python
def plot_displacement(displacement):
# 绘制位移时程曲线
x = np.arange(0, len(displacement))
y = displacement[:, 1]
plt.plot(x, y)
plt.show()
```
6. 进入主循环,逐帧处理:
```python
# 读取第一帧
ret, prev_frame = cap.read()
prev_circles = detect_circles(prev_frame)
prev_points = np.array([[x, y] for x, y, r in prev_circles])
# 逐帧处理
while True:
# 读取当前帧
ret, cur_frame = cap.read()
if not ret:
break
cur_circles = detect_circles(cur_frame)
if cur_circles is not None:
cur_points = np.array([[x, y] for x, y, r in cur_circles])
# 计算位移
cur_points, displacement = calculate_optical_flow(prev_frame, cur_frame, prev_points)
# 绘制位移时程曲线
plot_displacement(displacement)
# 更新上一帧的信息
prev_frame = cur_frame.copy()
prev_points = cur_points.copy()
```
这样就完成了读取悬臂梁振动冲击视频,利用圆心标靶检测算法、Gunner Farneback算法提取测点的位移并绘制每个测点的位移时程曲线的完整算法。
阅读全文