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

如何在循环中拼接13张TIFF图像为(13,224,224)数组?

TIFF图像拼接成(13,224,224)数组的解决方法

你当前的问题是循环中没有收集处理后的图像数组,无法完成批量拼接。核心思路是先把每张处理好的图像存入列表,最后一次性拼接成目标形状的数组。

修改后的完整代码

方法一:保留单张图像的(1,224,224)维度后拼接

import os
import cv2
import numpy as np

path = "你的图像文件夹路径"
imgs = os.listdir(path)
imgs.remove('metadata.json')

# 初始化空列表,用于存储所有处理后的单张图像数组
processed_images = []

for img_name in imgs:
    # 读取图像并提取第一个通道
    image = cv2.imread(os.path.join(path, img_name))[:, :, 0]
    # 缩放到224x224尺寸
    image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
    # 转换为uint8类型
    image = np.uint8(image)
    # 扩展维度为(1,224,224)
    image = np.expand_dims(image, axis=0)
    # 将当前图像加入列表
    processed_images.append(image)

# 沿axis=0拼接所有图像,得到(13,224,224)数组
final_array = np.concatenate(processed_images, axis=0)
print(final_array.shape)  # 输出:(13, 224, 224)

方法二:直接存储(224,224)图像,转换时自动扩展维度(更简洁)

import os
import cv2
import numpy as np

path = "你的图像文件夹路径"
imgs = os.listdir(path)
imgs.remove('metadata.json')

processed_images = []

for img_name in imgs:
    image = cv2.imread(os.path.join(path, img_name))[:, :, 0]
    image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
    image = np.uint8(image)
    # 直接存入(224,224)形状的数组
    processed_images.append(image)

# 转换为numpy数组时自动扩展为(13,224,224)
final_array = np.array(processed_images)
print(final_array.shape)  # 输出:(13, 224, 224)

关键说明

  • 循环中用列表收集图像是最高效的方式,避免反复拼接数组导致的内存浪费
  • 原代码中np.concatenate(image, axis=0)错误在于传入了单个数组,而非数组序列(如列表)
  • 两种方法都能得到目标形状,方法二更简洁,省去了手动扩展维度的步骤

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:30:53