How to crop an image to the face in Ruby

Today we will use our image recognition API to quickly crop images to the person’s face. The first thing to do is add this snippet to your Gemfile so that we can access our API client.

gem 'cloudmersive-image-recognition-api-client', '~> 1.3.2'

Now you have the option of calling face_crop_first for a square image or face_crop_first_round for a round crop. The below example uses face_crop_first

# 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'
api_instance = CloudmersiveImageRecognitionApiClient::FaceApi.newimage_file ="/path/to/file") # File | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.begin
#Crop image to face (square)
result = api_instance.face_crop_first(image_file)
p result
rescue CloudmersiveImageRecognitionApiClient::ApiError => e
puts "Exception when calling FaceApi->face_crop_first: #{e}"

Here is an example image:

Image for post

And the resulting cropped image:

Image for post

Super easy right?

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