prologue
If there are abnormal images in the folder, you can use the following code to skip these abnormal images without affecting the operation of the conversion code. For example, when I was interrupted during decompression, the picture was abnormal. The picture example is as follows:
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
text
Import the library used
from PIL import Image
import os
Define format conversion functions
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)
Define the path variable for reading in the image and the variable for saving the image after format conversion
input_dir = 'E:/系统默认/桌面/rgbd_people_unihall/rgb' # 输入图片所在目录
output_dir = 'E:/系统默认/桌面/rgbd_people_unihall/rgb1' # 输出图片所在目录
The format conversion code runs
batch_convert_images(input_dir, output_dir)
full code
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)