数据格式如下,且一张样本里只有1个目标
import os
# 适用数据格式: file_name width height x1 y1 x2 y2 category 均为原始尺寸
csv_file = r'/home/luoye/myProject/ultralytics-main/annotations.csv'
save_folder = r'/home/luoye/myProject/ultralytics-main/labels'
with open(csv_file, 'r') as f:
for i, line in enumerate(f):
if i == 0: # 跳过第一行
continue
# print(line)
line = line.split(',')
# print(line)
txt_name = line[0][:-4] # 支持后缀长度3的图像名.png
save_path = save_folder + '/'+ txt_name + '.txt' # 拼接保存路径
print(save_path)
img_w = int(line[1]) # 图片的宽和高
img_h = int(line[2])
x1, y1, x2, y2 = float(line[3]) / img_w, float(line[4]) / img_h, float(line[5]) / img_w, float(line[6]) / img_h # 转float,归一化
w = x2 - x1
h = y2 - y1
centerX, centerY, w, h = x1 + w / 2, y1 + h / 2, w, h
label = line[-1][:-1] # 去掉最后的\n
print(label)
with open(save_path,'w')as f:
f.write(f'{label} {centerX} {centerY} {w} {h}')
画GT框——验证转换是否正确
import os
import cv2
import numpy as np
def read_gt(path_root_imgs,path_root_labels):# 总的检测根目录
type_object = '.txt'
gt_dict=dict()
for ii in os.walk(path_root_imgs):
for j in ii[2]:
type = j.split(".")[1]#判断遍历内容是否都为图像
if type != 'png':
continue
path_img = os.path.join(path_root_imgs, j)
# print(path_img)
label_name = j[:-4]+type_object
label_num=j[:-4][6:]
path_label = os.path.join(path_root_labels, label_name)
# print(path_label)
f = open(path_label, 'r+', encoding='utf-8')
if os.path.exists(path_label) == True:
img = cv2.imread(path_img)
w = img.shape[1]
h = img.shape[0]
# new_lines = []
img_tmp = img.copy()
# gt_boxes = []#初始化boxes
while True:
line = f.readline()
if line:
msg = line.split(" ")
# print(x_center,",",y_center,",",width,",",height)
x1 = int((float(msg[1]) - float(msg[3]) / 2) * w) # x_center - width/2
y1 = int((float(msg[2]) - float(msg[4]) / 2) * h) # y_center - height/2
x2 = int((float(msg[1]) + float(msg[3]) / 2) * w) # x_center + width/2
y2 = int((float(msg[2]) + float(msg[4]) / 2) * h) # y_center + height/2
gt_box=[x1,y1,x2,y2]
# gt_boxes.append(gt_box)
# print(x1,",",y1,",",x2,",",y2)
d = {'Caitlyn': 21, 'Darius': 45, 'Bard': 33, 'Ezreal': 24, 'Akali': 31, 'Fiora': 43}
cv2.rectangle(img_tmp,(x1,y1),(x2,y2),(0,0,255),1)
else :
break
# gt_dict[int(label_num)]=gt_boxes#全部box传入字典
cv2.imshow("show", img_tmp)
c = cv2.waitKey(0)
cv2.destroyAllWindows()
# gt_dict={k: gt_dict[k] for k in sorted(gt_dict.keys())}
# return gt_dict
# gt_box=gt_dict.values()
# print(gt_box)
# print(gt_dict[0])
# print(gt_box.shape)
# return gt_dict
# print(len(gt_dict))
if __name__ == '__main__':
read_gt(r'E:\datasets\archive(yolo)\images',r'E:\datasets\archive(yolo)\labels')