Removing a Solid Color Background from an image

I have an image with a solid color background. I don’t know what color it will be in advance. I want to take this background and use it as a mask. I’ve tried the image segmentation library, but I don’t know how to make it work in this case and it also feels overkill.

I don’t know the specific code to do this, but the way I’d approach it is

  1. Use Images.jl to read the image into an array
  2. Iterate over the pixels on the edges of the image and find the most common color.
  3. replace! the most common color with whatever value PNG uses to represent transparency (you’d have to look that up).

If the subject of the image has any parts that match the background color, they will be masked by this approach. So you could try starting at the edge and only replacing background color for the region that is contiguous with the edge.

But with that approach, you’d miss any background color that is in a hole of the subject (like a picture of a donut would have background color in the middle)

Hard to say what the best strategy is without more specifics on the images your working with.