pytohn用Pillow或OpenCV实现图片截取、横向纵向拼接

利用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()
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值