使用训练好的YOLOV5模型在已有XML标注文件中添加新类别

        训练完一个YOLOV5模型后,可以使用模型快速在已有XML标注文件中添加新类别,下面是在已有XML标注文件中添加新类别的具体脚本:

# YOLOv5  by Ultralytics, GPL-3.0 license

import argparse
import os
import sys
from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn
import glob
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.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
import xml.etree.ElementTree as et

@torch.no_grad()
def run(weights=ROOT / 'weights/yolov5x.pt',  # model.pt path(s)
        source='/home/image/imgs_xml',  # file/dir/URL/glob, 0 for webcam
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        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='',  # 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, data=data)
    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

    # Half
    half &= (pt or jit or onnx or engine) and device.type != 'cpu'  # FP16 supported on limited backends with CUDA
    if pt or jit:
        model.model.half() if half else model.model.float()

    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
        # vid_path, vid_writer = [None] * bs, [None] * bs

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

        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


            for i, det in enumerate(pred):  # per image
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
                p = Path(p)  # to Path
                # save_path = os.path.join(source, p.name)  # im.jpg
                tree_ = et.ElementTree()
                # tree_.parse(image_path.replace(".jpg", ".xml").replace("JPEGImages","Annotations"))
                tree_.parse(image_path.replace(".jpg", ".xml"))
                root = tree_.getroot()

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

                    # Write results
                    for *xyxy, conf, cls in reversed(det):
                        # print(xyxy)
                        c = int(cls)  # integer class
                        if c == 0:
                            object = et.SubElement(root, "object")
                            name = et.SubElement(object, "name")
                            name.text = "person"
                            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")
                    # tree.write(image_path.replace(".jpg", ".xml").replace("JPEGImages","Annotations"), encoding="utf-8")
                    print(image_path, index)
                    index += 1


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标注文件所在文件夹,修改的xml也在source路径下。亲测可用!

你可能感兴趣的:(YOLO,YOLO,xml,人工智能)