效果
代码
import os
import cv2
from tqdm import tqdm
import xml.etree.ElementTree as ET
if __name__ == '__main__':
test_imagesdir = r'F:\A_Publicdatasets\RDD2020-1202\train_valid\RDD2020_together\images\test'
test_xmlsdir = r'F:\A_Publicdatasets\RDD2020-1202\train_valid\RDD2020_together\annotations\test'
save_rectangle_dir = r'F:\A_Publicdatasets\RDD2020-1202\train_valid\RDD2020_together\images\test_rectangle'
colors = {'D00': [255, 0, 0], 'D10': [0, 255, 0], 'D20': [0, 0, 255], 'D40': [250, 140, 53]}
os.makedirs(save_rectangle_dir, exist_ok=True)
for imgfile in tqdm(os.listdir(test_imagesdir)):
filename = imgfile[:-4]
image = cv2.imread(os.path.join(test_imagesdir, imgfile))
xml_path = os.path.join(test_xmlsdir, filename + '.xml')
tree = ET.parse(xml_path)
root = tree.getroot()
objects = root.findall('object')
for obj in objects:
cls = obj.find('name').text
bndbox = obj.find('bndbox')
xmin = int(bndbox.find('xmin').text)
xmax = int(bndbox.find('xmax').text)
ymin = int(bndbox.find('ymin').text)
ymax = int(bndbox.find('ymax').text)
if xmin >= xmax or ymin >= ymax:
print(imgfile)
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), colors[cls][::-1], thickness=1)
cv2.putText(image, cls, (xmin, ymin - 2), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=colors[cls][::-1], thickness=1, lineType=cv2.LINE_AA)
save_path = os.path.join(save_rectangle_dir, imgfile)
cv2.imwrite(save_path, image)