因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()