从图像中删除白色背景并使其透明 [英] Remove white background from an image and make it transparent

查看:636
本文介绍了从图像中删除白色背景并使其透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正尝试在Mathematica中执行以下操作:

  img2 =导入@http://i.stack.imgur.com/k7E1F.png; 
(*关键点:放大图像以平滑边缘*)
img = ImageResize [img2,4 ImageDimensions [img2]];
mask = ChanVeseBinarize [img,TargetColor - > {1.,1.,1。},LengthPenalty - > 10];
mask1 =模糊[侵蚀[ColorNegate [mask],8],10];
f [col_]:= Rasterize [SetAlphaChannel [img,mask1],背景 - > col,
ImageSize - > ImageDimensions @ img2]
GraphicsGrid [{{f @ Red,f @ Blue,f @ Green}}]


点击放大



编辑2



只是为了了解图像中 halo 的范围和背景缺陷:

  img =导入@http://i.stack.imgur.com/k7E1F.png; 
加入[{img},MapThread [Binarize,{ColorSeparate [img,HSB],{。01,.01,.99}}]]

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


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 lousy (like having a halo around the image).

Here's what we've tried so far:

unground0[img_] := With[{mask = ChanVeseBinarize[img, TargetColor->{1.,1.,1.}]},
  Rasterize[SetAlphaChannel[img, ImageApply[1-#&, mask]], Background->None]]]

Here's an example of what that does.

Original image:

Image with the white background replaced with no background (or, for demonstration purposes here, a pink background):

Any ideas for getting rid of that halo? Tweaking things like LevelPenalty, I can only get the halo to go away at the expense of losing some of the image.

EDIT: So I can compare solutions for the bounty, please structure your solution like above, namely a self-contained function named unground-something that takes an image and returns an image with transparent background. Thanks so much, everyone!

解决方案

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]

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}}]]

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

这篇关于从图像中删除白色背景并使其透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆