import argparse
import time
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
def detect(save_img=False):
agnostic_nms, augment, classes, exist_ok, no_trace, nosave, save_conf, save_txt = False, False, None, False, False, False, False, False
conf_thres, iou_thres, imgsz = 0.45, 0.45, 640
device, update, view_img = '', False, False
trace = no_trace
save_img = not nosave and not source.endswith('.txt') # save inference images
# Directories
save_dir = Path(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
# Initialize
set_logging()
device = select_device(device)
half = device.type != 'cpu' # half precision only supported on CUDA
# Load model
model = attempt_load(weights, map_location=device) # load FP32 model
stride = int(model.stride.max()) # model stride
imgsz = check_img_size(imgsz, s=stride) # check img_size
# Set Dataloader
dataset = LoadImages(source, img_size=imgsz, stride=stride)
# Get names and colors
names = model.module.names if hasattr(model, 'module') else model.names
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
# print("object predict classname and color:",names,colors)
# while True:
t0 = time.time()
for path, img, im0s, vid_cap in dataset:
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# Inference
t1 = time_synchronized()
with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
pred = model(img, augment=augment)[0]
t2 = time_synchronized()
# Apply NMS
pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=agnostic_nms)
t3 = time_synchronized()
# Process detections
with open(r"D:\LABELAOI\Test\Yovo7_predictions.txt", "a")as ffff:
class_label = ""
for i, det in enumerate(pred): # detections per image
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # img.jpg
txt_path = str(save_dir / 'labels' / p.stem) + (
'' if dataset.mode == 'image' else f'_{frame}') # img.txt
print("save path is:", save_path, "txtpath is:", txt_path, "p is:", p)
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.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
with open(r"D:\LABELAOI\Test\label_position.txt", "a")as wLab:
for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(
-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
if save_img or view_img: # Add bbox to image
label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
# print(
# f'--------------plot_one_box({xyxy}, {im0}, label={label}, color={colors[int(cls)]}, line_thickness=1)')
x1 = int(xyxy[0].item())
y1 = int(xyxy[1].item())
x2 = int(xyxy[2].item())
y2 = int(xyxy[3].item())
wLab.write(
p.name + "," + label + "," + str(x1) + "," + str(x2) + "," + str(y1) + "," + str(
y2) + "\n")
class_label = label
# Print time (inference + NMS)
results = str(label.split(" ")).replace("[", "").replace("]", "").replace("'", "").replace(
" ", "")
ffff.write(f"{results}" + "\n")
print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
# Save results (image with detections)
if save_img:
if dataset.mode == 'image':
if class_label:
cv2.imwrite(save_path, im0)
# print(f" The image with the result is saved in: {save_path}")
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
print(f'Done. ({time.time() - t0:.3f}s)')
if __name__ == '__main__':
name = 'D:\\LABELAOI\\Test\\Yolov7_Test\\predictionsv7'
project = 'D:\\LABELAOI\\Test\\Yolov7_predictions'
source = 'D:\\LABELAOI\\Test'
weights = ['e:\\best.pt']
with torch.no_grad():
detect()