I am currently working on a project where I need to identify and remove a specific rectangle from an image by replacing it with a solid color using ImageMagick (v7) via the command line interface. To achieve this, I need to obtain the exact coordinates of the rectangle in the image first.
Could you please guide me on how to use magick
commands in CLI to extract these coordinates?
Thank you!
Here is another way to do it in Imagemagick using connected components processing to find a rectangle with area greater than 7000 and aspect ratio of about 4.4. I process the image with some morphology to isolate your rectangle from nearby regions after thresholding and inverting (negating). Then I use connected components to find all regions that are greater than 7000 px in area and find the bounding boxes of each region. Then I save only the white region bounding boxes. Then I do a for loop over each bounding box and filter on aspect ratio between 4.2 and 4.6.
Input:
bboxArr=(`magick img.png \
-threshold 20% \
-negate \
-morphology open square:1 -morphology close square:1 \
-type bilevel \
-define connected-components:verbose=true \
-define connected-components:mean-color=true \
-define connected-components:exclude-header=true \
-define connected-components:area-threshold=7000 \
-connected-components 8 img_ccl.png | grep "gray(255)" | awk '{print $2}' | tr "x" "+"`)
num=${#bboxArr[*]}
echo $num
for ((i=0; i<num; i++)); do
bbox=${bboxArr[$i]}
ww=`echo $bbox | cut -d+ -f1`
hh=`echo $bbox | cut -d+ -f2`
xo=`echo $bbox | cut -d+ -f3`
yo=`echo $bbox | cut -d+ -f4`
aspect=`echo "scale=6; $ww/$hh" | bc`
if [[ $aspect > 4.2 ]] && [[ $aspect < 4.6 ]]; then
echo "width=$ww; height=$hh; top-left-corner=$xo,$yo"
fi
done
Processed image from connected components:
Results:
width=196; height=46; top-left-corner=602,591