本文实例为大家分享了python实现图片横向和纵向拼接的具体代码,
这里主要用Python扩展库pillow中Image对象的paste()方法把两张图片拼接起来供大家参考,具体内容如下:
一、代码:
from PIL import Imagedef join(png1, png2, flag='horizontal'):""":param png1: path:param png2: path:param flag: horizontal or vertical:return:"""img1, img2 = Image.open(png1), Image.open(png2)# 统一图片尺寸,可以自定义设置(宽,高)img1 = img1.resize((1500, 1000), Image.ANTIALIAS)img2 = img2.resize((1500, 1000), Image.ANTIALIAS)size1, size2 = img1.size, img2.sizeif flag == 'horizontal':joint = Image.new('RGB', (size1[0] + size2[0], size1[1]))loc1, loc2 = (0, 0), (size1[0], 0)joint.paste(img1, loc1)joint.paste(img2, loc2)joint.save('horizontal.png')elif flag == 'vertical':joint = Image.new('RGB', (size1[0], size1[1] + size2[1]))loc1, loc2 = (0, 0), (0, size1[1])joint.paste(img1, loc1)joint.paste(img2, loc2)joint.save('vertical.png')if __name__ == '__main__':# 两张图片地址:png1 = r"C:\Desktop\img\15.jpg"png2 = r"C:\Desktop\img\01.jpg"# 横向拼接join(png1, png2, flag='horizontal')# 纵向拼接# join(png1, png2, flag='vertical')