Having product images increases sales, but post-processing is a chore which involves clicking around in Photoshop/Gimp to isolate the product and changing levels such that the background becomes pure white. As I've been selling Japanese candy online, taking shots like these has become a repeating task.
You could pay someone to do that, but wouldn't it be nice if it could happen automatically? Today I challenged myself to see if I could manage it. After a few hours of hacking it works quite well, actually the above image is output from the script.
One side effect is that because touching up the product picture is now free, you could even do it hundreds of times just for fun. For example for no particular reason, you could take a hundred pictures at different angles and then isolate the product on each frame to get a nice animation. Not that anyone would be crazy enough to do such a thing.
Tech used is just Python with the Image and ImageFilter modules. To put together the gif animation I used ffmpeg. How to do the isolating part then? The solution actually turns out to be very straightforward, just finding adjacent pixels based on color. Read on if you care for the details.
Convert the image to black and white such that the background becomes solid color that surrounds the object. Now the thing we want to isolate is the blob in the middle. If we had an outline for that, then that can be used to pick out the object from the original photo.
Find one pixel which is known to belong to the object that we want to isolate. I pick the first darkish pixel I can find near the center of the image. Then starting from that pixel, recursively explore neighboring pixels. If you get unlucky the algorithm will fail here if it happens to start from an unconnected island, so in reality I had to use multiple start points. Below is what you get after counting all neighboring pixels to be part of the object. Note we have now isolated it from the background, but there's still gaps inside.