You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AWS Rekognition自定义标签时仅返回单个标签的问题排查

问题原因

你的代码核心问题出在HashMap的使用方式:HashMap的key具有唯一性,每次循环都会覆盖"Label"和"Confidence"这两个key对应的value,最终返回的map里只会保留最后一个标签的数据,而非所有标签。

解决方案

要获取完整的标签列表,需要调整数据存储结构,用列表来保存每个标签的独立信息。以下是两种可行的实现方式:

方式1:使用List<Map<String, String>>存储标签

byte[] imageBytes = file.getBytes();

Image ri = Image.builder().bytes(SdkBytes.fromByteArray(imageBytes)).build();

DetectCustomLabelsRequest detectCustomLabelsRequest = DetectCustomLabelsRequest.builder()
        .projectVersionArn("project arn")
        .image(ri).build();

DetectCustomLabelsResponse response = rekognitionClient.detectCustomLabels(detectCustomLabelsRequest);

// 用列表存储每个标签的键值对
List<Map<String, String>> allLabels = new ArrayList<>();
for (CustomLabel customLabel : response.customLabels()) {
    Map<String, String> singleLabel = new HashMap<>();
    singleLabel.put("Label", customLabel.name());
    singleLabel.put("Confidence", String.valueOf(customLabel.confidence()));
    allLabels.add(singleLabel);
    System.out.println("label -> " + customLabel.name());
}

return allLabels;

方式2:自定义POJO类封装标签信息(可读性更佳)

先定义一个简单的实体类:

class LabelInfo {
    private String labelName;
    private float confidence;

    public LabelInfo(String labelName, float confidence) {
        this.labelName = labelName;
        this.confidence = confidence;
    }

    // 按需添加getter/setter方法
    public String getLabelName() { return labelName; }
    public float getConfidence() { return confidence; }
}

然后用列表存储实体类对象:

// 前面请求代码不变
DetectCustomLabelsResponse response = rekognitionClient.detectCustomLabels(detectCustomLabelsRequest);

List<LabelInfo> allLabels = new ArrayList<>();
for (CustomLabel customLabel : response.customLabels()) {
    allLabels.add(new LabelInfo(customLabel.name(), customLabel.confidence()));
    System.out.println("label -> " + customLabel.name());
}

return allLabels;

内容的提问来源于stack exchange,提问作者Mahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:32:38