用python根据XML文件批量画出标注框

根据XML文件批量画出标注框

做一个项目需要很多流程,其中最为重要的是检查数据集,很多bug到最后发现是数据集标注错误,本文提供标注GT框的代码:

import os
import xml.dom.minidom
import cv2 as cv
from tqdm import tqdm

ImgPath = 'D:/Download/img_512_voc_xml/VOC2007/JPEGImages'
AnnoPath = 'D:/Download/img_512_voc_xml/VOC2007/Annotations'
FinalPath ='D:/Download/final_images'

imagelist = os.listdir(ImgPath)

for image in tqdm(imagelist):

    image_pre, ext = os.path.splitext(image)

    imgfile = ImgPath +"/"+ image
    xmlfile = AnnoPath +"/"+ image_pre + '.xml'
    finalfile = FinalPath +"/"+ image


    # 打开xml文档
    DOMTree = xml.dom.minidom.parse(xmlfile)
    # 得到文档元素对象
    collection = DOMTree.documentElement
    # 读取图片
    img = cv.imread(imgfile)

    filenamelist = collection.getElementsByTagName("filename")
    filename = filenamelist[0].childNodes[0].data
    # print(filename)
    # 得到标签名为object的信息
    objectlist = collection.getElementsByTagName("object")

    for objects in objectlist:
        # 每个object中得到子标签名为name的信息
        namelist = objects.getElementsByTagName('name')
        # 通过此语句得到具体的某个name的值
        objectname = namelist[0].childNodes[0].data

        bndbox = objects.getElementsByTagName('bndbox')
        for box in bndbox:
            x1_list = box.getElementsByTagName('xmin')
            x1 = int(float(x1_list[0].childNodes[0].data))
            y1_list = box.getElementsByTagName('ymin')
            y1 = int(float(y1_list[0].childNodes[0].data))
            x2_list = box.getElementsByTagName('xmax')
            x2 = int(float(x2_list[0].childNodes[0].data))
            y2_list = box.getElementsByTagName('ymax')
            y2 = int(float(y2_list[0].childNodes[0].data))
            cv.rectangle(img, (x1, y1), (x2, y2), (255, 255, 255), thickness=1)
            cv.putText(img, objectname, (x1, y1), cv.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 0),
                       thickness=1)
            cv.imwrite('%s' % finalfile, img)

效果图:

用python根据XML文件批量画出标注框_第1张图片
用python根据XML文件批量画出标注框_第2张图片

你可能感兴趣的:(小技巧代码,xml,opencv)