详细说明如何被其他函数如何调用深度学习中训练生成的detect.py
时间: 2023-06-27 17:01:02 浏览: 73
如果你已经训练好了一个目标检测模型,可以使用 `detect.py` 脚本来进行对象检测。可以将该脚本作为一个函数来调用,以便在其他代码中使用。
以下是一个示例代码,展示如何在 Python 中调用 `detect.py` 脚本:
```python
import argparse
import torch
from models import *
from utils.datasets import *
from utils.utils import *
def detect():
parser = argparse.ArgumentParser()
parser.add_argument('--cfg', type=str, default='cfg/yolov3.cfg', help='*.cfg path')
parser.add_argument('--names', type=str, default='data/coco.names', help='*.names path')
parser.add_argument('--weights', type=str, default='weights/yolov3.weights', help='weights path')
parser.add_argument('--source', type=str, default='data/samples', help='source') # input file/folder, 0 for webcam
parser.add_argument('--output', type=str, default='output', help='output folder') # output folder
parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.3, help='object confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='display results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
opt = parser.parse_args()
with torch.no_grad():
if opt.classes:
opt.filter_classes = True
device = torch_utils.select_device(opt.device)
print(f'Using {device}')
# Initialize model
model = Darknet(opt.cfg, img_size=opt.img_size)
attempt_download(opt.weights)
if opt.weights.endswith('.pt'): # pytorch format
model.load_state_dict(torch.load(opt.weights, map_location=device)['model'])
else: # darknet format
load_darknet_weights(model, opt.weights)
model.to(device).eval()
# Get dataloader
dataset = LoadImages(opt.source, img_size=opt.img_size)
# Run inference
t0 = time.time()
for path, img, im0s, vid_cap in dataset:
img = torch.from_numpy(img).to(device)
img = img.float() / 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# Inference
pred = model(img)[0]
# Apply NMS
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
# Process detections
for i, det in enumerate(pred): # detections for image i
p, s, im0 = path[i], f'{i}: ', im0s[i].copy()
save_path = str(Path(opt.output) / Path(p).name)
txt_path = str(Path(opt.output) / Path(p).stem) + ('' if opt.save_txt else '.nobak') + '.txt'
s += '%gx%g ' % img.shape[2:] # print string
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if det is not None and 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, ' # add to string
# Write results
for *xyxy, conf, cls in det:
if opt.save_txt: # Write to file
xyxy = torch.tensor(xyxy).view(1, 4) # convert to tensor
xyxy = xyxy / gn[:2] + torch.tensor([0, 0, 1, 1]).float().cuda() # normalized to img0 0-1
line = (cls, *xyxy[0], conf) if opt.save_txt else (cls, conf)
with open(txt_path, 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
if opt.view_img: # Add bbox to image
c = int(cls) # integer class
label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
# Print time (inference + NMS)
print(f'{s}Done. ({time.time() - t0:.3f}s)')
# Save results (image with detections)
if opt.save_img:
cv2.imwrite(save_path, im0)
print(f'Done. ({time.time() - t0:.3f}s)')
```
上述代码中 `detect()` 函数中包含了 `detect.py` 的全部代码。在这个函数中,我们使用 `argparse` 模块来处理命令行参数,并在模型加载后对传入的图片进行目标检测。最后,我们可以选择将结果保存到文件或显示在屏幕上。
你可以在你自己的代码中调用此函数,以便在其他应用程序中使用目标检测模型。