Search code examples
pythonamazon-web-servicesboto3amazon-rekognition

AWS Boto3(Python): how to save multiple response from multiple image input to individual file?


The below code is for AWS Rekognition image label detection.

Question 1) Since AWS Recognition can only run one image at a time, I used [List] to add multiple images at a time. However, what if I want to run 100 images? this means I have to manually write name for 100 images in that [List] which will take forever. What is the best way to solve this issue supposing I have 100 images named image1, image2, image3, ... image100?

Question 2) The below code will save the response for all 3 images to a single JSON file. How can the response be saved into an individual file?

# 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)    

Solution

  • The code posted does not do what you think it does. Specifically, it does not save results from the three images. Only the last response is saved.

    This is because you are creating aresponselist which is simply not used at all. Also don't call your list a list as it is a python's actual list data structure.

    However, if you want to write results for each image separately you can try the following :

    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)