首页 > 解决方案 > 我如何查看文件夹中有多少个 png 文件及其分辨率以打印到 excel 中?

问题描述

我的文件夹结构如下

  1. 数据集文件夹
    • 子文件夹 1
      • a.png b.png c.png...
    • 子文件夹 2
      • a.png b.png c.png...
    • 子文件夹 3
      • a.png b.png c.png...
    • 子文件夹4
      • a.png b.png c.png...
    • 子文件夹 n
      • a.png b.png c.png...

标签: python

解决方案


您可以使用 递归查找文件glob.glob(),但我使用os.walk()str.endswith(".png")收集所有子目录中的所有 png 文件。

出色的Pillow模块用于获取图像的分辨率。

import os
from collections import defaultdict
from PIL import Image

DIR = r"C:\Dataset Folder"

results = defaultdict(list)
for root, _, filenames in os.walk(DIR):
    subdirectory = root.replace(f"{DIR}\\", "")
    for filename in filenames:
        if filename.endswith(".png"):
            filepath = os.path.join(root, filename)
            width, height = Image.open(filepath).size
            results[subdirectory].append((filename, width, height))

# Print output
for subdirectory, images in results.items():
    print(f"{subdirectory} has {len(images)} image(s):")
    for filename, width, height in images:
        print(f"{filename} resolution is {width}x{height}")
    print()

# Manually write the CSV file
with open("png files.csv", "wt") as f:
    f.write("Subdirectory,Filename,Width,Height\n") # Header
    for subdirectory, images in results.items():
        for filename, width, height in images:
            f.write(f"{subdirectory},{filename},{width},{height}\n") # Rows

stdout输出:

Subfolder1 has 4 image(s):
a.png resolution is 640x480
b.png resolution is 640x480
c.png resolution is 300x300
d.png resolution is 300x300

Subfolder2 has 4 image(s):
a.png resolution is 300x300
b.png resolution is 300x300
c.png resolution is 300x300
d.png resolution is 300x300

Subfolder3 has 4 image(s):
a.png resolution is 300x300
b.png resolution is 300x300
c.png resolution is 26x26
d.png resolution is 300x30

Subfolder4 has 1 image(s):
a.png resolution is 256x240

CSV 文件:

Subdirectory,Filename,Width,Height
Subfolder1,a.png,640,480
Subfolder1,b.png,640,480
Subfolder1,c.png,300,300
Subfolder1,d.png,300,300
Subfolder2,a.png,300,300
Subfolder2,b.png,300,300
Subfolder2,c.png,300,300
Subfolder2,d.png,300,300
Subfolder3,a.png,300,300
Subfolder3,b.png,300,300
Subfolder3,c.png,26,26
Subfolder3,d.png,300,30
Subfolder4,a.png,256,240

用 Microsoft Excel 打开的 CSV 文件:

在此处输入图像描述


推荐阅读