import os
import cv2
import numpy as np
import math
from PIL import Image
def crop_one_picture(path,save_split_path,height_min,width_min):
"""
切割图片
:param path: 原图路径
:param save_split_path: 切割小图保存路径
:param height_min: 切割尺寸
:param width_min: 切割尺寸
:return:
"""
for root, dirs, files in os.walk(path):
for file in files:
img = Image.open(os.path.join(root, file))
# 高度
sum_rows = img.size[0]
# 宽度
sum_cols = img.size[1]
# 创建文件夹
if not os.path.exists(save_split_path):
os.makedirs(save_split_path)
# 行列 切割
for i in range(math.ceil(sum_cols/width_min)):
for j in range(math.ceil(sum_rows/height_min)):
save_name = save_split_path + os.path.splitext(file)[0] + '_' + str(j) + '_' + \
str(i) + os.path.splitext(file)[1]
# 构建box 大小
box = (j*height_min, i*width_min, (j+1)*height_min, (i+1)*width_min)
# 切割
cropped = img.crop(box)
# 保存
cropped.save(save_name)
print("裁剪完成!")
def merge_picture(path,save_split_path,save_merge_path,height_min,width_min, merge_type):
"""
合并图片
:param path: 原图路径
:param save_split_path: 小图路径
:param save_merge_path: 合图保存路径
:param height_min: 小图尺寸
:param width_min: 小图尺寸
:param merge_type: 保存的类型
:return:
"""
# 创建文件夹
if not os.path.exists(save_merge_path):
os.makedirs(save_merge_path)
for root, dirs, files in os.walk(path):
for file in files:
# 读取原图片,获取大小
shape = cv2.imdecode(np.fromfile(os.path.join(root, file), dtype=np.uint8), cv2.IMREAD_COLOR).shape
width = shape[1]
height = shape[0]
channels = shape[2]
# 获取行和列
rows = math.ceil(height/height_min)
cols = math.ceil(width/width_min)
# 创建底板(原图大小 + 黑边大小)
dst = np.zeros((rows * height_min, cols * width_min, channels), np.uint8)
for i in range(cols):
for j in range(rows):
# 小图路径
split_name = save_split_path + os.path.splitext(file)[0] + '_' + str(j) + '_' + str(i) + os.path.splitext(file)[1]
img = cv2.imdecode(np.fromfile(split_name, dtype=np.uint8), cv2.IMREAD_COLOR)
# 合并
dst[i*height_min:(i+1)*height_min, j*width_min:(j+1)*width_min, :] = img
# 改变为原图的大小
dst_resize = dst[0:height, 0:width, :]
cv2.imencode(ext=merge_type, img=dst_resize)[1].tofile(save_merge_path + file)
print('合并完成!')
if __name__ == '__main__':
# 原图路径
path = './1/'
# 切割小图保存路径
save_split_path = './split_img/'
# 合图保存路径
save_merge_path = './merge_img/'
# 切割大小
height_min = 400
width_min = 400
# 合图保存的类型
merge_type = '.tiff'
# 切割
crop_one_picture(path, save_split_path, height_min, width_min)
# 合并
merge_picture(path, save_split_path, save_merge_path, height_min, width_min, merge_type)
原图:
切割小图:
合并图: