Java – Make an image’s background transparent or white programmatically

imageimage manipulationimage processingjava

If one is creating an application in which one would like to make the "background" of an image transparent or white, is there a way to do this?

For example :

In the image, http://upload.wikimedia.org/wikipedia/commons/b/b9/Bronze_Statuette_of_a_Veiled_and_Masked_Dancer_1.jpg , I would like to transform the image programmatically, such that only the statue remains, and the background (i.e. the rest of the image) is all white, or transparent.

Also, the user might point out to the part of the image that should "remain", and the rest should be all white or transparent.

How can this be done? Also, if there is a suitable java library or piece of code, it would be helpful.

Regards

Best Answer

What you're asking for is programmatic segmentation of foreground and background. As this is an active research area, you're unlikely to find any ready-mode source code that works out of the box (especially in Java).

If you have the time, look up image segmentation and browse through relevant papers on Google Scholar. You will see that in the general case, it's not an easy problem for a computer to solve. In specific cases, you can try to take advantage of certain conditions. In the image you've specified, the background is really blurry, so the edges of the figure really stand out well. Edge detection with the Canny operator gives you this:

enter image description here

It's not perfect, but it's a start. Using the edge information, you can locate major external contours and extract the dancer figure.