python实现拼接图片
最近在写一篇卷积神经网络的论文,有好多实验结果需要整理,本来是用美图秀秀进行图像的拼接,但是发现重复操作太多,而且拼接效果不好,想到用python写个脚本实现,看一个简单的例子:
横向拼接
首先我需要将同一张图片的变形拼接为一行,代码如下:
import osfrom PIL import ImageUNIT_SIZE = 229 # 单个图像的大小为229*229TARGET_WIDTH = 6 * UNIT_SIZE # 拼接完后的横向长度为6*229path = 'C:/Users/zm/Desktop/FinalResult/Other-Reconstruction/2'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 = []
纵向拼接
将每种类型的图片拼接为一行六个的图片后再将这些图片纵向拼接在一起,总共3种图像,那么有3行
import osfrom PIL import ImageUNIT_SIZE = 229 # 图像的高TARGET_WIDTH = 6 * UNIT_SIZE # 一行有6个图像,那么是6*229那么宽path = 'C:/Users/zm/Desktop/FinalResult/Other-Reconstruction/2/result'imagefile = [] for root, dirs, files in os.walk(path): for f in files : imagefile.append(Image.open(path+’/’+f)) target = Image.new(’RGB’, (TARGET_WIDTH, UNIT_SIZE*3)) # 最终拼接的图像的大小为(229*3) * (229*6)left = 0right = UNIT_SIZEfor image in imagefile: target.paste(image, (0, left, TARGET_WIDTH, right)) left += UNIT_SIZE # 从上往下拼接,左上角的纵坐标递增 right += UNIT_SIZE #左下角的纵坐标也递增 quality_value = 100 target.save(path+’/result.jpg’, quality = quality_value)
同时横向纵向拼接
今天需要处理的图片如下:左边是图片所在的文件夹,每个文件夹的图片如→_→右边所示,需要拼接为2*5的图片。
写的脚本如下:
import osfrom PIL import ImageUNIT_SIZE = 229 # the size of image def pinjie(images,num): target = Image.new(’RGB’, (UNIT_SIZE*5, UNIT_SIZE*2)) # result is 2*5 leftone = 0 lefttwo = 0 rightone = UNIT_SIZE righttwo = UNIT_SIZE for i in range(len(images)): if(i%2==0): target.paste(images[i], (leftone, 0, rightone, UNIT_SIZE)) leftone += UNIT_SIZE #第一行左上角右移 rightone += UNIT_SIZE #右下角右移 else: target.paste(images[i], (lefttwo, UNIT_SIZE, righttwo, UNIT_SIZE*2)) lefttwo += UNIT_SIZE #第二行左上角右移 righttwo += UNIT_SIZE #右下角右移 quality_value = 100 target.save(path+dirlist[num]+’.jpg’, quality = quality_value)path = 'C:/Users/laojbdao/Desktop/FinalResult/result4/different_distribution/'dirlist = [] # all dir namefor root, dirs, files in os.walk(path): for dir in dirs : dirlist.append(dir)num = 0for dir in dirlist: images = [] # images in each folder for root, dirs, files in os.walk(path+dir): # traverse each folder print path+dir+’’ for file in files: images.append(Image.open(path+dir+’/’+file)) pinjie(images,num) num +=1 images = []
本文已被收录到专题《python图片处理操作》 ,欢迎大家点击学习更多精彩内容。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章: