如何在Python中将图像正确地显示为具有步骤转换的3D绘图?

2024-09-30 04:40:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用3D来形象化图像之间的差异,以便更容易地区分积极和消极的差异。在

我已经成功地绘制了一幅图像的基本图,但是,值之间的matplotlib是插值。我需要这些是像素之间的阶跃变化。在

我经常测试非常低分辨率的图像,例如,16×16,所以插值有很大的影响。在

16 x 16的Numpy文件图像: https://wetransfer.com/downloads/c916f76e0d86a61c00c2ed4cfe4ae97520190210192200/60d87c

解决这个问题的一种方法是重复这些值,但是,这看起来效率很低,需要在之后清除刻度。在

enter image description here

生成上述图像的代码:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

SubIm = np.load("Subtract_Image.npy")

def ImPlot2D3D(img, cmap=plt.cm.jet):

    Z = img[::1, ::1]

    fig = plt.figure(figsize=(14, 7))

    # 2D Plot
    ax1 = fig.add_subplot(1, 2, 1)
    im = ax1.imshow(Z, cmap=cmap)
    ax1.set_title('2D')
    ax1.grid(False)

    # 3D Plot
    ax2 = fig.add_subplot(1, 2, 2, projection='3d')
    X, Y = np.mgrid[:Z.shape[0], :Z.shape[1]]
    ax2.plot_surface(X, Y, Z, cmap=cmap)
    ax2.set_title('3D')

    plt.show()


ImPlot2D3D(SubIm)

我看过3D柱状图,但它们都使用分块方案,我无法使其适用于图像。在


Tags: 图像importimgmatplotlibasnpfigplt
1条回答
网友
1楼 · 发布于 2024-09-30 04:40:14

最后终于回答了我自己的问题。在

解决这一问题的一种强力方法是重复数组中的值,从而使“matplotlib”所做的值之间的插值,影响更小,更接近阶跃变化。 这可以通过使用numpy.repeat来实现。由于这是一个三维数组,我们必须在一个轴上迭代,而不是在另一个轴上迭代。否则,将重复展平数组并返回此平面数组。在

结果: Results:

def ImPlot2D3D(img, cmap=plt.cm.jet, step=False, ratio=10):

    if step:
        img = (img.repeat(ratio, axis=0)).repeat(ratio, axis=1)

    Z = img[::1, ::1]

    fig = plt.figure(figsize=(14, 7))

    # 2D Plot
    ax1 = fig.add_subplot(1, 2, 1)
    im = ax1.imshow(Z, cmap=cmap)
    ax1.set_title('2D')
    ax1.grid(False)

    # 3D Plot
    ax2 = fig.add_subplot(1, 2, 2, projection='3d')
    X, Y = np.mgrid[:Z.shape[0], :Z.shape[1]]
    ax2.plot_surface(X, Y, Z, cmap=cmap)
    ax2.set_title('3D')

    # Scale the ticks back down to original values
    if step:
        ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x / ratio))
        ticks_y = ticker.FuncFormatter(lambda y, pos: '{0:g}'.format(y / ratio))
        ax1.xaxis.set_major_formatter(ticks_x)
        ax1.yaxis.set_major_formatter(ticks_y)
        ax2.xaxis.set_major_formatter(ticks_x)
        ax2.yaxis.set_major_formatter(ticks_y)

    plt.show()

import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

SubIm = np.load("Subtract_Image.npy")
ImPlot2D3D(SubIm, step=True)

相关问题 更多 >

    热门问题