Matplotlib 缩放 3D 曲面图尺寸并使其与真实图像尺寸不同

问题描述 投票:0回答:1

我有一张尺寸为 440x219 的 .jpg 图像。

Original .jpg image

我使用 Matplotlib 制作该图像的曲面图,该图像似乎工作正常,结果是:

Matplotlib rendered image

但是,您可以看到正方形变形为矩形。我的问题是:如何让 Matplotlib 将这些图像渲染为正方形(如原始 .jpg 中的图像)。

我当前用于渲染的代码:

 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')

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

我假设必须有一些可用的选项。任何指示将不胜感激。

python matplotlib plot surface
1个回答
0
投票

https://stackoverflow.com/a/64453375/21260084回答了如何设置Axis3d的纵横比的更普遍的问题,他们提出的解决方案工作正常。根据您的情况进行调整:

import matplotlib.pyplot as plt
import numpy as np

img = plt.imread('/tmp/ex.jpg')
fig = plt.figure(figsize=(5, 4))
ax = plt.axes(projection='3d')

xx, yy = np.mgrid[:img.shape[0], :img.shape[1]]
ax.plot_surface(xx, yy, img, rstride=1, cstride=1, linewidth=0, cmap='gray')
scale_height= 1.0
ax.set_box_aspect((img.shape[0], img.shape[1], np.ptp(img)*scale_height))

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

3d surface plot rendering of image

请注意,您还希望/必须缩放第三维。其他的。该示例将 1 个像素设置为等于灰度图像范围内 1 的变化,但您实际想要的显然取决于上下文。

© www.soinside.com 2019 - 2024. All rights reserved.