Reputation: 155
I have an image:
and I want to crop this image and extract sub images by horizontal black(gray) line and got smth like this (list of sub images):
and so on...
How can I do it with ImageMagick? Thanks for help.
Upvotes: 0
Views: 262
Reputation: 53081
Here is one way to do that in ImageMagick in Unix syntax and bash scripting. Threshold the image.
Add a black border all around. Then use connected components processing to find all the large white rectangles and their bounding boxes. Put those in an array. Then sort the array by Y value (top of bounding boxes). Then loop over each bounding box and crop the input image.
Input:
bboxArr=(`convert math.png -threshold 75% -bordercolor black -border 1 -type bilevel \
-define connected-components:exclude-header=true \
-define connected-components:area-threshold=100 \
-define connected-components:mean-color=true \
-define connected-components:verbose=true \
-connected-components 8 null: | grep "gray(255)" | awk '{print $2}'`)
num="${#bboxArr[*]}"
sortedArr=(`echo ${bboxArr[*]} | tr " " "\n" | sort -n -t "+" -n -k3,3 | tr "\n" " "`)
for ((i=0; i<num; i++)); do
cropval=${sortedArr[$i]}
convert math.png -crop $cropval +repage math_$i.png
done
Output (showing first 4 out of 11):
ImageMagick automatically sorts them by largest area first. So I had to sort them by Y.
Upvotes: 2