python批量放大图片

在尝试Tesseract-OCR对图片进行字符识别,训练样本的时候,发现直接截下来的图识别成功率不高,而放大图片后效果会改善,所以写了如下代码,能够对文件夹下图片进行判别,并批量将其放大为想要的大小。

代码:

import os
from PIL import Image
import sys


#获取path目录下的所有文件
def get_imlist(path):
    return[os.path.join(path,f)
           for f in os.listdir(path)]


def change_size(path):
    directorys=get_imlist(path)
    for directory in directorys:
    #不是图片文件就跳过
        print(directory)
        if not(directory.endswith('.jpg') or directory.endswith('.png') or directory.endswith('.bmp')):
            pass
        else:
            img=Image.open(directory)
            s="/"
            #获取文件名(含后缀)
            oimage_name=directory[directory.rfind(s)+1:]
            (oimage_width,oimage_height)=img.size
            new_width=oimage_width * 3
            new_height=oimage_height * 3
            out=img.resize((new_width,new_height),Image.ANTIALIAS)
            out.save("%s" %oimage_name)  #直接替换


if __name__ == '__main__':
    change_size("2")

你可能感兴趣的:(python)