Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib.pyplot.imshow() shows blank canvas

I've come across an oddity that the internet hasn't been able to solve so far. If I read in a .png file, then try to show it, it works perfectly (in the example below the file is a single blue pixel). However, if I try to create this image array manually, it just shows a blank canvas. Any thoughts?

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

im = Image.open('dot.png') # A single blue pixel
im1 = np.asarray(im)
print im1
# [[[  0 162 232 255]]]

plt.imshow(im1, interpolation='nearest')
plt.show() # Works fine

npArray = np.array([[[0, 162, 232, 255]]])
plt.imshow(npArray, interpolation='nearest')
plt.show() # Blank canvas

npArray = np.array([np.array([np.array([0, 162, 232, 255])])])
plt.imshow(npArray, interpolation='nearest')
plt.show() # Blank canvas

P.S. I've also tried replacing all of the np.array() with np.asarray(), but the outcome is just the same.

like image 337
LomaxOnTheRun Avatar asked Feb 11 '23 05:02

LomaxOnTheRun


1 Answers

According to the im.show docs:

X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
    Display the image in `X` to current axes.  `X` may be a float
    array, a uint8 array or a PIL image.

So X may be an array with dtype uint8.

When you don't specify a dtype,

In [63]: np.array([[[0, 162, 232, 255]]]).dtype
Out[63]: dtype('int64')

NumPy may create an array of dtype int64 or int32 (not uint8) by default.


If you specify dtype='uint8' explicitly, then

import matplotlib.pyplot as plt
import numpy as np

npArray = np.array([[[0, 162, 232, 255]]], dtype='uint8')
plt.imshow(npArray, interpolation='nearest')
plt.show() 

yields enter image description here


PS. If you check

im = Image.open('dot.png') # A single blue pixel
im1 = np.asarray(im)
print(im1.dtype)

you'll find im1.dtype is uint8 too.

like image 179
unutbu Avatar answered Feb 13 '23 03:02

unutbu