Reputation: 817
I am trying to feed an image from URL to a face_recognition library that I'm using, but it does not seem to be working.
I have tried the suggestion here: https://github.com/ageitgey/face_recognition/issues/442 but it did not work for me. I'm thinking that my problem is with the method that I'm using for fetching the image, and not the face_recognition library, that's why I decided to post the question here.
Bellow is my code:
from PIL import Image
import face_recognition
import urllib.request
url = "https://carlofontanos.com/wp-content/themes/carlo-fontanos/img/carlofontanos.jpg"
img = Image.open(urllib.request.urlopen(url))
image = face_recognition.load_image_file(img)
# Find all the faces in the image using the default HOG-based model.
face_locations = face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
# Print the location of each face in this image
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# You can access the actual face itself like this:
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.show()
I'm getting the following response when running the above code:
Traceback (most recent call last):
File "test.py", line 10, in <module>
image = face_recognition.load_image_file(img)
File "C:\Users\Carl\AppData\Local\Programs\Python\Python37-32\lib\site-packages\face_recognition\api.py", line 83, in load_image_file
im = PIL.Image.open(file)
File "C:\Users\Carl\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\Image.py", line 2643, in open
prefix = fp.read(16)
AttributeError: 'JpegImageFile' object has no attribute 'read'
I think the problem is with the line AttributeError: 'JpegImageFile' object has no attribute 'read'
Upvotes: 0
Views: 2681
Reputation: 142824
You don't need Image
to load it
response = urllib.request.urlopen(url)
image = face_recognition.load_image_file(response)
urlopen()
gives object which has methods read()
, seek()
so it is treated as file-like object
. And load_image_file()
needs filename
or file-like object
Upvotes: 1
Reputation: 1327
urllib.request.urlopen(url)
returns a http response and not an image file. i think you are supposed to download the image and give the path of the files as input to load_image_file().
Upvotes: 0