QBoard » Advanced Visualizations » Viz - Python » How do I convert a numpy array to an image?

How do I convert a numpy array to an image?

  • I have created an array :

    import numpy as np
    data = np.zeros( (512,512,3), dtype=np.uint8)
    data[256,256] = [255,0,0]

    What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)

      September 24, 2020 2:21 PM IST
    0
  • You could use PIL to create (and display) an image:

    from PIL import Image
    import numpy as np
    
    w, h = 512, 512
    data = np.zeros((h, w, 3), dtype=np.uint8)
    data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
    img = Image.fromarray(data, 'RGB')
    img.save('my.png')
    img.show()
      September 24, 2020 4:47 PM IST
    0
  • The following should work:

    from matplotlib import pyplot as plt
    plt.imshow(data, interpolation='nearest')
    plt.show()

    If you are using Jupyter notebook/lab, use this inline command before importing matplotlib:

    %matplotlib inline 
      September 24, 2020 4:51 PM IST
    0
  • Shortest path is to use scipy, like this:

    from scipy.misc import toimage
    toimage(data).show()

    This requires PIL or Pillow to be installed as well.

    A similar approach also requiring PIL or Pillow but which may invoke a different viewer is:

    from scipy.misc import imshow
    imshow(data)
      September 24, 2020 4:52 PM IST
    0
  • Using pillow's fromarray, for example:

    from PIL import Image
    from numpy import *
    
    im = array(Image.open('image.jpg'))
    Image.fromarray(im).show()
     
      September 24, 2020 4:54 PM IST
    0
  • here it is:

    import numpy as np
    from keras.preprocessing.image import array_to_img
    img = np.zeros([525,525,3], np.uint8)
    b=array_to_img(img)
    b​
      September 24, 2020 4:54 PM IST
    0