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

How to extract photos from JPG with white background?

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

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

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

如果有用,我在 OSX 10.13.2 上并安装了 ImageMagick 7.0.7-28。

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

trim 关闭它

输入:

首先是我的脚本,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

第二个是使用 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


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

输入:

首先要注意的是,您实际的两张图片是在右侧,但那里有一条黑边。还有一个在顶部。黑色边缘连接了两个图像,因此它们不能轻易地被 multicrop2 脚本分开。因此,您需要将右侧刮掉足够多的像素以移除该边缘。顶部也有边缘,您可以根据需要将其剃掉。如果这样做,您可以减少 -d​​ 参数。 -d 参数需要小于要提取的最小图像的区域,并且大于任何其他次要噪声或区域顶部的条纹。所以我从右侧剪掉 20 个像素,然后使用 multicrop2 并为 -d 设置一个非常大的值。我为 -f 选择了一个值为 8 的值,由于 non-constant 背景,它似乎在一个相当窄的范围内。您可以添加 -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