yolov7 detect
时间: 2025-04-23 15:06:24 浏览: 29
### 使用 YOLOv7 实现物体检测
为了使用 YOLOv7 进行目标检测,需遵循一系列配置和操作流程。首先,确保 Python 环境已经正确设置并安装必要的依赖项[^3]。
#### 准备工作
- **克隆官方仓库**:从 GitHub 上获取 YOLOv7 的官方实现代码库[^2]。
```bash
git clone https://github.com/WongKinYiu/yolov7.git
cd yolov7
```
- **创建虚拟环境并激活**
推荐使用 `venv` 或者 `conda` 创建独立的Python开发环境来管理项目的依赖关系:
```bash
python -m venv myenv
source myenv/bin/activate # Linux/MacOS
.\myenv\Scripts\activate # Windows
```
- **安装依赖包**
执行命令以安装所需的 Python 库:
```bash
pip install -r requirements.txt
```
#### 数据准备
对于训练或测试模型而言,准备好合适的数据集至关重要。如果打算利用预训练模型进行推理,则可以直接跳过此部分;但如果计划重新训练模型或是微调现有模型,则需要按照特定格式整理自己的数据集,并更新相应的配置文件。
#### 加载预训练模型
YOLOv7 提供了几种不同大小的预训练模型可供选择。可以通过下载对应的权重文件快速启动项目。例如,要加载标准版 YOLOv7 模型可以执行如下指令:
```python
from models.experimental import attempt_load
import torch
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = attempt_load('yolov7.pt', map_location=device) # 自动下载预训练权重
```
#### 图像推理过程展示
下面给出一段简单的代码片段用于演示如何对单张图片实施对象识别任务:
```python
import cv2
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device, time_synchronized
from pathlib import Path
def detect(image_path='data/images/bus.jpg'):
img0 = cv2.imread(str(Path(image_path))) # BGR
# Padded resize
img_size = 640
stride = int(model.stride.max()) # model stride
img = letterbox(img0, img_size, stride=stride)[0]
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
device = select_device('')
half = device.type != 'cpu'
# Load model
with torch.no_grad():
weights, imgsz = opt.weights, opt.img_size
set_logging()
device = select_device(opt.device)
half &= device.type != 'cpu' # half precision only supported on CUDA
model.half() if half else None
# Run inference
t0 = time.time()
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)
pred = model(img, augment=opt.augment)[0]
# Apply NMS
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
# Process detections
det = pred[0]
gn = torch.tensor(img0.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], img0.shape).round()
for *xyxy, conf, cls in reversed(det):
label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, img0, label=label, color=colors(int(cls), True))
return img0
```
上述脚本实现了读取输入图像、调整尺寸、转换颜色通道顺序等一系列预处理步骤之后,再送入网络得到预测结果,并通过非极大值抑制算法筛选出最终的目标框位置以及类别信息。
#### 结果可视化
最后一步是对检测到的对象绘制边界框并将分类标签附加在其旁边以便直观查看效果。这部分已经在上面的例子中有所体现(`plot_one_box`)函数负责完成这项工作。
---
阅读全文
相关推荐


















