利用python实现图片的横向和纵向拼接,实现起来主要有Pillow或OpenCV两个方法。两个代码略有不同,实现起来也还算简单。主要知识点是:
Pillow实现:主要采用crop,实现图片截取、采用paste,实现图片拼接。
OpenCV实现:截取直接[],截取需要的区域,采用np.vstack, np.hstack实现纵向,横向拼接。或者np.concatenate实现,通过axis来控制横向纵向。
实现代码如下:
import cv2
import numpy as np
from PIL import Image
# 程序目标,将example1 example2 分别截取上下部分,然后合成一张图
def crop_Pil():
img1 = Image.open("example1.jpg")
img2 = Image.open("example2.jpg")
print("example1 size", img1.size, " example2 size", img2.size)
img1 = img1.resize((1080, int(img1.size[1] * 1080 / img1.size[0])), Image.BILINEAR)
img2 = img2.resize((1080, int(img2.size[1] * 1080 / img2.size[0])), Image.BILINEAR)
joint = Image.new('RGB', (1080, 1920))
tmp1 = img1.crop( (0, 0, 1080, 960))
tmp2 = img2.crop((0, 0, 1080, 960))
joint.paste(tmp1, (0, 0)) # 纵向拼接
joint.paste(tmp2, (0, 960)) # 横向拼接
joint.save("output1.jpg")
joint = Image.new('RGB', (2160, 960))
joint.paste(tmp1, (0, 0))
joint.paste(tmp2, (1080, 0))
joint.save("output2.jpg")
def crop_cv2():
img1 = cv2.imread("example1.jpg")
img2 = cv2.imread("example2.jpg")
print("example1 shape", img1.shape, " example2 shape", img2.shape)
img1 = cv2.resize(img1, (1080, int(img1.shape[0] * 1080 / img1.shape[1])))
img2 = cv2.resize(img2, (1080, int(img2.shape[0] * 1080 / img2.shape[1])))
crop1 = img1[0:1080, 0:960]
crop2 = img2[0:1080, 0:960]
img3 = np.hstack((crop1, crop2)) #纵向拼接
cv2.imwrite("output4.jpg", img3)
img3 = np.vstack((crop1, crop2)) #纵向拼接
cv2.imwrite("output5.jpg", img3)
img3 = np.concatenate([crop1, crop2], axis=0) #纵向拼接
cv2.imwrite("output7.jpg", img3)
img3 = np.concatenate([crop1, crop2], axis=1)#横向拼接
cv2.imwrite("output6.jpg", img3)
if __name__ == '__main__':
crop_Pil()
crop_cv2()