检查图片(PNG/JPG)通道channel数量

该代码主要功能是检查指定目录下所有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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值