使用训练好的YOLOV5模型生成XML标注文件

        训练完一个YOLOV5模型后,可以使用模型快速生成新图片数据的xml标注文件,下面是生成xml标注文件的具体脚本:

# YOLOv5  by Ultralytics, GPL-3.0 license

import os
import sys
from pathlib import Path

import torch
import torch.backends.cudnn as cudnn

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.torch_utils import select_device, time_sync

import xml.etree.ElementTree as et
import glob

@torch.no_grad()
def run(weights=ROOT / 'runs/train/exp/weights/best.pt',  # model.pt path(s)
        source='/home/images/source',  # file/dir/URL/glob, 0 for webcam
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.4,  # confidence threshold
        iou_thres=0.2,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='0',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=False,  # save results to *.txt
        save_conf=False,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        ):
    source = str(source)

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Load model
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn)
    stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
    imgsz = check_img_size(imgsz, s=stride)  # check image size
    # print(names)
    # names=["car", "van", "bus", "truck", "other", 'left_line', 'right_line']
    # print(names)
    # Half
    half &= (pt or jit or engine) and device.type != 'cpu'  # half precision only supported by PyTorch on CUDA
    if pt or jit:
        model.model.half() if half else model.model.float()

    # Run inference
    model.warmup(imgsz=(1, 3, *imgsz), half=half)  # warmup
    dt, seen = [0.0, 0.0, 0.0], 0

    index = 0
    image_list = glob.glob(os.path.join(source, "*.jpg"))
    for image_path in image_list:
        dataset = LoadImages(image_path, img_size=imgsz, stride=stride, auto=pt)
        bs = 1  # batch_size

        for path, im, im0s, vid_cap, s in dataset:
            t1 = time_sync()
            im = torch.from_numpy(im).to(device)
            im = im.half() if half else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3:
                im = im[None]  # expand for batch dim
            t2 = time_sync()
            dt[0] += t2 - t1

            # Inference
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)
            t3 = time_sync()
            dt[1] += t3 - t2

            # NMS

            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
            dt[2] += time_sync() - t3

            # Process predictions
            for i, det in enumerate(pred):  # per image
                # if webcam:  # batch_size >= 1
                #     p, im0, frame = path[i], im0s[i].copy(), dataset.count
                #     s += f'{i}: '
                # else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

                p = Path(p)  # to Path

                root = et.Element("annotation")
                folder = et.SubElement(root, "folder")
                folder.text = "test"
                filename = et.SubElement(root, "filename")
                filename.text = p.name
                # path = et.SubElement(root, "path")
                # path.text = json_path.replace(".txt", ".jpg")
                source = et.SubElement(root, "source")
                database = et.SubElement(source, "database")
                database.text = "Unknown"
                size = et.SubElement(root, "size")
                width = et.SubElement(size, "width")
                width.text = str(im0s.shape[1])
                height = et.SubElement(size, "height")
                height.text = str(im0s.shape[0])
                depth = et.SubElement(size, "depth")
                depth.text = "3"
                segmented = et.SubElement(root, "segmented")
                segmented.text = "0"

                if len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()

                    # Print results
                    for c in det[:, -1].unique():
                        n = (det[:, -1] == c).sum()  # detections per class
                        s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                    # Write results
                    for *xyxy, conf, cls in reversed(det):
                        c = int(cls)  # integer class
                        # print(c)
                        # if c == 5 or c == 6:
                        #     continue
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')

                        object = et.SubElement(root, "object")
                        name = et.SubElement(object, "name")
                        name.text = names[c]
                        # print(names[c])
                        pose = et.SubElement(object, "pose")
                        pose.text = "Unspecified"
                        truncated = et.SubElement(object, "truncated")
                        truncated.text = "0"
                        difficult = et.SubElement(object, "difficult")
                        difficult.text = "0"
                        occluded = et.SubElement(object, "occluded")
                        occluded.text = "0"
                        bndbox = et.SubElement(object, "bndbox")

                        xmin = et.SubElement(bndbox, "xmin")
                        xmin.text = str(int(xyxy[0]))
                        ymin = et.SubElement(bndbox, "ymin")
                        ymin.text = str(int(xyxy[1]))
                        xmax = et.SubElement(bndbox, "xmax")
                        xmax.text = str(int(xyxy[2]))
                        ymax = et.SubElement(bndbox, "ymax")
                        ymax.text = str(int(xyxy[3]))
                pretty_xml(root, '  ', '\n')
                tree = et.ElementTree(root)
                tree.write(image_path.replace(".jpg", ".xml"), encoding="utf-8")
                index += 1
                print(image_path, index)

def pretty_xml(element, indent, newline, level=0):  # elemnt为传进来的Elment类,参数indent用于缩进,newline用于换行
    if element:  # 判断element是否有子元素
        if (element.text is None) or element.text.isspace():  # 如果element的text没有内容
            element.text = newline + indent * (level + 1)
        else:
            element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * (level + 1)
            # else:  # 此处两行如果把注释去掉,Element的text也会另起一行
            # element.text = newline + indent * (level + 1) + element.text.strip() + newline + indent * level
    temp = list(element)  # 将element转成list
    for subelement in temp:
        if temp.index(subelement) < (len(temp) - 1):  # 如果不是list的最后一个元素,说明下一个行是同级别元素的起始,缩进应一致
            subelement.tail = newline + indent * (level + 1)
        else:  # 如果是list的最后一个元素, 说明下一行是母元素的结束,缩进应该少一个
            subelement.tail = newline + indent * level
        pretty_xml(subelement, indent, newline, level=level + 1)  # 对子元素进行递归操作

if __name__ == "__main__":

    run()

         以上代码需要修改run函数中的:weights为yolov5模型路径,source为新图片数据所在文件夹,生成的xml也在source路径下。亲测可用!

你可能感兴趣的:(YOLO,YOLO,xml,深度学习)