功能
Faster r_cnn 训练神经网络时,从GitHub上clone作者的代码,并创建了自己的数据库。但是由于源代码中输入的图像的大小有一定的限制,一般在500-750之间, 自己创建的图像数据库中图像过大,因此用python 批量更改图像尺寸到统一大小。
从CSDN上找到了一段代码,但是这段代码在运行的时候会报错,导致部分生成的图像无法打开。对其进行了修改,修改后的代码如下所示。错误分析:”‘P’,’RGBA’,’RGB’这是PIL Image读图可能出现的三种mode,每种mode的图片数据都有不同的组织形式。
修改部分功能为:将读图的mode全部转换为“RGB“。
修改后的代码(python)
from PIL import Image
import os.path
import glob
def convertjpg(jpgfile,outdir,width=500,height=500):
img=Image.open(jpgfile)
try:
new_img = img.resize((width, height), Image.BILINEAR)
if new_img.mode == 'P':
new_img = new_img.convert("RGB")
if new_img.mode == 'RGBA':
new_img = new_img.convert("RGB")
new_img.save(os.path.join(outdir, os.path.basename(jpgfile)))
except Exception as e:
print(e)
for jpgfile in glob.glob("G:/my/Process_recent/python/Image_database/figure/spacecraft/*.jpg"):
# print(jpgfile)
convertjpg(jpgfile,"G:/my/Process_recent/python/Image_database/figure/spacecraft_unifsize")