如何用Python将80张图片按8行10列无间距拼接成单图?
解决Matplotlib图片无间距拼接成8行10列的问题
需求:将80张图片展示在一个figure中,排列为8行10列,图片在垂直和水平方向完全拼接(无任何间距)。
原代码存在的问题
原代码虽设置了wspace=0和hspace=0,但子图轴默认存在内边距,导致图片间仍有间隙;同时figsize设置未匹配图片实际尺寸,易引发图片拉伸变形。
修改后的代码
import matplotlib.pyplot as plt import os from PIL import Image # 图片文件夹路径 image_folder = '/Users/shaimaa/Downloads/Speaker_image.fld' # 获取所有png格式图片,取前80张避免数量超界 image_files = [f for f in os.listdir(image_folder) if f.endswith('.png')][:80] # 统一图片尺寸 img_width, img_height = 50, 50 # 根据图片像素和dpi计算figure尺寸(默认dpi=100,50像素=0.5英寸) fig_width = 10 * img_width / 100 fig_height = 8 * img_height / 100 fig = plt.figure(figsize=(fig_width, fig_height), dpi=100) # 彻底清除所有间距和边缘空白 fig.subplots_adjust(wspace=0, hspace=0, left=0, right=1, top=1, bottom=0) for idx, img_file in enumerate(image_files): row = idx // 10 col = idx % 10 # 打开并调整图片尺寸 img_path = os.path.join(image_folder, img_file) img = Image.open(img_path).resize((img_width, img_height)) # 添加子图并关闭轴显示 ax = fig.add_subplot(8, 10, idx+1) ax.imshow(img) ax.axis('off') # 移除轴内边距,隐藏刻度和边框 ax.margins(0) ax.set_xticks([]) ax.set_yticks([]) for spine in ax.spines.values(): spine.set_visible(False) plt.show()
关键修改说明
- 匹配figure尺寸:根据单图像素和默认dpi计算figure的英寸尺寸,避免图片拉伸或压缩。
- 彻底清除间距:除了子图间的
wspace和hspace,还设置left/right/top/bottom消除figure边缘空白。 - 清除轴内边距:通过
ax.margins(0)移除子图轴的内边距,同时隐藏所有轴的刻度和边框,确保图片无缝拼接。 - 限制图片数量:取前80张图片,避免循环时索引越界。
内容的提问来源于stack exchange,提问作者Shema
相关产品推荐
相关产品推荐

