因OCR文字识别的需要,要拼接图片
初次使用Python,写个拼接小工具
需求:
1.对图片进行横向拼接,要求长宽比不变,要求高度统一
2.对图片进行纵向拼接,不做对齐要求
代码如下
from os import listdir
from PIL import Image
#给定宽度,按比例缩放
def zoom_by_width(pic, wid):
im = pic
(x,y) = im.size
ratio = x/y #长宽比
new_x = wid
new_y = int(wid/ratio)
out = im.resize((new_x,new_y))
return out
#给定高度,按比例缩放
def zoom_by_height(pic, height):
im = pic
(x,y) = im.size
ratio = x/y #长宽比
new_x = int(height * ratio)
new_y = height
out_pic = im.resize((new_x,new_y))
#print('new_x: ' + str(out_pic.width))
#print('new_y: ' + str(out_pic.height))
#out_pic.save(str(out_pic.size) + '.jpg')
return out_pic
#横向拼接,等高拼接,按比例缩放
def compose_by_height():
#图片地址
image_PATH = 'D:\ProgramFile\xxxx\inpic'
image_save_PATH = 'D:\ProgramFile\xxxx\outPic'
maxHeight = 0 #最大高度
sumWidth = 0 #总宽度(与最大高度配套使用)
# 获取当前文件夹中所有JPG图像
im_list = [Image.open(image_PATH + '\\' + fn) for fn in listdir(image_PATH) if fn.endswith('.jpg')]
#找出最大高度
for j in im_list:
if j.height >= maxHeight:
maxHeight = j.height
print('maxHeight: '+str(maxHeight))
# 图片等比例缩放
im_zoomed = []
for i in im_list:
new_img = zoom_by_height(i , maxHeight)
im_zoomed.append(new_img)
#算出总宽度
for j in im_zoomed:
sumWidth = sumWidth + j.width
print('sumWidth: '+str(sumWidth))
# 创建空白长图
result = Image.new(im_zoomed[0].mode, (sumWidth, maxHeight))
# 拼接图片f
currentWidth = 0
for i in im_zoomed:
print('current: '+str(currentWidth))
result.paste(i, (currentWidth, 0))
currentWidth = currentWidth + i.width
# 保存图片
result.save('res2.jpg')
#默认拼接,纵向拼接,不进行缩放
def compose():
#图片地址
image_PATH = 'D:\ProgramFile\xxxx\inpic'
image_save_PATH = 'D:\ProgramFile\xxxx\outPic'
maxWidth = 0 #最大宽度
sumHeight = 0 #总高度(与最大宽度配套使用)
# 获取当前文件夹中所有JPG图像
im_list = [Image.open(image_PATH + '\\' + fn) for fn in listdir(image_PATH) if fn.endswith('.jpg')]
#找出最大宽度
for j in im_list:
if j.width >= maxWidth:
maxWidth = j.width
print('maxWidth: '+str(maxWidth))
#算出总高度
for j in im_list:
sumHeight = sumHeight + j.height
print('sumHeight: '+str(sumHeight))
# 创建空白长图
result = Image.new(im_list[0].mode, (maxWidth,sumHeight ))
# 拼接图片f
currentHeight = 0
for i in im_list:
#print('current: '+str(currentHeight))
result.paste(i, (0,currentHeight))
currentHeight = currentHeight + i.height
# 保存图片
result.save(image_save_PATH + '\\'+ 'res3.jpg')
if __name__ == '__main__':
compose()
compose_by_height()