Square pegs don’t fit in round holes, but what if you have power tools?
Digital images often don’t fit where we want them: advertisements, social networks, and printers all require that images be a specific aspect ratio (i.e., the ratio of the image’s width to height). Take Facebook ads for example: different aspect ratios are required depending on what kind of ad you wish to run. This is a large pain point for marketers: each piece of content must be manually cropped to fit the aspect ratio of the channel. Typically, images are either padded with white pixels (thus wasting valuable screen real estate) or arbitrarily cropped (possibly degrading the content).
But it doesn’t have to be this way! In this post, we present a technique that we use for intelligent cropping: a fully automatic method that preserves the image’s content. We’ve included some example code so you can explore on your own, and some real-world examples from Curalate’s products.
The following illustrates our approach:
- The input to the algorithm is an image and a desired aspect ratio.
- First, we use a variety of techniques to detect different types of content in the image. Each technique results in a number of content rectangles that are assigned a value score.
- Second, we select the optimal region of the image as that which contains the content rectangles with the higest cumulative score.
- Finally, we crop the input image to the optimal region.
The result is a cropped image of the desired aspect ratio fully containing the content in the image.
- Identifying Content in Images
- Optimal Cropping
- Result Gallery
- Uses in Curalate Products
To run these examples for yourself, you’ll need Python 2 with OpenCV, NumPy, and matplotlib installed. The images used for examples in this post may be downloaded here. This entire post is also available as a python notebook if you want to take it for a spin.
To start off, let’s load an image we’d like to use:
Let’s assume we’re creating a Facebook ad to drive traffic to our website. The
1200x628 for target aspect ratio of
The naive approach would just crop the center of the image:
Ugh. I wouldn’t click on that. Let’s do something intelligent!
Identifying Content in Images
Our first task is to detect different content in the image. Object detection is still an active area of research, though recent advances have started to make it feasible in many applications. Here we explore a few simple techniques that are built into OpenCV but you can use any detector you like.
If an image contains a face, it’s likely that the person is a key element in the image. Fortunately, face detection is a common task in computer vision:
The result is a numpy array of rectangles containing the faces:
Sometimes, we don’t know what we’re looking for in an image. Low-level image characteristics, however, often correspond to the interesting area of images. There are many common techniques for identifying interesting areas of an image, even ones that estimate visual saliency. Shi-Tomasi’s Good Features To Track is one technique commonly used to indicate interest points in an image. Detecting these interest points is also relatively simple using OpenCv:
Other times, we know a specific product is in an image and we want to make sure we don’t crop it out. We can achieve this by localizing an image of the product in our image of interest.
In our example, the product is:
We can locate the product in the image using instance retrieval techniques. First, we’ll estimate the transformation between the product and the target image:
The result is a set of correspondence points between the images:
We simply take the bounding box around the product’s location:
In summary, we have detected faces, interest points, and products in the image. Together, these form the full set of content regions:
Now that we have detected the content regions in the image, we’d like to
identify the best way to crop the image to a desired aspect ratio of
strategy is simple: find the area of the image with the desired aspect ratio
containing the highest sum of the content rectangle scores.
First, let’s assign a score to each content rectangle. For this example, we’ll just use the area of each rectangle.
Reducing to One Dimension
Now for the fun part: Depending on the input image and desired aspect ratio, the resulting crop will either have the same height as the input image and a reduced width, or the same width as the input image and a reduced height. The principal axis is the dimension of the input image that needs to be cropped. Let:
be the aspect ratio of the input image. If
alpha > desiredAspectRatio, then
the horizontal axis is the principal axis and the system crops the width of the
image. Similarly, if
alpha < desiredAspectRatio, then the vertical axis is the
principal axis and the system crops the height of the image.
Projecting the content rectangles onto the principal axis simplifies our goal: the optimal crop is simply the window along the principal axis containing the highest sum of content region scores. The length of this window is the size of the final crop along the principal axis.
Thus, the content rectangles are reduced from two dimensional rectangles to one dimensional regions.
Selecting the Optimal Crop
The optimal crop is the window of length
contentRegions’ scores sum to the largest possible value. We can use a sliding
window approach to quickly and efficiently find such a crop.
First, we’ll define the inflection points for the sliding window approach. Each inflection point is a location on the number line where the value of the current window can change. There are two inflection points for each content region: one that removes the content region’s score when the window passes the region’s starting location, and one that adds a content region’s score when the window encapsulates it.
Next, we’ll sort the inflection points by their locations on the number line, and ignore any outside the valid range:
To implement our sliding window algorithm, we need only accumulate the sum of the inflection points’ values at each location, and then take the maximum:
optimalInflectionPoint contains a starting location that has the most
value. In fact the range of pixels between that inflection point and the next
one all have that same value. We’ll take the middle of that range for our
Now that we know where the optimal crop begins on the principal axis, we can un- project it to get the final crop:
Awesome! Now we know where to crop the image! You can see below that the optimal crop indeed includes the product, the face, and a large number of the interest points:
Now that’s a good pic!
Disclaimer: The code above is meant as a demonstration. Optimization, handling of edge cases, and parameter tuning are left as an exercise for the reader 😉.
Below are some example results. The desired aspect ratio is listed below the input image.
Uses in Curalate Products
One great place we use intelligent cropping is when displaying our clients’ images. Below is a screenshot showing some product images before intelligent cropping, and then after. Notice how the models’ faces, the shoe, and the bag were all cropped using the naive method. After intelligent cropping, our thumbnails are much more useful representations of the original images.
|Before Intelligent Cropping||After Intelligent Cropping|