Evangelism/Firefox3.5/35Days/Articles/CAIR

From MozillaWiki
Jump to: navigation, search

Firefox for Content Aware Image Resizing interactive demo

Nasa-cair.jpg

Content Aware Image Resizing is a way to retarget an image size without modifying its content ratio, in other words : non-linear image resizing. The algorithm has been worked out by Shai Avidan and Ariel Shamir and published in 2007 (“Seam Carving for Content-Aware Image Resizing”)

Since then, and after a big buzz, several excellent Open Source implementations have been released. For example, there is a plugin for The Gimp and CAIR a standalone application, all in C++.

What about Firefox ? Does it require a plugin ? Answer : No, it is now opened to the JavaScript hackers.

Nowadays time has changed. Who could have imagined, few years ago, advanced pixel manipulation straight in the browser ?

Since version 1.5, Firefox offers bitmap manipulation through the Canvas API. Version 3.5 introduced not only the fastest Firefox JavaScript engine ever, but also a new Canvas method – createImageData – providing a much more powerful environment.

Cair-steps.jpg

For this demo, a sub part of the Content Aware Image Resizing algorithm has been implemented. The width of the image can be reduced interactively without modifying its height. This implementation uses seam carving to resize the image, subtracting the less visible vertical lines. It is a four steps iterative algorithm. One iteration is one pixel width resize. First an Image is loaded into the Canvas context and then the iteration starts :

A grayscale version of the image has to be calculated

The edges of the image (Sobel convolution is used in our case) and at the same time its energy matrix are computed

The seam of least energy (1 pixel vertical line from the bottom to the top of the energy matrix) is detected

Then the pixel of the detected seam is removed from the original image and the result is re-injected as a source image to step 1

Each previous steps requires to store a whole matrix of data of the source image size. While these matrix are not all images but actually artifacts of the algorithm, storing them in an ImageData object is more convenient than using simple Arrays. This is why createImageData method of the Canvas context is used. One of the benefits of this process is to allow showing the intermediate computations made under the wood.

The author of the demo, Stéphane Roucheray is a member of the PIMS team. The demo has been first explained on the Pims World Labs.