在 matplotlib 中打开灯

Nat*_*iel 4 python matplotlib

我有以下Python代码:

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = [12, 7]

n = 100
m = 100

X = np.arange(-n/2,n/2,1)
Y = np.arange(-m/2,m/2,1)
X, Y = np.meshgrid(X, Y)
    
landscape = np.exp(-0.01 * (X*X + Y*Y) )

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.plot_surface(X, Y, landscape,
                linewidth=0,
                antialiased=False
                )
Run Code Online (Sandbox Code Playgroud)

在笔记本中运行它会生成此图像

在此输入图像描述

如果仔细观察,您会发现高斯峰的左侧比右侧稍微亮一些。不过,这种照明效果几乎不可见,我想增加它,以便 3D 形状变得容易可见。

我知道matplotlib.colors.LightSource,但无论我做什么,我都无法让它产生我想要的效果。理想情况下,我只想增加“默认”照明的强度,而不是摆弄它。但如果有人能解释如何使用 LightSource 来处理此图像,那也会有帮助。

请注意,我不想对图像应用高度图,也不想在其上绘制网格线 - 我只是想增加照明效果,同时保持表面颜色均匀。

还值得一提的是,我有点坚持使用 MatPlotLib,因为我使用Jupyterlite与没有安装 Python 的学生共享笔记本,所以我需要一个适用于它的解决方案。

Guy*_*Guy 5

Using LightSource you can do something like

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import LightSource

plt.rcParams['figure.figsize'] = [12, 7]

n = 100
m = 100

X = np.arange(-n / 2, n / 2, 1)
Y = np.arange(-m / 2, m / 2, 1)
X, Y = np.meshgrid(X, Y)

landscape = np.exp(-0.01 * (X * X + Y * Y))

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

# this is used to set the graph color to blue
blue = np.array([0., 0., 1.])
rgb = np.tile(blue, (landscape.shape[0], landscape.shape[1], 1))

ls = LightSource()
illuminated_surface = ls.shade_rgb(rgb, landscape)

ax.plot_surface(X, Y, landscape,
                linewidth=0,
                antialiased=False,
                facecolors=illuminated_surface)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

If you want the light from the right change the azdeg parameter at the LightSource creation

ls = LightSource(azdeg=80)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Parameters
    ----------
    azdeg : float, default: 315 degrees (from the northwest)
        The azimuth (0-360, degrees clockwise from North) of the light
        source.
    altdeg : float, default: 45 degrees
        The altitude (0-90, degrees up from horizontal) of the light
        source.
Run Code Online (Sandbox Code Playgroud)