Search code examples
mxnet

How to display MXNet NDArray as image in Jupyter Notebook?


I have an MXNet NDArray that has image data in it. How do I render the NDArray as image in Jupyter Notebook?

type(data)
mxnet.ndarray.ndarray.NDArray

data.shape
(3, 759, 1012)

Solution

  • Here is how to do it:

    1. Convert the MXNet NDArray to numpy array.
    2. Transpose the array to move channel to last dimension.
    3. Convert the array to uint8 (0 to 255).
    4. Render the array using matplotlib.

    Here is the code:

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

    You can then render the array by calling render_as_image.

    render_as_image(data)