今天在做毕设答辩视频的时候,需要批处理剪裁图片,并且将批处理图片两两拼接,手动一张一张地改费时费力,于是想到用python实现了批处理,计算机不愧是干重复工作的好帮手。
首先,将图片剪裁为需要的大小(比如剪裁掉图片中的空白部分)。这个代码直接将剪裁后的图片代替了原来的图片,如果想要存到不同的文件夹,需要将存储时的文件夹位置改变。
其中,box1 = (0, 0, 1350, 1074) 表示剪裁后左边框离原图左边的距离、上边框离原图上边的距离、右边框离原图左边的距离、下边框离原图上边的距离,这个距离可以根据img.size打印出的图片大小来自己衡量剪裁多少。
# coding: utf-8
from PIL import Image
import os
import os.path
import numpy as np
# 指明被遍历的文件夹
rootdir = r'D:\four\'
for parent, dirnames, filenames in os.walk(rootdir): # 遍历每一张图片
for filename in filenames:
print('parent is :' + parent)
print('filename is :' + filename)
currentPath = os.path.join(parent, filename)
print('the fulll name of the file is :' + currentPath)
img = Image.open(currentPath)
print(img.format, img.size, img.mode)
box1 = (0, 0, 1350, 1074) # 设置左、上、右、下的坐标
image1 = img.crop(box1) # 图像裁剪
#image1.show()
image1.save(r"D:\four" + '\\' + filename) # 存储裁剪得到的图像
然后,将两个文件夹中的不同图片一一对应拼接。比如第一个文件夹中的第一张与第二个文件夹中的第一张图片拼接。
from os import listdir
from PIL import Image
import os.path
def pinjie():
rootdir1 = r'D:\four\多图片文件夹1'
rootdir2 = r'D:\four\多图片文件夹2'
path1=[] #存放图片路径
path2=[]
for parent, dirnames, filenames in os.walk(rootdir1): # 遍历每一张图片
for filename in filenames:
# print(filename)
currentPath = os.path.join(parent, filename)
path1.append(currentPath)
for parent, dirnames, filenames in os.walk(rootdir2): # 遍历每一张图片
for filename in filenames:
# print(filename)
currentPath = os.path.join(parent, filename)
path2.append(currentPath)
print(path1)
print(path2)
for i in range(0, 36):#这个范围是你要做拼接的次数。
currentPath1 = path1[i]
currentPath2 = path2[i]
img1 = Image.open(currentPath1)
img2 = Image.open(currentPath2)
width, height = img1.size
# print(width,height)
# # 创建空白长图
result = Image.new(img1.mode, (width*2, height))
result.paste(img2, box=(0,0)) #把图片2的左上角位置粘到(0,0)的位置
result.paste(img1, box=(1350,0)) #图片1的左上角位置粘到(图片2的宽度,0)的位置
# result.show()
# 保存图片
result.save(r"D:\four\%d.png"%i)
if __name__ == '__main__':
pinjie()
于是,实现了中国地图与世界地图的拼接.
+
=完成后: