yolov5detect的检测结果进行目标提取的代码
时间: 2024-05-15 21:15:00 浏览: 107
人工智能-项目实践-检测-基于yolov5的人脸检测,带关键点检测.zip
把检测结果进行目标提取的代码可以参考以下代码:
```python
import cv2
import numpy as np
from PIL import Image
# 加载模型
model = cv2.dnn.readNetFromDarknet('yolov5.cfg', 'yolov5.weights')
# 获取输出层信息
ln = model.getLayerNames()
ln = [ln[i[0] - 1] for i in model.getUnconnectedOutLayers()]
# 检测函数
def detect(image):
# 获取图像尺寸
(H, W) = image.shape[:2]
# 构建一个blob
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
# 设置模型输入
model.setInput(blob)
# 运行前向传递
layerOutputs = model.forward(ln)
# 初始化检测结果列表
boxes = []
confidences = []
classIDs = []
# 处理每个输出层
for output in layerOutputs:
# 处理每个检测
for detection in output:
# 提取类别ID和置信度
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
# 过滤掉置信度低的检测
if confidence > 0.5:
# 获取检测框坐标
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
# 计算检测框的左上角坐标
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# 更新检测结果列表
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
# 进行非极大值抑制
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.3)
# 提取目标
targets = []
if len(idxs) > 0:
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
targets.append(image[y:y+h, x:x+w])
return targets
# 测试
image = cv2.imread('test.jpg')
targets = detect(image)
for i, target in enumerate(targets):
cv2.imwrite(f'target{i}.jpg', target)
```
阅读全文