You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pillow编写Python脚本批量转换RGB图像数据集为灰度图

批量将RGB图像数据集转为灰度的Pillow实现

前置依赖

先在服务器端安装所需库:
pip install pillow


脚本特性

  • 支持命令行传入数据集根路径,无需硬编码路径即可适配不同存储位置
  • 递归遍历路径下所有子文件夹,自动识别jpg、jpeg、png、bmp、tiff等常见格式图像
  • 逐张转换为标准8位单通道灰度格式,处理过程实时打印进度,单张图像损坏不会中断整体任务
  • 全流程在服务器本地完成读写,仅需上传KB级的脚本文件,完全省去大体量数据集的传输开销

完整脚本代码

import argparse
import os
from PIL import Image

# 支持识别的图像格式后缀
SUPPORTED_EXTS = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif')

def convert_dataset_to_gray(data_root: str):
    total_cnt = 0
    success_cnt = 0
    fail_cnt = 0

    # 递归遍历目录下所有文件
    for root, _, files in os.walk(data_root):
        for file in files:
            ext = os.path.splitext(file)[1].lower()
            # 跳过非图像文件
            if ext not in SUPPORTED_EXTS:
                continue
            total_cnt += 1
            file_path = os.path.join(root, file)
            try:
                with Image.open(file_path) as img:
                    # 转换为8位灰度图
                    gray_img = img.convert('L')
                    # 默认覆盖原文件,需保留原图可修改此处保存路径
                    gray_img.save(file_path)
                success_cnt += 1
                print(f"[处理成功] {file_path}")
            except Exception as e:
                fail_cnt += 1
                print(f"[处理失败] {file_path},错误信息:{str(e)}")
    
    print(f"\n任务结束!共扫描到图像{total_cnt}张,成功转换{success_cnt}张,处理失败{fail_cnt}张")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='批量转换RGB图像数据集为灰度数据集')
    parser.add_argument('--data-path', required=True, type=str, help='数据集存储的根目录路径')
    args = parser.parse_args()

    if not os.path.isdir(args.data_path):
        print(f"路径错误:{args.data_path}不是有效目录")
        exit(1)
    
    convert_dataset_to_gray(args.data_path)

使用方法

  1. 将上述代码保存为rgb2gray_dataset.py,仅需把这个小体积脚本上传到服务器即可,不需要传输原始数据集
  2. 在服务器端执行以下命令,将路径替换为你自己的数据集实际存储位置:
    python rgb2gray_dataset.py --data-path /path/to/your/dataset

注意:脚本默认转换后直接覆盖原图像文件,如果需要保留原始RGB数据,修改代码中gray_img.save()的入参为自定义输出路径即可。

内容的提问来源于stack exchange,提问作者aarya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 21:18:22