文章目录
效果
代码
- 稍微参考了一下以前的代码:【脚本】绘制矩形框,文字(用cv2)【草稿暂存】
- 使用方法:根据注释,更改代码前4行参数即可
import os
import cv2
from tqdm import tqdm
import xml.etree.ElementTree as ET
if __name__ == '__main__':
test_imagesdir = r'F:A_PublicdatasetsRDD2020-1202 rain_validRDD2020_togetherimages est' # 图片文件夹
test_xmlsdir = r'F:A_PublicdatasetsRDD2020-1202 rain_validRDD2020_togetherannotations est' # 对应的xml文件夹
save_rectangle_dir = r'F:A_PublicdatasetsRDD2020-1202 rain_validRDD2020_togetherimages est_rectangle' # 存放文件夹
colors = {'D00': [255, 0, 0], 'D10': [0, 255, 0], 'D20': [0, 0, 255], 'D40': [250, 140, 53]} # D00红色, D10绿色, D20蓝色, D40橘色,自己设定类别名以及对应的颜色
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是BGR,所以这里将颜色倒序一下
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)