I want to load a jpg image from a url as a numpy array. But whenenver I do, I get an error. Can someone tell me what I can do to make my code work?
import urllib2
import matplotlib.pyplot as plt
import numpy as np
f=urllib2.urlopen("https://www.ibiblio.org/hyperwar/USA/USA-EF-Defeat/maps/USA-EF-Defeat-40.jpg")
print(f.shape)
plt.imshow(f)
plt.show()
When I run this code, I get the error:
TypeError: Image data can not convert to float
One way, is to Use PIL
to load JPG image
import urllib2
import cStringIO
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline
url='https://www.ibiblio.org/hyperwar/USA/USA-EF-Defeat/maps/USA-EF-Defeat-40.jpg'
im = Image.open(cStringIO.StringIO(urllib2.urlopen(url).read()))
plt.imshow(im, cmap='Greys_r')
or use plt.imread
with format=
to have image in numpy format directly.
im = plt.imread(urllib2.urlopen(url), format='jpeg')
# or using `io.BytesIO`
# im = plt.imread(io.BytesIO(urllib2.urlopen(url).read()), format='jpeg')
plt.imshow(im, cmap='Greys_r')