How to Draw a Rectangle Over an Image with ImageMagick?

This article provides a quick overview and step-by-step guide on how to draw a rectangle over an image using the ImageMagick convert command. You will learn the basic syntax, how to define coordinates, and how to customize the rectangle’s color, border thickness, and transparency. Whether you are using ImageMagick v6 or the newer v7 (magick command), these examples will help you easily annotate and modify your images from the command line.

The Basic Command Syntax

To draw a shape on an image, ImageMagick uses the -draw operator followed by the shape type and its coordinates. For a rectangle, you need to specify the top-left corner and the bottom-right corner coordinates in pixels $(x_0, y_0)$ and $(x_1, y_1)$.

Here is the standard format for the command:

convert input.jpg -draw "rectangle x0,y0 x1,y1" output.jpg

Step-by-Step Examples

1. Drawing a Simple Solid Rectangle

If you want to draw a solid red rectangle starting at pixel coordinates (50, 50) and ending at (250, 150), you must define the fill color before the draw command:

convert input.jpg -fill red -draw "rectangle 50,50 250,150" output.jpg

2. Drawing a Transparent Rectangle with a Border

To create a bounding box (like those used in object detection) where the inside is hollow and only the border is visible, set the -fill color to none and define a -stroke color and -strokewidth.

convert input.jpg -fill none -stroke blue -strokewidth 3 -draw "rectangle 100,100 400,300" output.jpg

3. Drawing a Semi-Transparent Rectangle

If you want to highlight an area with a tinted, see-through background, you can use RGBA color values to define the opacity of the fill color.

convert input.jpg -fill "rgba(0, 255, 0, 0.4)" -draw "rectangle 30,30 200,200" output.jpg

In this example, rgba(0, 255, 0, 0.4) creates a green fill with a 40% opacity level, allowing the underlying image to show through.

A Note on ImageMagick Versions

If you are using ImageMagick v7 or newer, the convert command has been replaced by the unified magick command. The syntax remains exactly the same, but you change the initial keyword:

magick input.jpg -fill red -draw "rectangle 50,50 250,150" output.jpg