YOLOv5可视化训练集的标注框和类别
- 导入必要的库
- 设置超参数
- 标签坐标反归一化
- 主函数
导入必要的库
import os
import shutil
from pathlib import Path
import numpy as np
import cv2
from tqdm import tqdm
import argparse
设置超参数
parser = argparse.ArgumentParser()
parser.add_argument('--imgs', type=str, default='', help='图像路径')
parser.add_argument('--labels', type=str, default='', help='标签路径')
parser.add_argument('--save', type=str, default='runs/GT', help='保存路径')
args = parser.parse_args()
img_folder = args.imgs
img_list = os.listdir(img_folder)
img_list.sort()
label_folder = args.labels
label_list = os.listdir(label_folder)
label_list.sort()
output_folder = args.save
labels = ['']
colormap = [(255, 255, 255)]
标签坐标反归一化
def xywh2xyxy(x, w1, h1, img):
label, x_, y_, w_, h_ = x
label = int(label)
label_ind = label
x_t = x_ * w1
y_t = y_ * h1
w_t = w_ * w1
h_t = h_ * h1
top_left_x = x_t - w_t / 2
top_left_y = y_t - h_t / 2
bottom_right_x = x_t + w_t / 2
bottom_right_y = y_t + h_t / 2
p1, p2 = (int(top_left_x), int(top_left_y)), (int(bottom_right_x), int(bottom_right_y))
cv2.rectangle(img, p1, p2, colormap[label_ind + 1], thickness=2, lineType=cv2.LINE_AA)
label = labels[label_ind]
if label:
w, h = cv2.getTextSize(label, 0, fontScale=2 / 3, thickness=2)[0]
outside = p1[1] - h - 3 >= 0
p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
cv2.rectangle(img, p1, p2, colormap[label_ind + 1], -1, cv2.LINE_AA)
cv2.putText(img, label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2), 0, 2 / 3, colormap[0],
thickness=2, lineType=cv2.LINE_AA)
return img
主函数
if Path(output_folder).exists():
shutil.rmtree(output_folder)
os.mkdir(output_folder)
for img in tqdm(img_list):
if not 'png' in img:
continue
image_path = img_folder + "/" + img
label_path = label_folder + "/" + img.split('.')[0] + '.txt'
img = cv2.imread(str(image_path))
h, w = img.shape[:2]
with open(label_path, 'r') as f:
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)
for x in lb:
img = xywh2xyxy(x, w, h, img)
cv2.imwrite(output_folder + '/' + '{}.png'.format(image_path.split('/')[-1][:-4]), img)