How to detect faces in photo in Python

Automatically detecting faces in a photograph has never been easier. Our image procession API lets you instantly harness the power of machine learning to trivialize this task in minutes. Let’s take a quick look at how to do this.

First step is to install the API client using pip installer.

pip install git+https://github.com/Cloudmersive/Cloudmersive.APIClient.Python.ImageRecognition.git

Second, call face_locate:

from __future__ import print_function
import time
import cloudmersive_image_api_client
from cloudmersive_image_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_image_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Apikey'] = 'Bearer'
# create an instance of the API class
api_instance = cloudmersive_image_api_client.FaceApi(cloudmersive_image_api_client.ApiClient(configuration))
image_file = '/path/to/file' # file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.
try:
# Find faces in an image
api_response = api_instance.face_locate(image_file)
pprint(api_response)
except ApiException as e:
print("Exception when calling FaceApi->face_locate: %s\n" % e)

And that’s it. No really, that’s all you’ve got to do. Let’s look at a quick example using the following image:

Image for post
Image for post

Our result looks like this:

{
"ErrorDetails": null,
"Successful": true,
"Faces": [
{
"LeftX": 521,
"TopY": 494,
"RightX": 646,
"BottomY": 618
},
{
"LeftX": 300,
"TopY": 507,
"RightX": 424,
"BottomY": 632
}
],
"FaceCount": 2
}

As you can see, it specifies the corners of each face as well as the number of total faces.

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store