|
import argparse |
|
from PIL import Image |
|
import json |
|
import os |
|
|
|
|
|
def process_images(image_filenames, label): |
|
for image_filename in image_filenames: |
|
prefix = os.path.splitext(image_filename)[0] |
|
json_filename = f"{os.path.splitext(image_filename)[0]}.json" |
|
|
|
|
|
if os.path.isfile(image_filename): |
|
|
|
try: |
|
with Image.open(image_filename) as img: |
|
|
|
image_info = { |
|
'filename': os.path.basename(image_filename), |
|
'label': label, |
|
'format': img.format, |
|
'mode': img.mode, |
|
'size': img.size, |
|
|
|
} |
|
|
|
|
|
json_output = json.dumps( |
|
image_info, ensure_ascii=False, indent=4) |
|
|
|
|
|
|
|
|
|
|
|
with open(json_filename, 'w', encoding='utf-8') as json_file: |
|
print(f"write to {json_filename}") |
|
json_file.write(json_output) |
|
except (IOError, SyntaxError) as e: |
|
print(e) |
|
else: |
|
print(f"文件 {image_filename} 不存在。") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
parser = argparse.ArgumentParser(description='读取图片文件并输出为 JSON 格式') |
|
|
|
|
|
parser.add_argument('--label', type=int, default=None, help='图片的标签') |
|
|
|
|
|
parser.add_argument('image_filenames', nargs='+', help='要处理的图片文件名') |
|
|
|
|
|
args = parser.parse_args() |
|
|
|
|
|
process_images(args.image_filenames, args.label) |
|
|