Home > front end >  Issue with matplotlib when trying to show a png file from a URL
Issue with matplotlib when trying to show a png file from a URL

Time:09-15

I'm trying to open a png file using matplotlib to then add further layers of clusters/graphs on top. A self contained code that shows my problem is the following:

import urllib.request as urllib2
import matplotlib.pyplot as plt

DIRECTORY = "http://commondatastorage.googleapis.com/codeskulptor-assets/"
MAP_URL = DIRECTORY   "data_clustering/USA_Counties.png"

map_file = urllib2.urlopen(MAP_URL)
map_img = plt.imread(map_file)

implot = plt.imshow(map_img)

where I am getting the following error message:

runfile('G:/My Drive/Python/Fundamentals of computing/AT/Application 3/untitled0.py', wdir='G:/My Drive/Python/Fundamentals of computing/AT/Application 3')
Traceback (most recent call last):

  File "G:\My Drive\Python\Fundamentals of computing\AT\Application 3\untitled0.py", line 15, in <module>
    map_img = plt.imread(map_file)

  File "C:\Users\Tomas\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2160, in imread
    return matplotlib.image.imread(fname, format)

  File "C:\Users\Tomas\anaconda3\lib\site-packages\matplotlib\image.py", line 1560, in imread
    with img_open(fname) as image:

  File "C:\Users\Tomas\anaconda3\lib\site-packages\PIL\ImageFile.py", line 116, in __init__
    self._open()

  File "C:\Users\Tomas\anaconda3\lib\site-packages\PIL\PngImagePlugin.py", line 727, in _open
    cid, pos, length = self.png.read()

  File "C:\Users\Tomas\anaconda3\lib\site-packages\PIL\PngImagePlugin.py", line 176, in read
    pos = self.fp.tell()

UnsupportedOperation: seek

Just for a bit of extra information, I am running python on Spyder 5.2.2, within anaconda3. I already tried updating conda, spyder and the pillow package from the Anaconda prompt.

Any ideas why is this happening?

EDIT

I found a work around that involves modifying my code to not use urllib2.urlopen, but to pass the MAP_URL directly to imread, as follows:

# map_file = urllib2.urlopen(MAP_URL)
# map_img = plt.imread(map_file)
map_img = plt.imread(MAP_URL)

I'm still leaving the question because I'd like a bit of clarification on why this is working, since I'm clearly far from an expert with these libraries and packages.

CodePudding user response:

it appears as though you have already figured this out in the workaround.

Basically, the urllib2 method is not required, as plt.imread() is sufficient on its own.

So the code looks like this:

import matplotlib.pyplot as plt

DIRECTORY = "http://commondatastorage.googleapis.com/codeskulptor-assets/"
MAP_URL = DIRECTORY   "data_clustering/USA_Counties.png"

map_img = plt.imread(MAP_URL)

implot = plt.imshow(map_img)
plt.show()

and the result looks like this:

enter image description here

  • Related