python文字图片拼接_Python-PIL-拼接图片

本文介绍了如何使用Python的PIL库进行图片的横向和纵向拼接。首先,介绍了在Windows环境下安装PIL的方法,接着详细展示了如何通过PIL将图片横向和纵向拼接,并保存结果。在拼接过程中,注意了图片尺寸匹配的问题,以避免ValueError。
摘要由CSDN通过智能技术生成

最近学习了PIL,主要学习的是如何把当前目录下的图片拼接在一起,以下仅仅是拼接图片的学习笔记:

二、下载:

(1)windows不能通过pip直接安装(我目前是还没找到安装的方法,如有人找到了请告知一下我,此处省略一万个感谢)

(2)根据需要自己去官网选择适合自己电脑的安装包,PIL官方网站:http://pythonware.com/products/pil/

安装的需要了解更多详情,看官方文档 or 问度娘都是可以的 这里就不搬砖了

三、拼接图片:

(1)横向拼接:

import os

from PIL import Image

UNIT_SIZE = 768#高

TARGET_WIDTH = 1184*6 # 拼接完后的横向长度

path = "D:/imgs/"

images = [] # 先存储所有的图像的名称

for root, dirs, files in os.walk(path):

for f in files :

images.append(f)

for i in range(len(images)/6): # 6个图像为一组

imagefile = []

j = 0

for j in range(6):

imagefile.append(Image.open(path+images[i*6+j]))

target = Image.new('RGB', (TARGET_WIDTH, UNIT_SIZE))

left = 0

right = UNIT_SIZE

for image in imagefile:

target.paste(image, (left, 0, right, UNIT_SIZE))# 将image复制到target的指定位置中

left += UNIT_SIZE # left是左上角的横坐标,依次递增

right += UNIT_SIZE # right是右下的横坐标,依次递增

quality_value = 100 # quality来指定生成图片的质量,范围是0~100

target.save(path+'/result/'+os.path.splitext(images[i*6+j])[0]+'.jpg', quality = quality_value)

imagefile = []

(2)纵向拼接:

import os

from PIL import Image

high_size = 768#高

width_size = 1184#宽

path = u'D:/imgs/'

imghigh = sum([len(x) for _, _, x in os.walk(os.path.dirname(path))])#获取当前文件路径下的文件个数

print imghigh

imagefile = []

for root,dirs,files in os.walk(path):

for f in files:

imagefile.append(Image.open(path+f))

target = Image.new('RGB',(width_size,high_size*imghigh))#最终拼接的图像的大小

left = 0

right = high_size

for image in imagefile:

target.paste(image,(0,left,width_size,right))

left += high_size#从上往下拼接,左上角的纵坐标递增

right += high_size#左下角的纵坐标也递增

target.save(path+'result.jpg',quality=100)

*ValueError: images do not match表示图片大小和box对应的宽度不一致,参考API说明:Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.使用2纬的box避免上述问题

后续再更新...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值