我将在此处放一个示例让您看到,但我不想发布大量图像。这是最简单的图像。它只有一个白色背景,但有些产品具有更复杂的背景。 我知道在该图像上做这样的事情可能行不通,因此我希望找出问题并以某种方式优雅地失败,而不是真正删除背景并通知我。
我正在使用Ruby on Rails 3和CarrierWave作为我的上传处理程序。
这是否可能,或者我只能去除白色背景?
以下是使用imagemagick的bash脚本来从图像中去除白色背景:
#!/bin/bash
# pass the image path, image name and threshold(used as a fuzz factor) to the bash script
IMGPATH=$1
IMGNAME=$2
THRESHOLD=$3
# start real
convert ${IMGPATH}${IMGNAME} \( +clone -fx 'p{0,0}' \) -compose Difference -composite -modulate 100,0 +matte ${IMGPATH}${IMGNAME}_difference.png
# remove the black, replace with transparency
convert ${IMGPATH}${IMGNAME}_difference.png -bordercolor white -border 1x1 -matte -fill none -fuzz 7% -draw 'matte 1,1 floodfill' -shave 1x1 ${IMGPATH}${IMGNAME}_removed_black.png
composite -compose Dst_Over -tile pattern:checkerboard ${IMGPATH}${IMGNAME}_removed_black.png ${IMGPATH}${IMGNAME}_removed_black_check.png
# create the matte
convert ${IMGPATH}${IMGNAME}_removed_black.png -channel matte -separate +matte ${IMGPATH}${IMGNAME}_matte.png
# negate the colors
convert ${IMGPATH}${IMGNAME}_matte.png -negate -blur 0x1 ${IMGPATH}${IMGNAME}_matte-negated.png
# eroding matte(to remove remaining white border pixels from clipped foreground)
convert ${IMGPATH}${IMGNAME}_matte.png -morphology Erode Diamond ${IMGPATH}${IMGNAME}_erode_matte.png
# you are going for: white interior, black exterior
composite -compose CopyOpacity ${IMGPATH}${IMGNAME}_erode_matte.png ${IMGPATH}${IMGNAME} ${IMGPATH}${IMGNAME}_finished.png
#remove white border pixels
convert ${IMGPATH}${IMGNAME}_finished.png -bordercolor white -border 1x1 -matte -fill none -fuzz ${THRESHOLD}% -draw 'matte 1,1 floodfill' -shave 1x1 ${IMGPATH}${IMGNAME}_final.png
#deleting extra files
rm ${IMGPATH}${IMGNAME}_difference.png
rm ${IMGPATH}${IMGNAME}_removed_black.png
rm ${IMGPATH}${IMGNAME}_removed_black_check.png
rm ${IMGPATH}${IMGNAME}_matte.png
rm ${IMGPATH}${IMGNAME}_matte-negated.png
rm ${IMGPATH}${IMGNAME}_finished.png
来源:将白色转换为透明
ImageMagick是最可能的解决方案(也许与Rails的mini-magick gem一起使用),但正如您所建议的那样,在某些情况下,您不太可能得到良好的结果。简单地将所有白色像素变为透明很可能会留下锯齿状的边缘,在非白色背景上会非常明显。但是有许多令人惊讶的选项可以给您提供类似于PhotoShop或其他软件中可能具有的控制,您可以创建一个掩模,找到在色调、颜色或类似物的某个容差范围内的形状轮廓,然后将所有匹配的像素更改为透明。我认为您还必须更改为PNG格式,因为我不认为JPEG支持alpha-transparency。
CarrierWave是这种处理的正确工具--您可以使用其“versions”功能存储原始文件,并尝试使用不同参数进行几次自动化尝试(这将保存不同的文件而不触及原始文件)。
http://www.imagemagick.org/Usage/masking/#two_background 可能会给您一个开始。
http://research.microsoft.com/apps/pubs/default.aspx?id=69117
OR
自然图像抠图的闭式解决方案
www.wisdom.weizmann.ac.il/~levina/papers/Matting-Levin-Lischinski-Weiss-CVPR06.pdf
后者提供了Matlab代码,供学术用途。但是这些都是严肃的数字计算器,可以在更大的文件上使用您的所有系统资源,正如从http://PixelFeather.com/download的试用版本pullmatt应用程序中可以确定的那样。顺便说一句,它比任何专有软件(包括Photoshop)都更好地解决了自然图像问题。