from lxml.etree import Element, SubElement, tostring


def create_xml(boxs,img_shape,xml_path):
    """
    创建xml文件,依次写入xml文件必备关键字
    :param boxs:   txt文件中的box
    :param img_shape:   图片信息,xml中需要写入WHC
    :return:
    """
    node_root = Element('annotation')
    node_folder = SubElement(node_root, 'folder')
    node_folder.text = 'Images'
    node_filename = SubElement(node_root, 'filename')
    node_filename.text = str(img_shape[3])
    node_size = SubElement(node_root, 'size')
    node_width = SubElement(node_size, 'width')
    node_width.text = str(img_shape[1])
    node_height = SubElement(node_size, 'height')
    node_height.text = str(img_shape[0])
    node_depth = SubElement(node_size, 'depth')
    node_depth.text = str(img_shape[2])

    if len(boxs)>=1:        # 循环写入box
        for box in boxs:
            node_object = SubElement(node_root, 'object')
            node_name = SubElement(node_object, 'name')
            # if str(list_[4]) == "person":                # 根据条件筛选需要标注的标签,例如这里只标记person这类,不符合则直接跳过
            #     node_name.text = str(list_[4])
            # else:
            #     continue
            node_name.text = str(list(box.keys())[0])
            node_difficult = SubElement(node_object, 'difficult')
            node_difficult.text = '0'
            node_bndbox = SubElement(node_object, 'bndbox')
            node_xmin = SubElement(node_bndbox, 'xmin')
            node_xmin.text = str(int(list(box.values())[0][0]))
            node_ymin = SubElement(node_bndbox, 'ymin')
            node_ymin.text = str(int(list(box.values())[0][1]))
            node_xmax = SubElement(node_bndbox, 'xmax')
            node_xmax.text = str(int(list(box.values())[0][2]))
            node_ymax = SubElement(node_bndbox, 'ymax')
            node_ymax.text = str(int(list(box.values())[0][3]))

    xml = tostring(node_root, pretty_print=True)   # 格式化显示,该换行的换行

    file_name = img_shape[3].split(".")[0]
    filename = xml_path+"/{}.xml".format(file_name)

    f = open(filename, "wb")
    f.write(xml)
    f.close()