如何从白色背景的JPG中提取照片?

时间:2018-04-05 23:35:56

标签: image image-processing imagemagick command-line-interface

我有一个JPG文件,其中包含多张白色背景照片。

我正在寻找一种CLI工具,它可以将源JPG中的照片(不提供坐标)提取到单独的JPG文件中,从而保持质量和照片分辨率。

从某些研究中我怀疑ImageMagick可以实现这一点,但不确定正确的CLI命令。

如果有用,我使用的是OSX 10.13.2并安装了ImageMagick 7.0.7-28。

Image extraction example

1 个答案:

答案 0 :(得分:0)

以下是使用Imagemagick在Unix中执行此操作的两种方法。我只是从你的图表中裁剪出你的基本图像,因为我不确定它是你图像的一部分。如果它是图像的一部分,那么你必须首先使用-trim来修剪它。

输入:

enter image description here

第一个是我的脚本,multicrop2:
(-f 10是提取背景的模糊因子)
(-u 3表示没有尝试取消旋转结果)

multicrop2 -f 10 -u 3 image.jpg resulta.jpg

Processing Image 0
Initial Crop Box: 113x84+81+89

Processing Image 1
Initial Crop Box: 113x67+144+10

Processing Image 2
Initial Crop Box: 113x66+10+11

enter image description here enter image description here enter image description here

第二个是使用Imagemagick -connected-componets(这是我在我的脚本中使用的)

这是做什么的:

1) fuzzy flood fill the background to transparent (since jpg is loss and does not preserve a uniform background.
2) change the color under the transparent to white and remove the transparency
3) change anything not white to black
4) apply -connected-components to throw out areas smaller than 400 pixel area and extract each bounding box and color
5) if the color is gray(0), i.e. black, then crop the original image to the bounding box and save to disk


OLDIFS=$IFS
IFS=$'\n'
arr=(`convert image.jpg -fuzz 10% -fill none -draw "matte 0,0 floodfill" \
-background white -alpha background -alpha off \
-fill black +opaque white -type bilevel \
-define connected-components:verbose=true \
-define connected-components:mean-color=true \
-define connected-components:area-threshold=400 \
-connected-components 4 null: | tail -n +2 | sed 's/^[ ]*//'`)
IFS=$OLDIFS
num=${#arr[*]}
j=0
for ((i=0; i<num; i++)); do
bbox=`echo "${arr[$i]}" | cut -d\  -f2`
color=`echo "${arr[$i]}" | cut -d\  -f5`
if [ "$color" = "gray(0)" ]; then
convert image.jpg -crop $bbox +repage resultb_$j.jpg
j=$((j+1))
fi
done


enter image description here enter image description here enter image description here

编辑:添加实际图像的处理

输入:

enter image description here

首先要注意的是,您的实际两幅图像位于右侧,但那里有一条黑色边缘。还有一个在顶部。黑色边缘连接两个图像,因此无法通过multicrop2脚本轻松分离。因此,您需要通过足够的像素去除右侧以移除该边缘。顶部还有边缘,如果你愿意,你可以剃掉它。如果这样做,您可以减少-d参数。 -d参数需要小于要提取的最小图像的区域,并且大于任何其他次要噪声或区域顶部的条带。因此,我从右侧剪切20像素,然后使用具有非常大的值的multicrop2 -d。我选择了-f为8的值,由于非常数背景,它似乎处于相当窄的范围内。您可以添加-m save以查看脚本创建的掩码,以查看两个映像之间的良好分离。我在-c 20,20处理处理以避免图像顶部的黑色边框,以便脚本可以很好地测量填充步骤的背景颜色。

convert test.jpeg -gravity east -chop 20x0 tmp.png
multicrop2 -c 20,20 -f 8 -d 100000 tmp.png result.jpg

Processing Image 0
Initial Crop Box: 2319x1627+968+2153

Processing Image 1
Initial Crop Box: 2293x1611+994+436

enter image description here

enter image description here