Displaying/getting Images from an URL in Python - python

I am new to python. But I got a task and I need to Displaying/getting Images from an URL.
I have been using Jupyter notebook with python to try to do this.
import sys
print(sys.version)
3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]
I was trying to do it as in this post but none of the answers work.
With
import urllib, cStringIO
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
I get:
ImportError Traceback (most recent call last)
<ipython-input-33-da63c9426dad> in <module>()
1 url='http://images.mid-day.com/images/2017/feb/15-Justin-Bieber.jpg'
2 print(url)
----> 3 import urllib, cStringIO
4
5 file = cStringIO.StringIO(urllib.urlopen(URL).read())
ImportError: No module named 'cStringIO'
With:
from PIL import Image
import requests
from io import BytesIO
response = requests.get(url)
img = Image.open(BytesIO(response.content))
I get:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-11-168cd6221ea3> in <module>()
1 #response = requests.get("https://baobab-poseannotation-appfile.s3.amazonaws.com/media/project_5/images/images01/01418849d54b3005.o.1.jpg")
----> 2 response.read("https://baobab-poseannotation-appfile.s3.amazonaws.com/media/project_5/images/images01/01418849d54b3005.o.1.jpg").decode('utf-8')
3 img = Image.open(StringIO(response.content))
AttributeError: 'Response' object has no attribute 'read'
With:
from PIL import Image
import requests
from StringIO import StringIO
response = requests.get(url)
img = Image.open(StringIO(response.content))
I get:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-37-5716207ad35f> in <module>()
3 from PIL import Image
4 import requests
----> 5 from StringIO import StringIO
6
7 response = requests.get(url)
ImportError: No module named 'StringIO'
Etc....
I thought it was going to be an easy task, but so far I haven't been able to find an answer.
I really hope someone can help me

This worked for me
from PIL import Image
import requests
from io import BytesIO
url = "https://baobab-poseannotation-appfile.s3.amazonaws.com/media/project_5/images/images01/01418849d54b3005.o.1.jpg"
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.show()
You are getting an error because you used the line response.read("https://baobab-poseannotation-appfile.s3.amazonaws.com/media/project_5/images/images01/01418849d54b3005.o.1.jpg").decode('utf-8') instead. I'd switch back to using response = requests.get(url)
Additionally, for your error: ImportError: No module named 'cStringIO', you are using python3. StringIO and cStringIO from python 2 were removed in python 3. Use from io import StringIO instead. See StringIO in Python3 for more details.

This might be duplicated with https://stackoverflow.com/a/46954931/4010864.
For your third option with PIL you can try this:
from PIL import Image
import requests
import matplotlib.pyplot as plt
response = requests.get(url, stream=True)
img = Image.open(response.raw)
plt.imshow(img)
plt.show()

Related

Using urllib.request to write an image

I am trying to use this code to download an image from the given URL
import urllib.request
resource = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
output = open("file01.jpg","wb")
output.write(resource)
output.close()
However, I get the following error:
TypeError Traceback (most recent call last)
<ipython-input-39-43fe4522fb3b> in <module>()
41 resource = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
42 output = open("file01.jpg","wb")
---> 43 output.write(resource)
44 output.close()
TypeError: a bytes-like object is required, not 'tuple'
I get that its the wrong data type for the .write() object but I don't know how to feed resource into output
Right, Using urllib.request.urlretrieve like this way:
import urllib.request
resource, headers = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
image_data = open(resource, "rb").read()
with open("file01.jpg", "wb") as f:
f.write(image_data)
PS: urllib.request.urlretrieve return a tuple, the first element is the location of temp file, you could try to get the bytes of temp file, and save it to a new file.
In Official document:
The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.
So I would recommend you to use urllib.request.urlopen,try code below:
import urllib.request
resource = urllib.request.urlopen("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
output = open("file01.jpg", "wb")
output.write(resource.read())
output.close()

Importing PIL ImageFont is giving a py3 import error

I'm trying to import a PIL ImageFont but when I do that, it gives me the following error:
<ipython-input-16-ef225ec0d8fd> in <module>()
----> 1 from PIL import ImageFont
/usr/local/lib/python3.6/dist-packages/PIL/ImageFont.py in <module>()
27
28 from . import Image
---> 29 from ._util import isDirectory, isPath, py3
30 import os
31 import sys
ImportError: cannot import name 'py3'
I can't find any similar issues on the internet related with this.

NameError: name 'images' is not defined

I was trying to import some images to my local computer from amazon using their api for data analysis
This is my code I am getting this error.Don't know what to do Please suggest some solution
Code
from PIL import Image
import requests
from io import BytesIO
for index, row in images.iterrows():
url = row['large_image_url']
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.save('images/15k_images/'+row['asin']+'.jpeg')
Error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-36-ce8803db815e> in <module>()
9 from io import BytesIO
10
---> 11 for index, row in images.iterrows():
12 url = row['large_image_url']
13 response = requests.get(url)
NameError: name 'images' is not defined

Import .edf file directly from online archive in python

Using pyedflib to import edf files, is it possible to import datasets directly from their source? Or is it always necessary to download data and import locally?
for example, I would like to do this:
pyedflib.EdfReader("https://www.physionet.org/pn6/chbmit/chb02/chb02_02.edf")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-64-d123ce671a2f> in <module>()
----> 1 pyedflib.EdfReader("https://www.physionet.org/pn6/chbmit/chb02/chb02_02.edf")
pyedflib/_extensions/_pyedflib.pyx in pyedflib._extensions._pyedflib.CyEdfReader.__init__()
pyedflib/_extensions/_pyedflib.pyx in pyedflib._extensions._pyedflib.CyEdfReader.open()
pyedflib/_extensions/_pyedflib.pyx in pyedflib._extensions._pyedflib.CyEdfReader.check_open_ok()
IOError: can not open file, no such file or directory
Answer received on GitHub page
import pyedflib
import os
url = "https://www.physionet.org/pn6/chbmit/chb01/chb01_01.edf"
filename = "./chb.edf"
try:
from urllib import urlretrieve # Python 2
except ImportError:
from urllib.request import urlretrieve # Python 3
urlretrieve(url,filename)
pyedflib.EdfReader(filename)
os.remove(filename)
https://github.com/holgern/pyedflib/issues/22#issuecomment-341649760

Python - how to read an image from a URL?

I am completely new to Python and I'm trying to figure out how to read an image from a URL.
Here is my current code:
from PIL import Image
import urllib.request, io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
s = url.read()
Image.open(s)
I get the following error:
C:\python>python image.py
Traceback (most recent call last):
File "image.py", line 8, in <module>
Image.open(s)
File "C:\Anaconda3\lib\site-packages\PIL\Image.py", line 2272, in open
fp = builtins.open(filename, "rb")
ValueError: embedded null byte
I have no idea what any of this means. What am I doing wrong?
Image.open() expects filename or file-like object - not file data.
You can write image locally - i.e. as "temp.jpg" - and then open it
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
with open('temp.jpg', 'wb') as f:
f.write(url.read())
img = Image.open('temp.jpg')
img.show()
Or you can create file-like object in memory using io module
from PIL import Image
import urllib.request
import io
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
f = io.BytesIO(url.read())
img = Image.open(f)
img.show()
EDIT: 2022
Because urlopen() also gives file-like object so you can even skip io and use directly url (without .read()) in Image.open()
from PIL import Image
import urllib.request
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
img = Image.open(url)
img.show()
Here's how to read an image from a URL using scikit-image
from skimage import io
io.imshow(io.imread("http://www.w3schools.com/css/trolltunga.jpg"))
io.show()
Note: io.imread() returns a numpy array
To begin with, you may download the image to your current working directory first
from urllib.request import urlretrieve
url = 'http://www.w3schools.com/css/trolltunga.jpg'
urlretrieve(url, 'pic.jpg')
And then open/read it locally:
from PIL import Image
img = Image.open('pic.jpg')
# For example, check image size and format
print(img.size)
print(img.format)
img.show()
As suggested in this stack overflow answer, you can do something like this:
import urllib, cStringIO
from PIL import Image
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
Then you can use your image freely.
For example, you can convert it to a numpy array:
img_npy = np.array(img)

Categories