Python - Read image from a URL then use for face_recognition? - python

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'

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

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().

Related

How can I edit an image's "Date taken" value and a video's "Media created" value?

On Windows, by right-clicking an image or video, then clicking on properties, then clicking on the "details" tab, origin information can be found about that file.
This is how that looks like for an image:
And this is how that looks like for a video:
I want to edit the values of the "Date taken" and "Media created" keys with Python.
What I've tried
Using the Pillow library
This is my code:
import piexif
from PIL import Image
img = Image.open("test.jpg")
exif_dict = piexif.load(img.info['exif'])
exif_dict["Exif"][piexif.ExifIFD.DateTimeOriginal] = u"2099:09:29 10:10:10"
exif_bytes = piexif.dump(exif_dict)
img.save("test", "jpg", exif=exif_bytes)
I get the error:
Traceback (most recent call last):
File "app.py", line 53, in <module>
exif_dict = piexif.load(img.info["exif"])
KeyError: 'exif'
That's because jpg images are not supported by Pillow
Using the setctime function from the win32_setctime module
from win32_setctime import setctime
setctime("test.jpg", 523434.342)
This method works only for videos, but not for images.
Also, this method works only for Windows.

TypeError: NoneType, when trying to loop crop images

from os import listdir
import cv2
files=listdir('/home/raymond/Desktop/Test/Test') #Importing the dir for cropping
for file in files:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
crop_img = img[0:1600, 0:1600]
cv2.imwrite('/home/raymond/Desktop/Test/cropped'+file,crop_img) # write new data to img
Im trying to loop crop images, while getting an error of
Traceback (most recent call last):
File "Files.py", line 8, in <module>
crop_img = img[0:1600, 0:1600]
TypeError: 'NoneType' object is not subscriptable
(fixi) ➜ exercises
You are probably missing a slash at the end of the path here:
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
Should be:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file) # reading a single image from the dir
or even better:
import os
img = cv2.imread(os.path.join('/home/raymond/Desktop/Test/Test/',file)) # reading a single image from the dir
img = cv2.imread('/home/raymond/Desktop/Test/Test'+file)
Hello Dan Raymond,
This cannot work because Python does not add a slash (/) before listed filenames.
Which means that if you have a filename "hello", then what is appended to '/home/raymond/Desktop/Test/Test' is "hello" which results in '/home/raymond/Desktop/Test/Testhello' which does not exist.
Replace your line with this:
img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file)

Read image from URL and keep it in memory

I am using Python and requests library. I just want to download an image to a numpy array for example and there are multiple questions where you can find different combinations (using opencv, PIL, requests, urllib...)
None of them work for my case. I basically receive this error when I try to download the image:
cannot identify image file <_io.BytesIO object at 0x7f6a9734da98>
A simple example of my code can be:
import requests
from PIL import Image
response = requests.get(url, stream=True)
response.raw.decode_content = True
image = Image.open(response.raw)
image.show()
The main this that is driving me crazy is that, if I download the image to a file (using urllib), the whole process runs without any problem!
import urllib
urllib.request.urlretrieve(garment.url, os.path.join(download_folder, garment.get_path()))
What can I be doing wrong?
EDIT:
My mistake was finally related with URL formation and not with requests
or PIL library. My previous code example should work perfectly if the URL is correct.
I think you are using data from requests.raw object somehow before save them in Image but requests response raw object is not seekable, you can read from it only once:
>>> response.raw.seekable()
False
First open is ok:
>>> response.raw.tell()
0
>>> image = Image.open(response.raw)
Second open throws error (stream position is on the end of file already):
>>> response.raw.tell()
695 # this file length https://docs.python.org/3/_static/py.png
>>> image = Image.open(response.raw)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 2295, in open
% (filename if filename else fp))
OSError: cannot identify image file <_io.BytesIO object at 0x7f11850074c0>
You should save data from requests response in file-like object (or file of course) if you want to use them several times:
import io
image_data = io.BytesIO(response.raw.read())
Now you can read image stream and rewind it as many times as needed:
>>> image_data.seekable()
True
image = Image.open(image_data)
image1 = Image.open(image_data)

opencv error cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale

I am following a tutorial for face recognition using python. so this is the code im using
import cv2,os
import numpy as np
from PIL import Image
recognizer = cv2.face.createLBPHFaceRecognizer()
detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
def getImagesAndLabels(path):
#get the path of all the files in the folder
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#create empth face list
faceSamples=[]
#create empty ID list
Ids=[]
#now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
#loading the image and converting it to gray scale
pilImage=Image.open(imagePath).convert('L')
#Now we are converting the PIL image into numpy array
imageNp=np.array(pilImage,'uint8')
#getting the Id from the image
Id=int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces=detector.detectMultiScale(imageNp)
#If a face is there then append that in the list as well as Id of it
for (x,y,w,h) in faces:
faceSamples.append(imageNp[y:y+h,x:x+w])
Ids.append(Id)
return faceSamples,Ids
faces,Ids = getImagesAndLabels('trainingImage')
recognizer.train(faces, np.array(Ids))
recognizer.save('trainer/trainer.yml')
and this is the error message im getting
Traceback (most recent call last):
File "/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py", line 32, in
faces,Ids = getImagesAndLabels('trainingImage')
File "/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py", line 24, in getImagesAndLabels
faces=detector.detectMultiScale(imageNp)
error: /home/pi/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
I read somewhere said that the folder I am pointing to (trainingImage) is empty, but it is not. I put my face training images there with the same filename format used by the tutorial author. I wish some one would help me with this problem.
problem solved. i had my haarcascade xml path wrong. fixed the path,and it is working as expected.

Method works in one program but not the other

I'm programming a solution to a problem, and I've run into an issue with the PIL image method.
choice = input("Would you like to save the maze as a file, Y/N?").upper()
if choice == "Y":
canvas.update()
canvas.postscript(file="maze.eps", colormode='color')
img = Image.open("maze.eps")
However I get the following error message:
Traceback (most recent call last):
File "C:\Users\Matthew\Desktop\NEA\Technical Solution\mazeVisualiser.py", line 66, in <module>
img = Image.open("maze.eps")
AttributeError: type object 'Image' has no attribute 'open'
But while learning the PIL module I know this is valid like so:
from PIL import Image
img = Image.open('brick-house.png')
Any help would be greatly appreciated as this has got me completely stuck.
Try This:
import PIL.Image
fp = open("brick-house.png", "rb")
img = PIL.Image.open(fp)
img.show()

Categories