这么多篇csdn没有一篇令人满意的,真是垃圾桶吧这里
import numpy as np
import cv2
import matplotlib.pyplot as plt
# 坐标转换,原始存储的是YOLOv5格式
# Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
def draw_yolo_labels(label_path, img_path,labels:list, is_show=True):
# 读取图像
img = cv2.imread(img_path)
h1, w1 = img.shape[:2]
# 读取 labels
with open(label_path, 'r', encoding='utf-8') as f:
boxes = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)
colors = {'chenpidan': (0, 0, 255), 'ckool': (0, 255, 0), 'meiyitian': (255, 0, 0)}
for box in boxes:
label_idx, x, y, w, h = box
label = labels[int(label_idx)]
color = colors[label]
# 反归一化
x_t = int(x * w1)
y_t = int(y * h1)
w_t = int(w * w1)
h_t = int(h * h1)
# 计算坐标
top_left_x = int(x_t - w_t / 2)
top_left_y = int(y_t - h_t / 2)
bottom_right_x = int(x_t + w_t / 2)
bottom_right_y = int(y_t + h_t / 2)
# 绘制矩形框
cv2.rectangle(img, (top_left_x, top_left_y), (bottom_right_x, bottom_right_y), color, 2)
# 添加标签
cv2.putText(img, label, (top_left_x, top_left_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
if is_show:
# 使用 matplotlib 在 Jupyter 中显示图像
plt.figure(figsize=(10, 10))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # 转换为 RGB 格式以正确显示颜色
plt.axis('off') # 关闭坐标轴
plt.show()
return img
使用例
label_path = r'label.txt'
image_path = r'label.jpg'
labels = ['class1', 'c2', 'c3']
a=draw_yolo_labels(label_path, image_path)