import os
os.environ["OPENCV_IO_MAX_IMAGE_PIXELS"] = pow(2, 50).__str__()
import matplotlib
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def split_image(image_path, output_dir,size,name=""):
with Image.open(image_path) as im:
width, height = im.size
x_slices = width // size
y_slices = height // size
idx=1
for i in range(x_slices):
for j in range(y_slices):
left = i * size
upper = j * size
right = left + size
lower = upper + size
box = (left, upper, right, lower)
piece = im.crop(box)
piece_path = f"{output_dir}/"+ name +f"_{idx}.jpg"
piece.save(piece_path)
idx+=1
if __name__ == '__main__':
size = 512 # 可以自己设置尺寸大小
path = ' '# 图片路径
split_folder = ' '# 保存路径
if not os.path.exists(split_folder):
os.mkdir(split_folder)
jpg_list = os.listdir(path)
for img in jpg_list:
jpg_name = os.path.splitext(img)[0]
path1 = os.path.join(path,img)
print("分割成小块")
split_image(path1,split_folder,size,jpg_name)
分割图像代码
最新推荐文章于 2024-09-15 13:45:34 发布
本文介绍了如何使用Python中的os,PIL和matplotlib库对大图像进行分块处理,通过`split_image`函数将大图片分割成指定大小的子图并保存。
摘要由CSDN通过智能技术生成