怎么利用YOLOv11推理输出进行计数
时间: 2025-05-22 08:54:21 浏览: 27
### 使用 YOLOv11 的推理输出实现目标计数的方法
YOLOv11 是一种高效的目标检测算法,其推理阶段会返回一系列边界框及其对应的类别和置信度分数。为了从这些推理结果中提取目标的数量信息,可以按照以下方法操作:
#### 1. 解析推理输出
YOLOv11 的推理输出通常是一个张量列表,其中每个元素表示一个预测的边界框。该边界框包含位置坐标 (x, y, w, h),类别索引以及置信度得分。解析此输出的第一步是从模型的结果中获取所有满足阈值条件的有效预测。
对于每一张输入图片,假设推理输出为 `output`,则可以通过筛选高置信度的预测来获得有效目标集合[^4]:
```python
import torch
def filter_predictions(output, confidence_threshold=0.5):
"""
过滤掉低于置信度阈值的预测。
参数:
output: 模型推理输出 Tensor (batch_size, num_boxes, [x,y,w,h,class,score])
confidence_threshold: 置信度阈值
返回:
filtered_output: 高置信度预测的子集
"""
high_confidence_preds = output[output[..., -1] >= confidence_threshold]
return high_confidence_preds
```
#### 2. 对类别进行分组统计
一旦获得了有效的预测结果,就可以按类别对其进行分类并计算数量。这一步骤涉及遍历过滤后的预测结果,并记录每一类别的实例数目。
以下是具体实现方式:
```python
from collections import Counter
def count_objects(filtered_output, class_names):
"""
统计各个类别的对象数量。
参数:
filtered_output: 高置信度预测 Tensor (num_boxes, [x,y,w,h,class,score])
class_names: 类别名称列表
返回:
object_counts: 各类别对应的对象数量字典
"""
classes = filtered_output[:, -2].long().tolist() # 获取类别索引列
counts = dict(Counter(classes))
object_counts = {class_names[k]: v for k, v in counts.items()}
return object_counts
```
#### 3. 结果展示与验证
最后,在完成上述两步之后,可将最终的计数结果显示给用户或者保存至文件中以便后续分析。如果使用 PySide6 构建 GUI,则可以直接在界面上更新计数值;如果是命令行工具,则打印即可。
例如,调用以上函数可能得到如下结果:
```python
object_counts = {'red_blood_cell': 120, 'white_blood_cell': 8}
print(object_counts)
```
此外,还可以绘制带有标签的图像以直观呈现检测效果:
```python
import cv2
def draw_and_label(image, predictions, class_names):
"""
在原图上绘制边框并标注类别及数量。
参数:
image: 原始图像 numpy array
predictions: 预测结果 Tensor (num_boxes, [x,y,w,h,class,score])
class_names: 类别名称列表
返回:
annotated_image: 添加了标记的新图像
"""
img_copy = image.copy()
for pred in predictions:
x, y, w, h, cls_idx, score = pred.tolist()
label = f"{class_names[int(cls_idx)]}: {score:.2f}"
color = tuple(map(int, np.random.randint(0, 255, size=(3,))))
start_point = (int(x-w/2), int(y-h/2))
end_point = (int(x+w/2), int(y+h/2))
cv2.rectangle(img_copy, start_point, end_point, color, thickness=2)
cv2.putText(img_copy, label, start_point, cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
return img_copy
```
---
###
阅读全文
相关推荐


















