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

如何使Matplotlib 3D表面图匹配原图维度,避免方块变形为矩形?

解决Matplotlib 3D表面图方块变形问题

你的问题核心是3D坐标轴未保持原图的宽高比例,导致方块被拉伸为矩形。以下是具体修复方案:

关键设置逻辑

  • 让X、Y轴的取值范围严格匹配原图像素尺寸(440×219),网格生成要对应单个像素的索引
  • 强制3D坐标轴保持与原图一致的宽高比,避免自动拉伸变形

修改后的代码示例

import numpy as np
import matplotlib.pyplot as plt

# 假设img_binary是已加载的440×219二维数组
img_height, img_width = img_binary.shape  # 若为彩色图需先转灰度并确认维度

# 生成匹配原图像素尺寸的X、Y网格
X = np.arange(img_width)
Y = np.arange(img_height)
X, Y = np.meshgrid(X, Y)

fig = plt.figure(figsize=(5, 4))
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, img_binary, rstride=1, cstride=1, linewidth=0, cmap='gray')

# 核心设置:固定坐标轴宽高比,参数对应(X轴长度, Y轴长度, Z轴长度)
# Z轴长度根据你的img_binary取值范围调整,比如取值0-1则设1,0-255则设255
z_range = img_binary.max() - img_binary.min()
ax.set_box_aspect((img_width, img_height, z_range))

ax.view_init(40, -20)
plt.show()

低版本兼容方案

如果你的Matplotlib版本低于3.3(set_box_aspect()是3.3+新增方法),可以用以下代码替代比例设置:

from mpl_toolkits.mplot3d.axes3d import Axes3D
# 替换ax.set_box_aspect(...)这一行
ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([img_width/img_height, 1, 1, 1]))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 12:16:04