Remove White Background from an Image and Make It Transparent

后端 未结 9 972
一向
一向 2020-11-29 16:01

We\'re trying to do the following in Mathematica - RMagick remove white background from image and make it transparent.

But with actual photos it ends up looking lous

9条回答
  •  萌比男神i
    2020-11-29 16:27

    Perhaps, depending on the edge quality you need:

    img = Import@"http://i.stack.imgur.com/k7E1F.png";
    mask = ChanVeseBinarize[img, TargetColor -> {1., 1., 1.}, "LengthPenalty" -> 10]
    mask1 = Blur[Erosion[ColorNegate[mask], 2], 5]
    Rasterize[SetAlphaChannel[img, mask1], Background -> None]
    

    enter image description here

    Edit

    Stealing a bit from @Szabolcs

    img2 = Import@"http://i.stack.imgur.com/k7E1F.png";
    (*key point:scale up image to smooth the edges*)
    img = ImageResize[img2, 4 ImageDimensions[img2]];
    mask = ChanVeseBinarize[img, TargetColor -> {1., 1., 1.}, "LengthPenalty" -> 10];
    mask1 = Blur[Erosion[ColorNegate[mask], 8], 10];
    f[col_] := Rasterize[SetAlphaChannel[img, mask1], Background -> col, 
                         ImageSize -> ImageDimensions@img2]
    GraphicsGrid[{{f@Red, f@Blue, f@Green}}]
    

    Click to enlarge

    Edit 2

    Just to get an idea of the extent of the halo and background imperfections in the image:

    img = Import@"http://i.stack.imgur.com/k7E1F.png";
    Join[{img}, MapThread[Binarize, {ColorSeparate[img, "HSB"], {.01, .01, .99}}]]
    

    enter image description here

    ColorNegate@ImageAdd[EntropyFilter[img, 1] // ImageAdjust, ColorNegate@img]
    

    enter image description here

提交回复
热议问题