我们尝试在Mathematica中执行以下操作:
RMagick从图像中删除白色背景并使其透明
但实际照片看起来很糟糕(就像图像周围有光环).
这是我们到目前为止所尝试的:
unground0[img_] := With[{mask = ChanVeseBinarize[img, TargetColor->{1.,1.,1.}]},
Rasterize[SetAlphaChannel[img, ImageApply[1-#&, mask]], Background->None]]]
Run Code Online (Sandbox Code Playgroud)
这是一个例子.
原始图片:

没有背景的白色背景替换图像(或者,为了演示目的,粉红色背景):

什么想法摆脱光环?调整像LevelPenalty这样的东西,我只能以丢失一些图像为代价来消除光环.
编辑:所以我可以比较赏金的解决方案,请像上面那样构建你的解决方案,即一个名为unground的自包含函数,它可以获取图像并返回具有透明背景的图像.非常感谢大家!
我没有将以下PHP/ImageMagick代码转换为Ruby RMagick(以使其对未来用户更易于管理并了解它的真正用途):
$output = array();
$returnValue = 0;
$pngFiles = $myDir->find("/.png$/i");
foreach($pngFiles as $pngFile) {
$cmd = 'convert '.$pngFile->path.' -resize 1x1 -alpha on -channel o -format "%[fx:u.a]" info:'
exec($cmd, $output, $returnValue);
if($output[0] != 1) {
logMessage("PNG file contains some alpha transparency and will not be modified");
}
}
Run Code Online (Sandbox Code Playgroud)
到现在为止,我以为我或多或少地理解了convert-command正在做什么,但将其翻译成RMagick让我重新思考.
例如:为什么$output[0] != 1 有时候 true在PNG格式$myDir,但RMagick的Image.alpha?是始终 true对PNG图像的$myDir?我错过了什么吗?
我认为,如果有人能够向我解释转换命令正在做什么(包括表达式%[fx:u.a]),那么让我回到正轨的最佳方法就是.
更新:与此同时,我编写了我需要此信息的脚本.您可以在Github上查看它是否对您有任何帮助.
可能重复:
使用以下代码将Ruby转换为PHP代码
我找到了一个非常有用的Ruby代码来删除图像白色背景颜色.
请参阅下面的参考代码: 从图像中删除白色背景并使其透明
我试图将代码翻译成php.但是我得到了一个不想要的结果.这是我第一次在这里发帖提问,有人可以给我一些指导并原谅我可怜的英语.
function setTransparency($new_image,$image_source)
{
$transparencyIndex = imagecolortransparent($image_source);
$transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);
if ($transparencyIndex >= 0) {
$transparencyColor = imagecolorsforindex($image_source, $transparencyIndex);
}
$transparencyIndex = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
imagefill($new_image, 0, 0, $transparencyIndex);
imagecolortransparent($new_image, $transparencyIndex);
}
//create image from the source link
$image = imagecreatefrompng('http://i.stack.imgur.com/k7E1F.png');
//create image mask layer
$new_image = ImageCreateTruecolor(imagesx($image), imagesy($image));
//remove white background
setTransparency($new_image,$image);
//merge mask with original image source
ImageCopyMerge($new_image, $image, 0, 0, 0, 0, imagesx($image), …Run Code Online (Sandbox Code Playgroud)