AWS Rekognition 中的边界框

Bounding box in AWS Rekognition

我正在尝试从 Rekognition 中的图像获取边界框,我得到了标签,但我得到:

Keyerror'instances' in response['instances']

def detect_labels(bucket, key, max_labels=10, min_confidence=90, region="eu-west-1"):
    rekognition = session.client("rekognition", region)
    response = rekognition.detect_labels(
        Image={
            "S3Object": {
                "Bucket": bucket,
                "Name": key,
            }
        }, MaxLabels=10
    )
    return response

if __name__ == "__main__":

response= detect_labels(BUCKET, KEY)

    print('Detected labels for ' + photo) 
    print()   
    for label in response['Labels']:

        for instance in label['Instances']:
            print ("  Bounding box")
            print ("    Top: " + str(instance['BoundingBox']['Top']))

        print ("----------")
        print ()

请确保您使用的是最新的 boto3 SDK。我发现 boto3 v1.9.20 没有 return 实例数组,而当前的 v1.9.84 return 它。

除此之外,documentation 指出:

If Label represents an object, Instances contains the bounding boxes for each instance ...

这似乎意味着只有当标签代表一个对象时才会出现实例。您的代码应检查给定标签是否确实具有实例,例如:

if 'Instances' in label:
    for instance in label['Instances']:
        # print details of instance

确认这一点也很简单,只需将 label 字典打印为 JSON 字符串并查看它实际包含的内容。