import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Circle, Rectangle # 创建画布 fig = plt.figure(figsize=(14, 8)) fig.suptitle("Drone Environment Perception System", fontsize=16, fontweight='bold') # 创建子图布局 gs = fig.add_gridspec(3, 4) ax_cam = fig.add_subplot(gs[:, 0:2]) # 摄像头视图 ax_radar = fig.add_subplot(gs[0, 2:4], projection='polar') # 雷达图(极坐标) ax_path = fig.add_subplot(gs[1:, 2:4]) # 路径规划图 # 模拟摄像头画面(带YOLO检测结果) def plot_camera_view(ax): # 生成随机障碍物 np.random.seed(42) for _ in range(5): x = np.random.randint(20, 180) y = np.random.randint(20, 180) w = np.random.randint(10, 30) h = np.random.randint(10, 30) cls = np.random.choice(['person', 'car', 'tree', 'building']) conf = np.random.uniform(0.7, 0.95) # 绘制检测框 ax.add_patch(Rectangle((x, y), w, h, linewidth=2, edgecolor='r', facecolor='none')) ax.text(x, y - 5, f"{cls} {conf:.2f}", color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.7)) # 无人机位置 ax.plot(100, 100, 'ro', markersize=10) ax.text(105, 105, 'Drone', color='white', fontsize=10) # 设置参数 ax.set_title("Live Camera View with YOLO Detection") ax.set_facecolor('black') ax.set_xlim(0, 200) ax.set_ylim(0, 200) ax.set_xticks([]) ax.set_yticks([]) # 雷达图 def plot_radar(ax): ax.set_title("Obstacle Radar", pad=20) ax.set_theta_zero_location('N') # 设置0度方向为北方 ax.set_theta_direction(-1) # 设置顺时针方向 ax.set_rlim(0, 50) # 设置半径范围 # 生成障碍物极坐标 angles = np.random.rand(5) * 2 * np.pi distances = np.random.randint(5, 50, 5) sizes = np.random.randint(10, 50, 5) ax.scatter(angles, distances, s=sizes, c='r', alpha=0.6) ax.fill_between(np.linspace(0, 2 * np.pi, 100), 0, 50, color='g', alpha=0.1) # 路径规划图 def plot_path_planning(ax): # 生成路径 x = np.linspace(0, 100, 100) y = 5 * np.sin(x / 10) + 0.1 * (x - 50) ** 2 # 障碍物 ax.add_patch(Circle((30, 30), 10, color='gray')) ax.add_patch(Rectangle((60, 40), 15, 15, color='gray')) # 路径 ax.plot(x, y, 'g-', linewidth=2, label='Planned Path') ax.plot(0, 0, 'bo', markersize=10, label='Start') ax.plot(100, 100, 'y*', markersize=15, label='Goal') ax.set_title("Path Planning (A* Algorithm)") ax.set_xlim(0, 100) ax.set_ylim(0, 100) ax.legend(loc='upper right') ax.grid(True) # 状态信息 status_text = """Status: Altitude: 50.2m Speed: 8.4m/s Obstacles Detected: 5 Battery: 78% GPS Satellites: 12 """ fig.text(0.05, 0.15, status_text, fontfamily='monospace', bbox=dict(facecolor='lightgray', alpha=0.8)) # 绘制所有组件 plot_camera_view(ax_cam) plot_radar(ax_radar) plot_path_planning(ax_path) plt.tight_layout() plt.show() 圈框的图片不合适,我想自己加入 图片然后框选在生成剩下的效果
时间: 2025-07-06 09:41:42 浏览: 16
<think>好的,我现在需要解决的问题是如何修改现有的Python代码,使其能够使用用户自定义的图片,并在图片上添加检测框,同时保持其他部分的效果不变。用户提到原来的代码中模拟的摄像头画面不合适,想用自己的图片并框选后生成剩下的效果。
首先,我需要回顾原始代码的结构。代码使用matplotlib创建了三个子图:摄像头视图(ax_cam)、雷达图(ax_radar)和路径规划图(ax_path)。其中,摄像头视图部分用随机生成的矩形框模拟YOLO检测结果,用户希望替换这部分为真实图片,并在图片上绘制检测框。
步骤一:替换模拟数据为真实图片。原来的plot_camera_view函数生成了随机障碍物,并绘制在ax_cam上。要替换为真实图片,需要使用plt.imread或类似函数加载图片,然后通过ax.imshow显示图片。需要注意图片的尺寸和坐标系的适配,可能需要调整ax的xlim和ylim,或者使用extent参数来匹配图片的实际尺寸。
步骤二:处理检测框的位置。用户可能需要提供检测框的坐标信息,或者从文件(如YOLO的txt标注文件)中读取。假设用户已经有检测数据,可能是以列表或文件形式存储的,每个检测结果包含类别、置信度、边界框坐标(如x_center, y_center, width, height,或者是左上角坐标和宽高)。需要将这些坐标转换为绘图所需的格式,可能需要坐标系的转换,因为图片显示时可能使用像素坐标系,而matplotlib的默认坐标可能不同。
步骤三:调整绘图参数。原来的代码中,ax_cam设置了xlim和ylim为0到200,这是因为模拟的图片是200x200的。使用真实图片后,需要根据图片的实际尺寸调整这些范围,或者让matplotlib自动调整。例如,如果图片是640x480,则ax.set_xlim(0, 640)和ax.set_ylim(0, 480),或者在imshow时指定extent参数。
步骤四:保持其他图表不变。用户希望保留雷达图和路径规划图的效果,因此只需要修改摄像头视图的部分,其他部分不需要改动。
可能的挑战:
1. 图片的显示和坐标对齐问题。需要确保检测框的位置正确,尤其是在使用imshow后,坐标原点可能在左上角还是左下角的问题。matplotlib的imshow默认将原点放在左上角,而绘图的坐标系可能默认左下角为原点,这可能导致检测框的位置错误。需要调整坐标轴的方向,或者在处理检测框坐标时进行转换。
解决方案:
- 使用ax.imshow(img, origin='upper')来保持图片的原点在左上角,这样检测框的坐标可以直接对应像素坐标。
- 或者在加载图片时,将Y轴进行反转,使得原点在左下角,与常规的数学坐标系一致。这取决于用户的数据格式。
示例代码修改:
在plot_camera_view函数中,首先加载用户提供的图片,并显示在ax_cam上。然后读取检测框的数据,可能来自文件或列表,然后绘制矩形和文本。
假设用户有一个图片文件“drone_view.jpg”,并且检测数据存储在一个列表中,例如:
detections = [
{'class': 'person', 'conf': 0.85, 'x': 100, 'y': 150, 'w': 30, 'h': 50},
...
]
修改后的plot_camera_view函数可能如下:
def plot_camera_view(ax):
# 加载图片
img = plt.imread('drone_view.jpg')
ax.imshow(img, origin='upper') # 假设原点在左上角
# 假设detections是用户提供的检测列表
detections = [...] # 用户需要提供自己的检测数据
for detection in detections:
x = detection['x']
y = detection['y']
w = detection['w']
h = detection['h']
cls = detection['class']
conf = detection['conf']
# 绘制矩形框,注意坐标可能需要调整(例如,从中心坐标转为左上角)
# 如果检测数据是中心坐标,需要转换为左上角坐标
# rect_x = x - w/2
# rect_y = y - h/2
rect = Rectangle((x, y), w, h, linewidth=2, edgecolor='r', facecolor='none')
ax.add_patch(rect)
ax.text(x, y - 5, f"{cls} {conf:.2f}", color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.7))
# 无人机位置可能需要根据图片调整
ax.plot(...)
ax.text(...)
# 设置参数,可能需要根据图片尺寸调整
ax.set_xlim(0, img.shape[1])
ax.set_ylim(img.shape[0], 0) # 保持原点在左上角
用户需要准备自己的图片和检测数据,并替换模拟数据部分。此外,可能需要调整无人机的标记位置,确保其在图片中的正确位置。
如果用户的检测数据是YOLO格式(归一化的中心坐标、宽高),则需要将这些坐标转换为绝对像素坐标。例如,如果图片尺寸为width和height,则:
x_center = x_center_normalized * width
y_center = y_center_normalized * height
w = w_normalized * width
h = h_normalized * height
然后左上角坐标为 (x_center - w/2, y_center - h/2)
因此,在代码中需要进行这样的转换,然后绘制矩形。
总结修改步骤:
1. 加载用户图片,显示在ax_cam。
2. 读取检测数据,转换为正确的坐标格式。
3. 绘制检测框和标签。
4. 调整坐标轴范围和设置,确保图片和框正确显示。</think>为了使代码能够使用自定义图片并添加检测框,需要修改摄像头视图部分的代码,使用真实图片数据和检测框坐标:
```python
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def plot_camera_view(ax, img_path, detections):
"""参数说明:
img_path: 自定义图片路径
detections: 检测框列表,格式示例:
[{
'class': 'person',
'confidence': 0.9,
'bbox': (x_min, y_min, width, height) # 绝对像素坐标
}, ...]
"""
# 加载自定义图片
img = plt.imread(img_path)
ax.imshow(img, origin='upper') # 保持像素坐标系
# 绘制检测框
for detection in detections:
x, y, w, h = detection['bbox']
rect = Rectangle((x, y), w, h,
linewidth=2,
edgecolor='r',
facecolor='none')
ax.add_patch(rect)
ax.text(x, y-15,
f"{detection['class']} {detection['confidence']:.2f}",
color='white', fontsize=8,
bbox=dict(facecolor='red', alpha=0.7))
# 设置坐标轴参数
ax.set_title("Live Camera View with YOLO Detection")
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim(0, img.shape[1])
ax.set_ylim(img.shape[0], 0) # 保持图片方向正确
# 使用示例
detections = [
{
'class': 'person',
'confidence': 0.89,
'bbox': (100, 150, 30, 50) # (x,y,w,h)
},
# 添加更多检测结果...
]
fig = plt.figure(figsize=(14, 8))
ax_cam = fig.add_subplot(131)
plot_camera_view(ax_cam, "your_image.jpg", detections)
# 其他子图(雷达和路径规划)保持原有代码不变
plt.show()
```
**修改说明:**
1. `plot_camera_view` 函数现在接受图片路径和检测数据作为参数
2. 使用绝对像素坐标系统(原点在左上角),与常规图像处理坐标系一致
3. 检测框数据需要以绝对像素坐标提供(x_min, y_min, width, height)
4. 移除了模拟数据生成部分,改用真实图片和检测数据
**注意事项:**
1. 确保检测框坐标使用图片的实际像素坐标
2. 图片格式支持常见格式(JPG/PNG等)
3. 如果使用YOLO格式的归一化坐标,需要先进行转换:
```python
# YOLO格式转换示例(假设img_width和img_height已知)
def yolo_to_pixel(yolo_coords, img_width, img_height):
x_center, y_center, w, h = yolo_coords
x = (x_center - w/2) * img_width
y = (y_center - h/2) * img_height
width = w * img_width
height = h * img_height
return (x, y, width, height)
```
阅读全文
相关推荐



















