import cv2
import matplotlib.pyplot as plt
import numpy as np
def draw_kitti_labels(label_path, img_path, labels, is_show=True):
# 读取图像
img = cv2.imread(img_path)
# 根据标签数量自动生成颜色(这里使用HSV色彩空间来生成不同颜色)
np.random.seed(42) # 为了可重复性
colors = {label: tuple(np.random.randint(0, 255, 3).tolist()) for label in labels}
# 读取标签文件
with open(label_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split()
label = parts[0]
x_min, y_min, x_max, y_max = map(int, parts[4:8])
color = colors.get(label, (255, 255, 255)) # 默认颜色为白色
# 绘制矩形框
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color, 2)
# 添加标签
cv2.putText(img, label, (x_min, y_min - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
if is_show:
# 使用 matplotlib 显示图像
plt.figure(figsize=(10, 10))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
return img
使用方法
b=draw_kitti_labels(label_path_kitti, image_path, labels,is_show)