如何在 Jupyter Notebook 中将 MXNet NDArray 显示为图像?

How to display MXNet NDArray as image in Jupyter Notebook?

我有一个 MXNet NDArray,其中包含图像数据。如何在 Jupyter Notebook 中将 NDArray 渲染为图像?

type(data)
mxnet.ndarray.ndarray.NDArray

data.shape
(3, 759, 1012)

操作方法如下:

  1. 将 MXNet NDArray 转换为 numpy 数组。
  2. 转置数组以将通道移动到最后一个维度。
  3. 将数组转换为 uint8(0 到 255)。
  4. 使用 matplotlib 渲染数组。

代码如下:

import mxnet as mx
import numpy as np
from matplotlib import pyplot as plt

def render_as_image(a):
    img = a.asnumpy() # convert to numpy array
    img = img.transpose((1, 2, 0))  # Move channel to the last dimension
    img = img.astype(np.uint8)  # use uint8 (0-255)

    plt.imshow(img)
    plt.show()

然后您可以通过调用 render_as_image 来呈现数组。

render_as_image(data)

要使用 Matplotlib 显示图像或任何其他绘图,您首先需要将 MXNet NDArray 转换为 NumPy 数组。

例如,a 是您的 MXNet NDArray 以将其转换为 Numpy,我们将这样做 b = a.asnumpy()。现在您可以使用 Matplotlib plot/show 这个 b