今天跑深度学习时因为数据集的图片尺寸和代码不一致,反向传播时出现某一层输入和输出的格式对不上一直报错,没搞明白代码怎么改,直接调整了图片尺寸去适配代码,顺便做一下笔记。
png转jpg
from PIL import Image
import os
import re
def png2jpg(png_file_path, jpg_dir_path):
infile = png_file_path
img = Image.open(infile)
image_name = re.sub(r'png|PNG$', 'jpg', re.sub(r'.*[/\\]', '', png_file_path))
outfile = jpg_dir_path + image_name
if not os.path.exists(jpg_dir_path):
os.makedirs(jpg_dir_path)
try:
if len(img.split()) == 4:
# prevent IOError: cannot write mode RGBA as BMP
r, g, b, a = img.split()
img = Image.merge("RGB", (r, g, b))
# quality表示图片质量,1最差,95最佳,设置为100会导致部分jpg压缩算法不执行
img.convert('RGB').save(outfile, quality=95)
else:
img.convert('RGB').save(outfile, quality=95)
return outfile
except Exception as e:
print("PNG转换JPG 错误", e)
像素大小调整
from PIL import Image
import os
import re
def resize_image(image_path, output_dir, w, h):
image_name = re.sub(r'.*[/\\]', '', image_path)
outfile = output_dir + image_name
if not os.path.exists(output_dir):
os.makedirs(output_dir)
img = Image.open(image_path)
img.resize((w, h), Image.ANTIALIAS).save(outfile, quality=95)
在深度学习项目中,因图片尺寸与代码不匹配导致的反向传播错误,通过调整图片尺寸和转换格式来解决问题。介绍了使用Python和PIL库进行png转jpg及图片尺寸调整的方法。
3673

被折叠的 条评论
为什么被折叠?



