该代码主要功能是检查指定目录下所有PNG和JPG图像文件的通道数,并打印每个图像的通道数。具体函数功能如下:
- check_image_channels(file_path)函数用于检查单个图像文件的通道数。它使用PIL库的Image模块打开图像文件,通过getbands()方法获取图像的通道数。如果处理文件时发生错误,将打印错误信息并返回None。
- check_channel(directory)函数用于遍历指定目录下的所有PNG和JPG图像文件,并打印每个图像的通道数。它首先检查指定的目录是否存在,如果不存在或不可访问,则打印错误信息并返回。然后使用os.walk()函数遍历目录下的所有文件,对于每个文件,使用check_image_channels()函数检查并打印其通道数。
- 在__main__部分,指定了要检查的目录路径,然后调用check_channel()函数进行图像通道数的检查和打印
import os
from PIL import Image
def check_image_channels(file_path):
"""检查图像文件的通道数。"""
try:
with Image.open(file_path) as img:
# 直接使用getbands()方法获取通道数,避免不必要的图像分割
channels = len(img.getbands())
return channels
except Exception as e:
print(f"处理文件时发生错误: {file_path}, 错误信息: {str(e)}")
return None
def check_channel(directory):
"""遍历给定目录下的所有PNG和JPG图像文件,打印每个图像的通道数。"""
if not os.path.isdir(directory):
print("指定的目录不存在或不可访问")
return
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith((".png", ".jpg")):
file_path = os.path.join(root, file)
channels = check_image_channels(file_path)
if channels is not None:
print(f"{file_path} has {channels} channels")
if __name__ == "__main__":
directory = r"E:\pics"
check_channel(directory)