简体   繁体   中英

For loop to iterate through a folder of images and output into a single JSON file

I am not a developer and I have a very limited knowledge of programming. I understand how to use and operate python scripts, however writing them is something I am yet to learn. Please can someone help a total noob :)

I am using an API by sightengine to asses a large folder of .jpg images for their sharpness and colour properties. The documentation for the API only provides a small script for assessing one image at a time. I have spoken to Sight Engines support and they are unwilling to provide a script for batch processing which is bizarre considering all other API companies usually do.

I need some help creating a for loop that will use a python script to iterate through a folder of images and output the API result into a single JSON file. Any help in how to structure this script would be extremely appreciated.

Here is the sightengine code for a simple one image check:

from sightengine.client import SightengineClient

client = SightengineClient("{api_user}", "{api_secret}")
output = client.check('properties','type').set_file('/path/to/local/file.jpg')

Thank you

Part of this is sort of a guess, as I don't know exactly what output will look like. I am assuming it's returned as json format. Which if thats the case, you can append the individual json responses into a single json structure, then use json.dump() to write to file.

So that part is a guess. The other aspect is you want to iterate through your jpg files, which you can do by using os and fnmatch . Just adjust the root directory/folder for it to walk through while it searches fro all the .jpg extensions.

from sightengine.client import SightengineClient
import os
from fnmatch import fnmatch
import json

client = SightengineClient("{api_user}", "{api_secret}")

# Get your jpg files into a list
r = 'C:/path/to/local'
pattern = "*.jpg"
filenames = []

for path, subdirs, files in os.walk(r):
    for name in files:
        if fnmatch(name, pattern):
            #print (path+'/'+name)
            filenames.append(path+'/'+name)


# Now iterate through those jpg files
jsonData = []            
for file in filenames:
    output = client.check('properties','type').set_file(file)
    jsonData.append(output)

with open('C:/result.json', 'w') as fp:
    json.dump(jsonData, fp, indent=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM