为了对比训练结果和标签是否一致,有时候需要可视化标签图像进行对比查看,可通过如下代码查看自己标签在图像中的具体框
import os
import cv2
import numpy as np
images_path = 'images/val'
labels_path = 'labels/val'
output_path = 'output'
os.makedirs(output_path, exist_ok=True)
image_files = [f for f in os.listdir(images_path) if f.endswith(('.bmp', '.jpg', '.jpeg', '.png'))]
for image_file in image_files:
image_path = os.path.join(images_path, image_file)
image = cv2.imread(image_path)
height, width, _ = image.shape
label_file = os.path.splitext(image_file)[0] + '.txt'
label_path = os.path.join(labels_path, label_file)
if os.path.exists(label_path):
with open(label_path, 'r') as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split()
class_id = int(parts[0])
points = list(map(float, parts[1:]))
points = [(int(p[0] * width), int(p[1] * height)) for p in zip(points[::2], points[1::2])]
points = [(points[0][0], points[0][1]), (points[1][0], points[1][1]),
(points[2][0], points[2][1]), (points[3][0], points[3][1])]
cv2.polylines(image, [np.array(points, np.int32)], isClosed=True, color=(0, 255, 0), thickness=2)
output_image_path = os.path.join(output_path, image_file)
cv2.imwrite(output_image_path, image)
补充,部分人使用的格式为xywh,进行如下判断执行
if len(parts) == 5:
class_id = int(parts[0])
center_x = float(parts[1]) * width
center_y = float(parts[2]) * height
bbox_w = float(parts[3]) * width
bbox_h = float(parts[4]) * height
top_left = (int(center_x - bbox_w / 2), int(center_y - bbox_h / 2))
bottom_right = (int(center_x + bbox_w / 2), int(center_y + bbox_h / 2))
cv2.rectangle(image, top_left, bottom_right, color=(255, 0, 0), thickness=2)