AWS Boto3(Python):如何将来自多个图像输入的多个响应保存到单个文件?

时间:2020-08-30 01:52:45

标签: python amazon-web-services boto3 amazon-rekognition

以下代码用于AWS Rekognition图像标签检测。

问题1)由于AWS Recognition一次只能运行一个图像,因此我使用[List]一次添加了多个图像。但是,如果我要运行100张图像怎么办?这意味着我必须在[列表]中手动为100张图像写入名称,这将永远生效。假设我有100张名为image1,image2,image3,... image100的图像,什么是解决此问题的最佳方法?

问题2)以下代码会将所有3张图片的响应保存到单个JSON文件中。如何将响应保存到单个文件中?

# List to record all the responses    
responselist=[]
list=['picture1.jpg','picture2.jpg','picture 3.jpg'] 
for image in list :
    response = client.detect_labels(
    Image={
    'S3Object': {
    'Bucket': 'test1',
    'Name': image
        }})
    responselist.append(response)

print(response)

# JASON file Save
json_file = json.dumps(response)
Path('rekognition_test.json').write_text(json_file)    

1 个答案:

答案 0 :(得分:0)

发布的代码与您认为的不一样。 具体来说,它不保存来自 这三个图像。只有最后一个response是 保存。

这是因为您正在创建一个responselist 根本不使用它。也不要打电话给你 列出list,因为它是python的实际list数据结构。

但是,如果要分别为每个图像写入结果 您可以尝试以下方法:

my_list=['picture1.jpg','picture2.jpg','picture 3.jpg'] 

for image in my_list:

    response = client.detect_labels(
                  Image={
                  'S3Object': {
                  'Bucket': 'test1',
                  'Name': image
                }})

    json_file = json.dumps(response)
    Path(f"{image}.json").write_text(json_file)