You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按图像ID将网格TIF图像分配到Matplotlib对应网格位置

解决图像按ID分配到网格位置的方案

步骤说明

  1. 解析文件名提取位置标识:从文件名中拆分出A1这类位置代码,这是映射到网格的核心依据。
  2. 位置转网格索引:
    • 行标识A-H对应网格行索引0-7(A是第1行,对应索引0)
    • 列标识1-12对应网格列索引0-11(1是第1列,对应索引0)
  3. 修正子图行列参数:你当前代码里plt.subplots(12, 8)是创建12行8列的网格,但需求是8行12列(A-H共8行,1-12共12列),所以要改成plt.subplots(8, 12)。
  4. 读取并绘制图像:遍历每个图像,读取后放到对应索引的子图中,隐藏多余的坐标轴。

完整代码

import os
import matplotlib.pyplot as plt
from PIL import Image

# Config:
images_dir = r'C:\Users\pateld1\Pictures\Incucyte\P1'  # 用原始字符串避免Windows路径转义问题
result_grid_filename = './grid.jpg'
result_figsize_resolution = 40  # 1 = 100px

images_list = os.listdir(images_dir)
images_count = len(images_list)
print('Images: ', images_list)
print('Images count: ', images_count)

# 创建8行12列的网格(对应A-H行,1-12列)
fig, axes = plt.subplots(8, 12, figsize=(result_figsize_resolution, result_figsize_resolution))

# 定义行标识到索引的映射
row_map = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7}

for img_name in images_list:
    # 拆分文件名提取位置代码,比如从VID1433_A1_1_00d00h00m.tif中取A1
    parts = img_name.split('_')
    if len(parts) < 2:
        continue  # 跳过不符合命名格式的文件
    pos_code = parts[1]  # 获取A1、B5这类位置标识
    
    # 拆分位置代码为行和列
    row_char = pos_code[0]
    col_num = int(pos_code[1:])
    
    # 转换为网格索引
    row_idx = row_map.get(row_char)
    col_idx = col_num - 1  # 列1对应索引0
    
    # 检查索引是否有效
    if row_idx is None or col_idx <0 or col_idx >=12:
        print(f"跳过无效位置的文件: {img_name}")
        continue
    
    # 读取图像
    img_path = os.path.join(images_dir, img_name)
    img = Image.open(img_path)
    
    # 在对应子图绘制图像,隐藏坐标轴
    ax = axes[row_idx, col_idx]
    ax.imshow(img)
    ax.axis('off')

# 调整子图间距,避免重叠
plt.tight_layout()
# 保存结果
plt.savefig(result_grid_filename, dpi=100)
plt.close()

关键细节

  • 用row_map字典快速将字母行转成索引,避免复杂的字符计算。
  • 处理不符合命名格式的文件,防止程序报错。
  • 使用tight_layout()自动调整子图间距,保证图像排列整齐。
  • 隐藏坐标轴让网格看起来更整洁,符合拼接成大网格的需求。

内容的提问来源于stack exchange,提问作者user12367917

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:06:25