目录
- 功能说明
- 【说明一些代码模块的从属关系的图】
- 【代码注释】
- 代码功能描述
- 代码内容
- 代码的输出,总结
功能说明
在做一些仿真实验时,得到的实验系列结果图会有很多。我们需要讲这一系列的图拼接起来,今天我们就来一起学习如何将一系列的图放在一个图中。从文件读取到图形绘制。
【说明一些代码模块的从属关系的图】
代码逻辑
【代码注释】
代码功能描述
- 能够从仿真实验的结果文件夹中读取和图相关的文件。我的仿真文件在以.out结尾的文件夹下,是一系列以n.png结尾的图形文件。首先读取这些图形文件。
- 读取之后,能够将所有的图形粘贴在一幅大图里。
代码内容
- 确认代码能够运行
import os
from PIL import Image# 仿真结果文件夹路径。如果是其他储存路径在这里改
simulation_dir = "your_file_location" # 替换为仿真结果文件夹的路径# 列出所有的'.png'文件,如果是其他类型的文件在这里改
image_files = [f for f in os.listdir(simulation_dir) if f.endswith('.png')]# 排序文件以保证顺序(如果需要的话)
image_files.sort()# 读取图像并获取单个图像的尺寸
images = [Image.open(os.path.join(simulation_dir, file)) for file in image_files]
widths, heights = zip(*(i.size for i in images))# 设置图像间的空隙大小(以像素为单位),这样保存图时中间的间隙能使图形排布更好看,不紧凑
gap = 10 # 间隙为10像素# 计算总的宽度和最大的高度(如果希望横向拼接)
# 现在总宽度还需要加上间隙的总宽度(图像数量减一乘以间隙宽度)
total_width = sum(widths) + (len(images) - 1) * gap
max_height = max(heights)# 创建新的图像,其中宽度是所有图像宽度之和加上所有间隙的宽度,高度是最高的图像高度
result_image = Image.new('RGB', (total_width, max_height), color=(255, 255, 255)) # 使用白色背景# 拼接图像
x_offset = 0
for im in images:result_image.paste(im, (x_offset, 0))x_offset += im.size[0] + gap # 在下一个图像粘贴前增加间隙# 保存大图
result_image.save('combined_image.png')
- 得到结果后,确认中间部分代码逻辑无误后。打包代码为方程黑盒,以便之后反复使用。
在function下写好注释,解释好这段代码的功能是什么。需要什么输入输出。
import os
import re
from PIL import Imagedef atoi(text):return int(text) if text.isdigit() else text# 自然排序而非字符的字典顺序
def natural_keys(text):return [atoi(c) for c in re.split(r'(\d+)', text)]def combine_images(simulation_dir, output_image_path, gap=10):"""Combine images from a simulation directory into a single image with gaps.Parameters:- simulation_dir: Path to the directory containing the simulation images.- output_image_path: Path where the combined image will be saved.- gap: The gap size in pixels between images. Default is 10 pixels."""# 列出所有的'.png'文件image_files = [f for f in os.listdir(simulation_dir) if f.endswith('.png')]# 排序文件以保证顺序(如果需要的话)#image_files.sort()# 使用自然排序算法对文件进行排序image_files.sort(key=natural_keys)# 读取图像并获取单个图像的尺寸images = [Image.open(os.path.join(simulation_dir, file)) for file in image_files]widths, heights = zip(*(i.size for i in images))# 计算总的宽度和最大的高度(如果希望横向拼接)# 现在总宽度还需要加上间隙的总宽度(图像数量减一乘以间隙宽度)total_width = sum(widths) + (len(images) - 1) * gapmax_height = max(heights)# 创建新的图像,其中宽度是所有图像宽度之和加上所有间隙的宽度,高度是最高的图像高度result_image = Image.new('RGB', (total_width, max_height), color=(255, 255, 255)) # 使用白色背景# 拼接图像x_offset = 0for im in images:result_image.paste(im, (x_offset, 0))x_offset += im.size[0] + gap # 在下一个图像粘贴前增加间隙# 保存大图result_image.save(output_image_path)print(f"Image successfully saved to {output_image_path}")# 使用函数示例
combine_images(simulation_dir="path_input", # 替换为仿真结果文件夹的路径output_image_path="path_output", # 替换希望保存合成图像的路径gap=20 # 可以调整间隙大小,让仿真图与图之间不会过于紧密
)
代码的输出,总结
以上代码是可以被反复使用的,打包好的图像处理代码。