为ssd_mobilenet_v2目标检测模型添加告警功能时报ValueError如何解决
问题解决方法
报错原因
- 你调用模型时输入的是带batch维度的张量(
np.expand_dims给原始图像加了一维batch维度),所以输出的detections['detection_classes']、detections['detection_scores']都是形状为(1, 检测框总数)的二维数组/张量,直接遍历detections['detection_classes']拿到的是包含所有检测类别的一维数组,将数组直接做布尔判断就会触发ValueError: The truth value of an array with more than one element is ambiguous的报错。 - 原始代码未加入置信度≥0.14的判断逻辑,不符合需求。
修复代码
方案1:遍历实现(逻辑直观,可按需扩展每个检测框的后续处理)
# 将张量转为numpy数组,并去掉多余的batch维度 detect_classes = detections['detection_classes'].numpy().squeeze() detect_scores = detections['detection_scores'].numpy().squeeze() for cls, score in zip(detect_classes, detect_scores): # 同时满足类别为ClassB、置信度≥0.14时触发告警 if cls == 1 and score >= 0.14: print("Attention needed") # 若只需首次触发告警就停止校验,可取消下方break注释 # break
方案2:向量化判断(效率更高,适合仅判断是否需要告警的场景)
detect_classes = detections['detection_classes'].numpy().squeeze() detect_scores = detections['detection_scores'].numpy().squeeze() # 直接判断是否存在符合条件的检测结果 if ((detect_classes == 1) & (detect_scores >= 0.14)).any(): print("Attention needed")
内容的提问来源于stack exchange,提问作者Mehtab Singh
相关产品推荐
相关产品推荐

