长宽等效,都适用
from PIL import Image
import os
#说明:依据装滚珠方法,默认单张图片缩放(也可以文件夹遍历),例如需要正方形模板,长大于宽的,缩放到长与正方形相等
wanlen = 1280
wanwidth = 720
indir = "G:/PythonIO/outImg"
def dirlist(path, allfile):
filelist = os.listdir(path)
for filename in filelist: #广义
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
dirlist(filepath, allfile)
else:
filepath = filepath.replace("\\","/")
allfile.append(filepath)
print(filepath)
return allfile
#######
cutyes = 1
def solveImage(infile):
outfile = infile.replace(".", "out.")
img = Image.open(infile)
# img.show()
# grayimg = img.convert('L')
# grayimg.save(outfile)
lenmore = True
imgsize = img.size
if (imgsize[0] / imgsize[1] < wanlen / wanwidth):
print(imgsize)
lenmore = True
relength = int(imgsize[0] * wanwidth / imgsize[1])
# print("len more" + str(relength))
out = img.resize((relength, wanwidth), Image.ANTIALIAS) # 抗毛刺
else:
print(imgsize)
lenmore = False
rewidth = int(imgsize[1] * wanlen / imgsize[0])
out = img.resize((wanlen, rewidth), Image.ANTIALIAS)
if cutyes == 1:
# 裁剪
if lenmore:
left = int(relength / 2 - wanlen / 2)
cropped = out.crop((left, 0, left + wanlen, wanwidth))
cropped.save(outfile)
else:
right = int(rewidth / 2 - wanwidth / 2)
cropped = out.crop((0, right, wanlen, right + wanwidth))
cropped.save(outfile)
cropped.save(outfile)
else:
out.save(outfile)
allfile = dirlist(indir,[])
# for infile in allfile:
# solveImage(infile)
cutyes = 0
solveImage("G:/PythonIO/bs_title_bgd.png")