写一段利用python语言,从悬臂梁振动冲击视频中利用圆心标靶检测算法提取悬臂梁上6个测点的位移,并绘制每个测点的位移时程曲线的完整算法
时间: 2023-12-03 08:44:56 浏览: 32
为了实现从悬臂梁振动冲击视频中利用圆心标靶检测算法提取悬臂梁上6个测点的位移,并绘制每个测点的位移时程曲线,我们需要使用以下步骤:
1. 导入必要的库
我们需要导入NumPy、OpenCV和Matplotlib三个库。
```python
import numpy as np
import cv2
import matplotlib.pyplot as plt
```
2. 加载视频文件
我们需要使用OpenCV库中的`cv2.VideoCapture()`函数来加载视频文件。
```python
cap = cv2.VideoCapture('video.mp4')
```
3. 提取圆心标靶
我们需要使用OpenCV库中的`cv2.HoughCircles()`函数来提取圆心标靶。该函数可以在图像中检测圆形形状,返回圆心坐标和半径。
```python
while True:
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
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")
for (x, y, r) in circles:
cv2.circle(frame, (x, y), r, (0, 255, 0), 4)
```
4. 定位测点
我们需要根据圆心标靶的位置,定位悬臂梁上的6个测点。这可以通过计算圆心标靶与悬臂梁上测点的距离来实现。
```python
targets = np.array([(x,y) for (x, y, r) in circles])
points = np.array([[100, 300], [230, 300], [360, 300], [490, 300], [620, 300], [750, 300]])
distances = np.sqrt(np.sum((targets[:, None, :] - points[None, :, :]) ** 2, axis=-1))
mapping = np.argmin(distances, axis=1)
```
5. 提取位移
我们需要根据测点位置,提取悬臂梁上每个测点的位移。这可以通过计算圆心标靶的位置变化来实现。
```python
displacements = []
for i in range(6):
x = []
y = []
while True:
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
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")
for (x, y, r) in circles:
cv2.circle(frame, (x, y), r, (0, 255, 0), 4)
targets = np.array([(x,y) for (x, y, r) in circles])
displacement = targets[mapping[i]] - points[i]
displacements.append(displacement)
break
else:
break
```
6. 绘制位移时程曲线
我们需要使用Matplotlib库来绘制每个测点的位移时程曲线。
```python
plt.figure(figsize=(10,6))
plt.plot(displacements)
plt.xlabel('Frame')
plt.ylabel('Displacement (pixels)')
plt.legend(['Point 1', 'Point 2', 'Point 3', 'Point 4', 'Point 5', 'Point 6'])
plt.show()
```
完整代码如下: