yolov5自动标注挑选置信度低的测试样本加入训练
import os
import sys
from pathlib import Path
import numpy as np
import cv2
import torch
import torch.backends.cudnn as cudnn
from tqdm import tqdm
import shutil
cwd = os.getcwd()
FILE = Path(cwd).resolve()
ROOT = FILE.parents[0]
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT))
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))
from models.common import DetectMultiBackend
from utils.dataloaders 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_boxes, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
weights = new_dir + "/weights/last.pt"
source=ROOT / 'data/images'
data=ROOT / 'data/coco128.yaml'
imgsz=(640, 640)
conf_thres=0.25
iou_thres=0.45
max_det=1000
device='0'
classes=None
agnostic_nms=False
augment=False
visualize=False
half=False
dnn=False
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)
half &= (pt or jit or onnx or engine) and device.type != 'cpu'
if pt or jit:
model.model.half() if half else model.model.float()
def detect(img):
model.warmup(imgsz=(1, 3, *imgsz))
dt, seen = [0.0, 0.0, 0.0], 0
im0 = img
im = letterbox(im0, imgsz, stride, auto=pt)[0]
im = im.transpose((2, 0, 1))[::-1]
im = np.ascontiguousarray(im)
t1 = time_sync()
im = torch.from_numpy(im).to(device)
im = im.half() if half else im.float()
im /= 255
if len(im.shape) == 3:
im = im[None]
t2 = time_sync()
dt[0] += t2 - t1
pred = model(im, augment=augment, visualize=visualize)
t3 = time_sync()
dt[1] += t3 - t2
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
dt[2] += time_sync() - t3
detections=[]
for i, det in enumerate(pred):
seen += 1
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]
if len(det):
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
for *xyxy, conf, index in reversed(det):
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4))/ gn).view(-1).tolist()
cls = names[int(index)]
conf = float(conf)
detections.append({'class': cls, 'conf': conf, 'position': xywh, 'index': int(index)})
return detections
def pick_auto_label_img(in_path, out_path, conf_threshold = 0.5):
out_label_dir_path = os.path.join(out_path,"labels")
out_img_dir_path = os.path.join(out_path,"images")
if os.path.exists(out_path):
shutil.rmtree(out_path)
os.makedirs(out_label_dir_path)
os.makedirs(out_img_dir_path)
in_path_list=os.listdir(in_path)
in_path_list.sort()
for file in tqdm(in_path_list):
img_full_path = os.path.join(in_path,file)
sptext = os.path.splitext(file)
label_file_name = sptext[0] + '.txt'
label_path = os.path.join(out_label_dir_path, label_file_name)
img = cv2.imread(img_full_path)
detections = detect(img)
pick = False
if len(detections)>0:
for i in detections:
if i["conf"] < conf_threshold:
pick = True
break
if pick:
out_img_path = os.path.join(out_img_dir_path, file)
shutil.copy(file_full_path, out_img_path)
for d in detections:
line = (d["index"],*d["position"])
with open(label_path, 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
auto_label_low_conf = "/workspace/data/small_flame_fog_smoke/auto_label_low_conf"
pick_auto_label_img(
in_path=Path("/workspace/data/small_flame_fog_smoke/test1"),
out_path=Path(auto_label_low_conf)
)
print("done")