批量操作拼接 并保存拼接后图片(1024*1024)
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 10 16:44:53 2022
@author: 38949
"""
import numpy as np
from PIL import Image
import os
# 判断是否需要进行图像填充
def judge(img, wi, he):
width, height = img.size
# 默认新图像尺寸初始化为原图像
new_width, new_height = img.size
if width % wi != 0:
new_width = (width//wi + 1) * wi
if height % he != 0:
new_height = (height//he + 1) * he
# 新建一张新尺寸的全黑图像
new_image = Image.new('L', (new_width, new_height))
# 将原图像粘贴在new_image上,默认为左上角坐标对应
new_image.paste(img, box=None, mask=None)
new_image.show()
return new_image
# 按照指定尺寸进行图片裁剪
def crop_image(image, patch_w, patch_h):
width, height = image.size
# 补丁计数
cnt = 0
for w in range(0, width, patch_w):
for h in range(0, height, patch_h):
cnt += 1
# 指定原图片的左、上、右、下
img = image.crop((w, h, w+patch_w, h+patch_h))
img.save("475-%d.tif" % cnt)
print("图片补丁裁剪结束,共有{}张补丁".format(cnt))
def main():
img_path = r"D:\数据集\1"
img_Topath = r'D:\数据集\2'
filelist = os.listdir(img_path)
i = 0
type = 'png'
# 查看图像形状
# 输入指定的补丁宽高
# =============================================================================
# print("输入补丁宽高:")
# wi, he = map(int, input().split(" "))
# =============================================================================
for item in filelist:
arr = item.strip().split('*')
img_name = arr[0]
image_path = os.path.join(img_path, img_name)
img = Image.open(image_path)
print("原始图像形状{}".format(np.array(img).shape))
# 进行图像填充
new_image = judge(img, 1024, 1024)
# 图片补丁裁剪
crop_image(new_image, 1024, 1024)
img = new_image
img.save(img_Topath +'/'+img_name)
if __name__ == '__main__':
main()
修改后