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

Python中温度网格插值到大网格遇维度错误求助

问题描述

我通过以下代码创建大网格:

min_value = -0.04
max_value = 0.04
step_size = 0.0001
xvalues = np.arange(min_value, max_value + step_size, step_size)
yvalues = np.arange(min_value, max_value + step_size, step_size)
xx, yy = np.meshgrid(xvalues, yvalues)

summed_temp = np.zeros_like(xx)

grid_coordinates = np.column_stack((xx.ravel(), yy.ravel()))

后续执行步骤:

  • 获取特定目标位置(x1,y1),以及二维温度网格target_temp_grid = ishape_temp_grid[0][:, :, 0]
  • 在大网格中找到目标位置的最近邻点,得到nearest_center_point = grid_coordinates[nearest_index]
  • 通过translate_grid函数生成该最近邻点周围的坐标
  • 对平移后的坐标进行旋转,得到新坐标

目前卡在第5、6步:需要将二维温度网格插值到预创建的全零大网格中,替换对应位置零值为温度值,之后绘制大网格并展示点位与温度值。

尝试以下代码时出现错误:

interpolated_temp = griddata(combined_rotated_coordinates, target_temp_grid.ravel(), (xx, yy), method='linear', fill_value=0)

错误信息:

File "interpnd.pyx", line 193, in scipy.interpolate.interpnd._check_init_shape
ValueError: different number of values and points
解决方案

1. 核心问题定位

报错本质是combined_rotated_coordinates的点数与target_temp_grid.ravel()的元素数不匹配,两者必须一一对应才能完成插值。

2. 校验坐标与温度值的数量匹配

先打印两者的数量,确认是否一致:

print(f"旋转后坐标点数: {combined_rotated_coordinates.shape[0]}")
print(f"温度网格元素数: {target_temp_grid.size}")

如果数量不匹配,回溯步骤3-4排查:

  • 检查translate_grid生成的坐标是否和target_temp_grid的网格维度对应(比如target_temp_grid是M×N,平移后的坐标也需是M×N个)
  • 若平移后坐标是(M,N,2)的网格形式,需先展平为(M*N,2)的二维数组:
    # 假设translate_grid返回(M,N,2)格式的平移坐标
    translated_grid = translate_grid(...)
    combined_translated_coordinates = translated_grid.reshape(-1, 2)
    # 再执行旋转操作
    combined_rotated_coordinates = rotate_coordinates(combined_translated_coordinates, angle=...) # 替换为你的旋转逻辑
    

3. 修正插值代码

确认数量匹配后,执行插值并覆盖到全零大网格:

# 先断言校验,避免不匹配问题
assert combined_rotated_coordinates.shape[0] == target_temp_grid.size, "坐标点数与温度值数不匹配"

# 执行线性插值,fill_value保持未插值区域为0
interpolated_temp = griddata(combined_rotated_coordinates, target_temp_grid.ravel(), (xx, yy), method='linear', fill_value=0)

# 将插值结果赋值给初始全零网格(若需叠加多个目标网格,可改为summed_temp += interpolated_temp)
summed_temp = interpolated_temp

4. 绘制大网格与点位

用Matplotlib绘制温度分布并标记关键点位:

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 8))
# 绘制温度热力图,设置坐标范围与原点
im = plt.imshow(summed_temp, extent=[min_value, max_value, min_value, max_value], origin='lower', cmap='inferno')
# 标记目标位置与最近邻点
plt.scatter(x1, y1, c='blue', label='目标位置', s=100)
plt.scatter(nearest_center_point[0], nearest_center_point[1], c='red', label='最近邻点', s=80, marker='x')
# 添加颜色条、图例与标签
plt.colorbar(im, label='温度值')
plt.legend()
plt.xlabel('X坐标')
plt.ylabel('Y坐标')
plt.title('大网格温度分布')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:07:29