Python-PIL-拼接图片

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

一、学习的网址:
  PIL – 廖雪峰的官方网站
  图像简单处理(PIL or Pillow)
  Python拼接图片
  PIL官方文档:http://effbot.org/imagingbook/

二、下载:
  (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避免上述问题

后续再更新…

操作图像部分源码:
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_resize.py
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_blur.py
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_draw.py
侵删

    原文作者:Koelre
    原文地址: https://www.jianshu.com/p/9a4739420c9e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞