在带有 Unix 脚本的 ImageMagick 6 中,一种可能的方法是执行以下操作:
Trim the image to remove most of the black on the sides
Scale the image down to 1 row, then scale up to 50 rows just for visualization
Threshold the scaled image so that you get the black region down the spine as the largest black region
Do connected components process to find the x coordinate of the largest black region
Crop the image according to the results from the connected components
输入:
convert img.jpg -fuzz 25% -trim +repage img_trim.png
convert img_trim.png -scale x1! -scale x50! -threshold 80% img_trim_x1.png
centx=$(convert img_trim_x1.png -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:verbose=true \
-connected-components 4 null: | \
grep "gray(0)" | head -n 1 | awk '{print $3}' | cut -d, -f1)
convert img_trim.png -crop ${centx}x+0+0 img_result.jpg
来自连接组件的数据具有以下标题和结构:
Objects (id: bounding-box centroid area mean-color):
所以 head -n 1 得到第一个黑色,即最大的灰色(0)区域(从大到小排序)。 awk 打印第三个条目,centroid,并且 cut 得到 x 分量。
如果使用 ImageMagick 7,则将 convert 更改为 magick
如果要排除中间的活页夹,则使用连接组件列表中边界框的 x 偏移量:
convert img_trim.png -scale x1! -scale x50! -threshold 80% img_trim_x1.png
leftcenterx=$(convert img_trim_x1.png -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:verbose=true \
-connected-components 4 null: | \
grep "gray(0)" | head -n 1 | awk '{print $2}' | cut -d+ -f2 | cut -d+ -f1)
convert img_trim.png -crop ${leftcenterx}x+0+0 img_result2.jpg
如果你只想要两个页面,那么我们可以找到白色区域,即 gray(255) 并根据边界框的宽度和 x 偏移量裁剪它们。
convert img.jpg -fuzz 25% -trim +repage img_trim.png
convert img_trim.png -scale x1! -scale x50! -threshold 80% img_trim_x1.png
OLDIFS=$IFS
IFS=$'\n'
bboxArr=(`convert img_trim_x1.png -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:area-threshold=100 \
-define connected-components:verbose=true \
-connected-components 4 null: | \
grep "gray(255)" | awk '{print $2}'`)
IFS=$OLDIFS
num=${#bboxArr[*]}
for ((i=0; i<num; i++)); do
WW=`echo ${bboxArr[$i]} | cut -dx -f1`
Xoff=`echo ${bboxArr[$i]} | cut -d+ -f2`
convert img_trim.png -crop ${WW}x+${Xoff}+0 img_result3_$i.jpg
done