yolov5 识别拍照
时间: 2023-10-23 22:15:26 浏览: 69
您可以使用 YOLOv5 模型来进行图像识别,包括拍照中的物体识别。您需要先安装 YOLOv5 并下载预训练模型,然后使用 Python 代码进行图像识别。以下是一个简单的示例代码:
```python
import torch
import cv2
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
# 加载模型
weights = 'yolov5s.pt'
device = select_device('')
model = attempt_load(weights, map_location=device)
# 读取图像
img = cv2.imread('test.jpg')
# 图像预处理
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = torch.from_numpy(img).to(device)
img = img.float() / 255.0
img = img.unsqueeze(0)
# 模型推理
pred = model(img)[0]
pred = non_max_suppression(pred, conf_thres=0.5, iou_thres=0.5)
# 处理输出结果
for det in pred:
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img.shape[2:]).round()
for *xyxy, conf, cls in reversed(det):
label = f'{model.names[int(cls)]} {conf:.2f}'
xyxy = [int(x) for x in xyxy]
cv2.rectangle(img, tuple(xyxy[:2]), tuple(xyxy[2:]), (255, 0, 0), 2)
cv2.putText(img, label, (xyxy[0], xyxy[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 显示结果
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文