有没有办法只在 VisionLabelDetector 中获得最高置信度的结果?

Is there a way to take highest confidence result only in VisionLabelDetector?

为了归档这个,我考虑只取 1 个结果,这是最上面的一个,所以我检查了文档和 VisionCloudDetectorOptions have this variable maxResults so if I set it to 1, my goal is complete but this only work with Cloud-based image labeling. So I check VisionLabelDetectorOptions,其中 运行 在本地,没有选择。打印出来的结果

return "Label: \(String(describing: feature.label)), " +
      "Confidence: \(feature.confidence), " +
      "EntityID: \(String(describing: feature.entityID)), " +
      "Frame: \(feature.frame)"
    }.joined(separator: "\n")

会变成这样

Label: Food, Confidence: 0.795696, EntityID: /m/02wbm, Frame: (0.0, 0.0, 0.0, 0.0)
Label: Fruit, Confidence: 0.71232, EntityID: /m/02xwb, Frame: (0.0, 0.0, 0.0, 0.0)
Label: Vegetable, Confidence: 0.595484, EntityID: /m/0f4s2w, Frame: (0.0, 0.0, 0.0, 0.0)
Label: Plant, Confidence: 0.536178, EntityID: /m/05s2s, Frame: (0.0, 0.0, 0.0, 0.0)

这些是示例代码 I 运行 来自 Firebase/quickstart-ios 从第 645 行开始。

我的第二个解决方案是像在 CoreML 中那样执行 topResult,它使用 VNClassificationObservation 到 return 第一个结果。像这样

guard let results = request.results as? [VNClassificationObservation],
            let topResult = results.first else {
                fatalError("Unexpected result")
        }

但我还没有想出如何像那样复制。

那么,有没有办法只取最高的Confidence标签呢?在这种情况下是 Food 标签。

假设labels是包含VisionLabelDetector.detect(in:completion:)返回的所有VisionLabel对象的数组,通常数组中的所有标签都已经根据它们的confidence从高到低排序,所以你可以简单地用 labels.first.

获得最高的 confidence 标签

如果您想更加安全并自己选择最高置信度标签,您可以执行以下操作:

let topLabel = labels.max(by: { (a, b) -> Bool in return a.confidence < b.confidence })