Search code examples
imagemagick

How to write the dimensions and position of each form?


I have the input image beloe for which I´d like to get the size and coordinates and write inside or at the top of each rectangle.

For now I was able to get the black rectangles data with this script

$ convert input.png -fill black +opaque '#FFFFFF' \
-define connected-components:verbose=true \
-define connected-components:area-threshold=5000 \
-define connected-components:mean-color=true \
-connected-components 4 output.png | awk '/srgb\(0,0,0\)/{print $2}'
450x338+25+1240
294x292+13+235
190x403+301+540
246x249+16+738
294x196+16+22
292x196+15+1013
163x267+325+22
248x176+14+540
163x207+321+310
159x200+320+1009

enter image description here

How to put inside or above of each rectangle (in input or output image) the corresponding WxH+X+Y text?

For example like this:

enter image description here


Solution

  • So based upon your comment, what you want to do in Imagemagick is the following with the input on the desktop. Note that you just need the X and Y offsets from the bbox as the argument to +X+Y in -annotate.

    Input:

    enter image description here

    cd
    cd desktop
    bboxArr=(`convert images.jpg \
    -fuzz 5% -fill none -draw "color 0,0 floodfill" \
    -channel rgba -fill white +opaque none -fill black +opaque white \
    -type bilevel \
    -define connected-components:verbose=true \
    -define connected-components:area-threshold=5000 \
    -define connected-components:mean-color=true \
    -connected-components 8 cleaned.png | grep "gray(255)" | awk '{print $2}'`)
    num=${#bboxArr[*]}
    echo $num
    convert images.jpg tmp.png
    for ((i=0; i<num; i++)); do
    bbox=${bboxArr[$i]}
    echo $bbox
    ww=`echo $bbox | tr "x" "+" | cut -d+ -f1`
    hh=`echo $bbox | tr "x" "+" | cut -d+ -f2`
    xo=`echo $bbox | tr "x" "+" | cut -d+ -f3`
    yo=`echo $bbox | tr "x" "+" | cut -d+ -f4`
    xo=$((xo+10))
    yo=$((yo+10))
    convert tmp.png \
    -gravity northwest -pointsize 14 -font arial-bold -fill white \
    -undercolor black -annotate +${xo}+${yo} "$bbox" tmp.png
    done
    convert tmp.png images_labeled.jpg
    rm -f cleaned.png tmp.png
    

    enter image description here