bashimage-processingimagemagickocrcrop

Crop the title (text) on the image to a certain border (by color)


How can I cut out a title from an image along the border of the lower red background (examples below)? I am planning a batch process, i.e. with hundreds of images with different titles (both with different widths and heights - only their location is constant). I'm using bash.

Example 1

Example 2

Desired Output


Solution

  • You have not said what you platform is nor what version of Imagemagick you are using. So I will assume Imagemagick 6 on a Unix-like system (Linux, Mac OSX or Windows 10/11 unix).

    This is the approach suggested by Mark Setchell in his comment above. (Make everything that is not red into black. Then trim to the red box bounds and find the top of the red box. Then chop off the top of the image down to the red box. Then add some black padding to the top of the image.)

    Here is the manual way in case you are on Windows. Sorry, I do not know how to deal with variables.

    Get the top of the red box, shave it off, then splice back a 20 pixel high black region on the top as pad.

    convert image1.png -fuzz 1% -fill black +opaque "rgb(237,28,36)" -format "%@" info:
    

    That returns the WxH+X+Y and we just want Y

    364x28+256+182

    Then chop of the top 182 and splice back 20 pixel tall blacktop the top of the image.

    convert image1.png +repage -gravity north -chop 0x182 -background black -splice 0x20 new_image1.png
    

    Here is the more automated way in Unix syntax.

    top=$(convert image1.png +repage -fuzz 1% -fill black +opaque "rgb(237,28,36)" -format "%@" info: | tr "x" "+" | cut -d+ -f4)
    convert image1.png -gravity north -chop 0x$top -background black -splice 0x20 new_image1.png
    

    Here is the result of either sets of commands above:

    enter image description here

    If on Imagemagick 7, just change convert to magick.