【Python编程】将格式为ppm和pgm的图片批量转换为png或jpg格式的图片

前序

如果文件夹中有异常图片,则可以使用以下代码从而跳过这些异常图片而不影响转换代码的运行。例如本人在解压时中断而导致的图片异常问题,图片示例如下:
在这里插入图片描述

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True

正文

导入用到的库

from PIL import Image
import os

定义格式转换函数

def batch_convert_images(input_dir, output_dir):
    for filename in os.listdir(input_dir):
        if filename.endswith('.ppm') or filename.endswith('.pgm'):
            img_path = os.path.join(input_dir, filename)
            img = Image.open(img_path)
            new_filename = os.path.splitext(filename)[0] + '.png'
            save_path = os.path.join(output_dir, new_filename)
            img.save(save_path)

定义读入图片的路径变量和格式转换后图片保存路径的变量

input_dir = 'E:/系统默认/桌面/rgbd_people_unihall/rgb'  # 输入图片所在目录
output_dir = 'E:/系统默认/桌面/rgbd_people_unihall/rgb1'  # 输出图片所在目录

格式转换代码运行

batch_convert_images(input_dir, output_dir)

完整代码

from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True   # 这两句代码可写可不写,如果自己要转换的文件夹中的图片没有异常,可不写

from PIL import Image
import os

def batch_convert_images(input_dir, output_dir):
    for filename in os.listdir(input_dir):
        if filename.endswith('.ppm') or filename.endswith('.pgm'):
            img_path = os.path.join(input_dir, filename)
            img = Image.open(img_path)
            new_filename = os.path.splitext(filename)[0] + '.png'
            save_path = os.path.join(output_dir, new_filename)
            img.save(save_path)

# 使用示例
input_dir = 'E:/系统默认/桌面/rgbd_people_unihall/rgb'  # 输入图片所在目录
output_dir = 'E:/系统默认/桌面/rgbd_people_unihall/rgb1'  # 输出图片所在目录
batch_convert_images(input_dir, output_dir)

猜你喜欢

转载自blog.csdn.net/lingchen1906/article/details/131425686