nailong-dataset / generate_info.py
XiC1's picture
Upload folder using huggingface_hub
d67c45e verified
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,
# 'info': img.info
}
# 将信息输出为 JSON 格式
json_output = json.dumps(
image_info, ensure_ascii=False, indent=4)
# 打印 JSON 输出
# print(json_output)
# 将 JSON 输出写入文件
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 格式')
# 添加可选参数 --label
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)