How to detect faces in photo in Ruby
2 min readAug 11, 2019
Let’s see how to use our image recognition API to easily detect faces in photos. The first step for Ruby users is to add the client to your Gemfile:
gem 'cloudmersive-image-recognition-api-client', '~> 1.3.2'
Next, call the function face_locate:
# load the gem
require 'cloudmersive-image-recognition-api-client'
# setup authorization
CloudmersiveImageRecognitionApiClient.configure do |config|
# Configure API key authorization: Apikey
config.api_key['Apikey'] = 'YOUR API KEY'
# Uncomment the following line to set a prefix for the API key, e.g. 'Bearer' (defaults to nil)
#config.api_key_prefix['Apikey'] = 'Bearer'
endapi_instance = CloudmersiveImageRecognitionApiClient::FaceApi.newimage_file = File.new("/path/to/file.txt") # File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.begin
#Find faces in an image
result = api_instance.face_locate(image_file)
p result
rescue CloudmersiveImageRecognitionApiClient::ApiError => e
puts "Exception when calling FaceApi->face_locate: #{e}"
end
If we use this image as an example input:
We get the following result:
{
"ErrorDetails": null,
"Successful": true,
"Faces": [
{
"LeftX": 1503,
"TopY": 687,
"RightX": 1627,
"BottomY": 812
},
{
"LeftX": 1217,
"TopY": 711,
"RightX": 1321,
"BottomY": 814
},
{
"LeftX": 929,
"TopY": 745,
"RightX": 1033,
"BottomY": 849
},
{
"LeftX": 699,
"TopY": 699,
"RightX": 803,
"BottomY": 803
},
{
"LeftX": 1724,
"TopY": 632,
"RightX": 1848,
"BottomY": 756
},
{
"LeftX": 397,
"TopY": 577,
"RightX": 521,
"BottomY": 701
}
],
"FaceCount": 6
}
As you can see, we are told whether it was successful, the location of each face, and overall number of faces. Easy peasy.