统计每一个子文件夹的图片数量并写入xlsx

import os
from PIL import Image
from openpyxl import Workbook

def is_image(file_path):
    """Check if a file is an image."""
    try:
        img = Image.open(file_path)
        img.verify()
        return True
    except (IOError, SyntaxError):
        return False

def count_images_in_folder(folder_path):
    """Count the number of image files in a folder."""
    count = 0
    for root, _, files in os.walk(folder_path):
        for file in files:
            if is_image(os.path.join(root, file)):
                count += 1
    return count

def main(root_folder, output_file):
    """Main function to count images and write results to an Excel file."""
    wb = Workbook()
    ws = wb.active
    ws.title = "Image Counts"
    ws.append(["Folder Name", "Image Count"])

    for subdir in next(os.walk(root_folder))[1]:
        folder_path = os.path.join(root_folder, subdir)
        image_count = count_images_in_folder(folder_path)
        ws.append([subdir, image_count])

    wb.save(output_file)
    print(f"Image counts saved to {output_file}")

if __name__ == "__main__":
    root_folder = "train_set/train_set"  # 修改为你的根文件夹路径
    output_file = "image_counts.xlsx"
    main(root_folder, output_file)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值