inference.py在models文件夹中,utils.py在dataset文件夹中,两个文件夹同在SAM文件夹中,inference.py想引用utils.py的generate_test_loader和generate_dataset两个函数,该怎么引用
时间: 2024-04-11 12:28:37 浏览: 27
对于inference.py想要引用utils.py中的函数,可以使用相对导入。假设你的文件结构如下所示:
```
SAM/
├── models/
│ └── inference.py
└── dataset/
└── utils.py
```
在inference.py中,你可以使用以下方式引用utils.py中的函数:
```python
from ..dataset.utils import generate_test_loader, generate_dataset
```
这样就可以成功导入utils.py中的函数了。需要注意的是,使用相对导入时,需要确保两个文件夹处于同一级别下,否则需要相应地调整导入路径。
相关问题
yolov5 detect.py中打开摄像头的代码在哪
在YoloV5的`detect.py`中,打开摄像头的代码可以在`detect()`函数中找到,具体代码如下:
```python
def detect():
...
# 如果使用摄像头,打开摄像头并获取视频流
if opt.source == '0' or opt.source.startswith('rtsp') or opt.source.startswith('http'):
# 打开摄像头或者视频流
view_img = True
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(opt.source, img_size=imgsz)
else:
# 读取本地视频文件
save_img = True
dataset = LoadImages(opt.source, img_size=imgsz)
# 读取模型
model = attempt_load(weights, map_location=device) # load FP32 model
imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size
if half:
model.half() # to FP16
# 获取类别名称
names = model.module.names if hasattr(model, 'module') else model.names
# 进行推理
results = []
for path, img, im0s, vid_cap in dataset:
# img : 当前帧的缩放后的图片
# im0s : 当前帧的原图
# 进行检测
t1 = torch_utils.time_synchronized()
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float()
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# 获取预测结果
pred = model(img, augment=opt.augment)[0]
# 进行后处理
pred = non_max_suppression(pred, conf_thres=conf_thres, iou_thres=iou_thres, classes=opt.classes,
agnostic=agnostic_nms, max_det=max_det)
t2 = torch_utils.time_synchronized()
# 输出当前帧信息
for i, det in enumerate(pred): # detections per image
if webcam: # batch_size >= 1
p, s, im0 = path[i], '%g: ' % i, im0s[i]
else:
p, s, im0 = path, '', im0s
save_path = str(Path(out) / Path(p).name)
txt_path = str(Path(out) / Path(p).stem) + (f'_{frame_i:06d}' if save_img else '')
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' * (n > 1)}, " # add to string
# Write results
for *xyxy, conf, cls in det:
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
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=3)
# Print time (inference + NMS)
print(f'{s}Done. ({t2 - t1:.3f}s)')
# Stream results
if view_img:
cv2.imshow(str(p), im0)
if cv2.waitKey(1) == ord('q'): # q to quit
raise StopIteration
# Save results (image with detections)
if save_img:
if dataset.mode == 'images':
cv2.imwrite(save_path, im0)
print(f'Done. ({time.time() - t0:.3f}s)')
```
在上面的代码中,如果`opt.source`为`0`或者以`rtsp`或`http`开头,则表示打开摄像头或视频流,代码中会调用`LoadStreams`函数加载视频流。在`for path, img, im0s, vid_cap in dataset:`这一行代码中,`img`表示当前帧的缩放后的图片,`im0s`表示当前帧的原图。在代码中,会对当前帧的图片进行目标检测,并对检测结果进行后处理,最后将结果输出到屏幕上或保存到本地。如果需要显示视频流,则调用`cv2.imshow`函数将当前帧的原图显示到屏幕上。
详细说明如何被其他函数如何调用深度学习中训练生成的detect.py
如果你已经训练好了一个目标检测模型,可以使用 `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` 模块来处理命令行参数,并在模型加载后对传入的图片进行目标检测。最后,我们可以选择将结果保存到文件或显示在屏幕上。
你可以在你自己的代码中调用此函数,以便在其他应用程序中使用目标检测模型。