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)
统计每一个子文件夹的图片数量并写入xlsx
最新推荐文章于 2025-03-09 16:54:04 发布