在做AI的时候,会有图像的解码的问题,有些框架或者是算法不支持PNG格式的图片反之亦然,导致训练的时候会出现图像解码失败的情况。下面是png和jpg互转的脚本,记录下:
jpg2png:
from PIL import Image
import os
def convert_to_png(image_path, output_path):
image = Image.open(image_path)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
image.save(output_path, 'PNG')
print(f"已将图片 {image_path} 转换为PNG格式,并保存为 {output_path}")
# # 使用示例
# convert_to_png("image.jpg", "image.png")
image_path = 'test/good'
image_out = 'test/good_n'
os.makedirs(image_out, exist_ok=True)
image_list = os.listdir(image_path)
for file in image_list:
img_path = os.path.join(image_path, file)
name, ext = file.rsplit('.')
name = name + '.png'
img_out = os.path.join(image_out, name)
convert_to_png(img_path, img_out)
png2jpg
import os
from PIL import Image
filePath = '../data/input/peta/image'
jpg_name = os.listdir(filePath)
if __name__ == '__main__':
# Convert PNG format pictures to JPG format pictures
path = filePath + 's/'
if os.path.exists(path):
pass
else:
os.mkdir(path)
for name in jpg_name:
im = Image.open('../data/input/peta/image/' + name)
im = im.convert('RGB')
im.save('../data/input/peta/images/' + name[0:5] + '.jpg', quality=95)
print(name[0:5])