Quick basic python tutorial on how to detect faces in images using Google's Vision API.
Code Below:
Imports system modules
import io
import os
def detect_faces(face_file, max_results=4):
Initializes image from image file path
with open(face_file, 'rb') as file:
content = file.read()
image = types.Image(content=content)
Performs face detection on the image
response = client.face_detection(image=image, max_results=max_results)
faces = response.face_annotations
likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
'LIKELY', 'VERY_LIKELY')
print('\nDetecting faces in file: {}'.format(face_file))
for face in faces:
print('Face detection confidence: {}'.format(face.detection_confidence))
print([face.joy_likelihood])
print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
print('sorrow: {}'.format(likelihood_name[face.sorrow_likelihood]))
print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
def detect_faces_uri(uri, max_results=4):
Initializes image from web url or image file path
image = vision.types.Image()
image.source.image_uri = uri
Performs face detection on the image
response = client.face_detection(image=image)
faces = response.face_annotations
Names of likelihood from google.cloud.vision.enums
likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
'LIKELY', 'VERY_LIKELY')
print('\nFaces:')
for face in faces:
#print('Face detection confidence: {}'.format(face.detection_confidence))
print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in face.bounding_poly.vertices])
print('face bounds: {}'.format(','.join(vertices)))
if input('See additional features? ') == 'yes':
print(faces)
Main starts here --------------------------------------------------------------------------------------
credential_path = r'PATH\YOUR_API_KEY.json' #modify this line
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
print('\nDetecting faces from url (input):')
detect_faces_uri(input('Enter image url: '))
detect_faces('rattlesnake_peak.jpg')
On this page of the site you can watch the video online Google Vision API Face Detection Python Tutorial with a duration of hours minute second in good quality, which was uploaded by the user Victor Yang 30 November 2019, share the link with friends and acquaintances, this video has already been watched 1,127 times on youtube and it was liked by 14 viewers. Enjoy your viewing!