# 标签xml转txt以及无xml的负样本空txt
import xml.etree.ElementTree as ET
import os, cv2
from os import getcwd

sets = ['train', 'val', 'test']

classes = ['tag', 'bandage', 'word', 'package']


def convert(size, box):
    dw = 1. / (size[0])
    dh = 1. / (size[1])
    x = (box[0] + box[1]) / 2.0 - 1
    y = (box[2] + box[3]) / 2.0 - 1
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    y = y * dh
    w = w * dw
    h = h * dh
    return x, y, w, h


def convert_annotation(image_id, imgname_list, label_path, Annotation_path, image_path):
    out_file = open(label_path + '%s.txt' % (image_id), 'w')
    if os.path.exists(Annotation_path + '%s.xml' % (image_id)):
        try:
            in_file = open(Annotation_path + '%s.xml' % (image_id), encoding='UTF-8')
            tree = ET.parse(in_file)
            root = tree.getroot()
            size = root.find('size')
            # if size!=None:
            #    w = int(size.find('width').text)
            #    h = int(size.find('height').text)
            # else:
            img_name = image_id + ".jpg"
            img_path = image_path + f"{img_name}"
            img_data_ = cv2.imread(img_path)
            h, w = img_data_.shape[0], img_data_.shape[1]

            for obj in root.iter('object'):
                # difficult = obj.find('difficult').text
                # difficult = obj.find('Difficult').text
                cls = obj.find('name').text
                # cls = cls[:13]
                # print("cls:", cls, len(cls))
                # if cls not in classes or int(difficult) == 1:
                #     continue
                try:
                    cls_id = classes.index(cls)
                    xmlbox = obj.find('bndbox')
                    b = (
                        float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text),
                        float(xmlbox.find('ymin').text),
                        float(xmlbox.find('ymax').text))

                    b1, b2, b3, b4 = b
                    # 标注越界修正
                    if b2 > w:
                        b2 = w
                    if b4 > h:
                        b4 = h
                    b = (b1, b2, b3, b4)
                    bb = convert((w, h), b)
                    out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')

                except Exception as e:
                    print(e, image_id)
                    imgname_list.append(image_id)
        except Exception as e:
            print('error:', e, image_id)
    else:
        out_file.write('\n')


# abs_path = os.getcwd()


image_path = '/home/lc/data_center/gift/v2/images/'  # img实际存放地址
Annotation_path = '/home/lc/data_center/gift/v2/xmls/'  # xml实际存放地址
label_path = '/home/lc/data_center/gift/v2/labels/'  # 保存路径

# wd = getcwd()
imgname_list = []
for image_set in sets:
    if not os.path.exists(label_path):
        os.makedirs(label_path)
    # image_ids = open('data/ImageSets/Main/%s.txt' % (image_set), encoding='gbk').read().strip().split()
    # image_ids = open('data/ImageSets/Main_0820/%s.txt' % (image_set)).read().strip().split()
    image_ids = open('/home/lc/data_center/gift/yolov10_data/Main/%s.txt' % (image_set)).read().split('\n')
    list_file = open('/home/lc/data_center/gift/yolov10_data/%s.txt' % (image_set), 'w')
    for image_id in image_ids:
        list_file.write(image_path + '%s.jpg\n' % (image_id))
        # print(image_id, "Converting...")
        convert_annotation(image_id, imgname_list, label_path, Annotation_path, image_path)

    list_file.close()
with open('error_img.txt', 'w+') as f:
    for i_name in imgname_list:
        f.write(i_name + '\n')
print("error imgname_list:", imgname_list)
