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

如何用双线性插值将二维numpy浮点数组调整为目标尺寸?

解决方案

你的问题出在tf.keras.utils.array_to_img步骤——它默认会将浮点数组归一化到0-255范围并转换为uint8类型的PIL图像,后续resize再转回数组自然会得到整数类型。下面是几种直接保留浮点类型、实现双线性插值resize的方法:

方法1:直接用OpenCV(最贴合需求)

既然你提到要类似cv2.resize的处理方式,直接用cv2.resize处理单通道浮点数组即可,指定双线性插值:

import cv2
import numpy as np

# 假设heatmap是形状(x, y)的浮点numpy数组,target_shape为目标(x', y')
target_shape = (x_prime, y_prime)
# cv2.resize的尺寸参数是(width, height),对应原数组的(y, x),所以要逆序传入
resized_heatmap = cv2.resize(heatmap, (target_shape[1], target_shape[0]), interpolation=cv2.INTER_LINEAR)

方法2:用TensorFlow直接处理(无需转图像)

如果想用TensorFlow生态的工具,可以直接用tf.image.resize处理张量,全程保持浮点类型:

import tensorflow as tf
import numpy as np

# 扩展为4D张量(batch, height, width, channel),符合tf.image.resize的输入要求
heatmap_4d = np.expand_dims(np.expand_dims(heatmap, axis=0), axis=-1)
# 指定双线性插值,设置目标尺寸
resized_4d = tf.image.resize(heatmap_4d, (x_prime, y_prime), method='bilinear')
# 还原为(x', y')的浮点数组
resized_heatmap = resized_4d.numpy()[0, :, :, 0]

方法3:用SciPy的ndimage.zoom

也可以用SciPy的缩放函数,order=1对应双线性插值:

from scipy.ndimage import zoom
import numpy as np

# 计算各维度的缩放因子
zoom_factor = (x_prime / heatmap.shape[0], y_prime / heatmap.shape[1])
# order=1表示双线性插值
resized_heatmap = zoom(heatmap, zoom_factor, order=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:40:27