读取xml文件并在图片上面进行标注

读取单张图片

import xml.etree.ElementTree as ET
import os, cv2

xml_file = '/home/zhaotongdong/data/华录杯广告/训练集/Annotations/train_29641.xml'
tree = ET.parse(xml_file)
root = tree.getroot()
imgfile = '/home/zhaotongdong/data/华录杯广告/训练集/Illegal_adv_images/train_29641.jpg'
im = cv2.imread(imgfile)
for object in root.findall('object'):
    object_name = object.find('name').text
    Xmin = int(object.find('bndbox').find('xmin').text)
    Ymin = int(object.find('bndbox').find('ymin').text)
    Xmax = int(object.find('bndbox').find('xmax').text)
    Ymax = int(object.find('bndbox').find('ymax').text)
    color = (4, 250, 7)
    cv2.rectangle(im, (Xmin, Ymin), (Xmax, Ymax), color, 2)
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(im, object_name, (Xmin, Ymin - 7), font, 0.5, (6, 230, 230), 2)
    cv2.imshow('img', im)
    cv2.waitKey(0)

读取多张图片

import xml.etree.ElementTree as ET
import os, cv2
from tqdm import tqdm

annota_dir = '/home/zhaotongdong/data/华录杯广告/训练集/Annotations/'
img_dir = '/home/zhaotongdong/data/华录杯广告/训练集/Illegal_adv_images/'

def divide_img(oriname):
    img_file = os.path.join(img_dir, oriname + '.jpg')
    im = cv2.imread(img_file)

    xml_file = os.path.join(annota_dir, oriname + '.xml')  # 读取每个原图像的xml文件
    tree = ET.parse(xml_file)
    root = tree.getroot()
#im = cv2.imread(imgfile)
    for object in root.findall('object'):
        object_name = object.find('name').text
        Xmin = int(object.find('bndbox').find('xmin').text)
        Ymin = int(object.find('bndbox').find('ymin').text)
        Xmax = int(object.find('bndbox').find('xmax').text)
        Ymax = int(object.find('bndbox').find('ymax').text)
        color = (4, 250, 7)
        cv2.rectangle(im, (Xmin, Ymin), (Xmax, Ymax), color, 2)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(im, object_name, (Xmin, Ymin - 7), font, 0.5, (6, 230, 230), 2)
        cv2.imshow('01', im)
        cv2.waitKey(0)

   # img_name = oriname + '.jpg'
    #to_name = os.path.join(target_dir1, img_name)
    #cv2.imwrite(to_name, im)

img_list = os.listdir(img_dir)
for name in img_list:
    divide_img(name.rstrip('.jpg'))
    原文作者:iddd
    原文地址: https://blog.csdn.net/AWhiteDongDong/article/details/108156240
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞