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

如何将np.array存储的DICOM图像按比例缩小适配(None,128,128,1)模型输入

问题原因解析

np.resize方案失效原因

np.resize本质是数组维度的重排,仅对底层存储的像素值做截断/重复填充,完全不保留图像的空间语义关系,因此输出和原图内容没有关联,不适合用于图像缩放场景。

cv2.resize方案失效原因

直接传入三维数组(129, 512, 512)调用cv2.resize时,OpenCV会默认将第一个维度识别为图像高度、第二个为宽度、第三个为通道数,相当于将129张切片当作同一幅多通道图像处理,自然会出现比例失衡、维度不符合要求的问题。

正确实现方案

核心逻辑是逐张处理单张切片,再合并为符合要求的四维数组,以下两种实现均可:

方案1:OpenCV逐张处理(易理解,性能好)

import numpy as np
import cv2

target_size = (128, 128) # cv2.resize的dsize参数顺序为(宽度, 高度)
sample_count = train_patient.shape[0]

# 初始化输出数组
resized_patient = np.zeros((sample_count, 128, 128, 1), dtype=train_patient.dtype)
resized_mask = np.zeros((sample_count, 128, 128, 1), dtype=train_mask.dtype)

for idx in range(sample_count):
    # 医学图像用三次插值保证灰度连续性
    resized_patient[idx, ..., 0] = cv2.resize(train_patient[idx], dsize=target_size, interpolation=cv2.INTER_CUBIC)
    # 掩码必须用最近邻插值,避免生成非标签类的中间灰度值
    resized_mask[idx, ..., 0] = cv2.resize(train_mask[idx], dsize=target_size, interpolation=cv2.INTER_NEAREST)

处理后resized_patient的shape为(129, 128, 128, 1),直接符合模型输入要求。

方案2:skimage向量化处理(代码更简洁)

import numpy as np
from skimage.transform import resize

# 先给原始数据加通道维度,再统一缩放
resized_patient = resize(
    train_patient[..., np.newaxis],
    (sample_count, 128, 128, 1),
    anti_aliasing=True,
    preserve_range=True
).astype(train_patient.dtype)

resized_mask = resize(
    train_mask[..., np.newaxis],
    (sample_count, 128, 128, 1),
    order=0, # 最近邻插值
    anti_aliasing=False,
    preserve_range=True
).astype(train_mask.dtype)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 02:15:02