Explain Codes LogoExplain Codes Logo

How to draw a rectangle on image

python
image-processing
matplotlib
pillow
Anton ShumikhinbyAnton Shumikhin·Dec 31, 2024
TLDR

OpenCV is a great choice for swiftly adding a rectangle to an image in Python. This is achieved using cv2.rectangle(). This function operates directly on your image array. You simply need to specify your image, the rectangle's top-left (x1, y1) and bottom-right (x2, y2) corners, the color (B, G, R) as a tuple, and line thickness. Look at this economized example:

import cv2 image = cv2.imread('your_image.jpg') cv2.rectangle(image, (50, 50), (200, 200), (255, 0, 0), 2) # Drawing red box, not you cv2.imshow('Result', image) # Reveal the masterpiece cv2.waitKey(0) cv2.destroyAllWindows()

Adjust 'your_image.jpg' to your image path. Tweak the tuple (50, 50) for the top-left and (200, 200) for the bottom-right to match your desired rectangle coordinates. In this script, the rectangle will be blue and with a thickness of 2 pixels.

Advanced uses and alternative methods

Using matplotlib for gentle image handling

Matplotlib combined with Pillow (PIL) offers a non-destructive way of working with images. Ideal when you're updating a frequently changing or complex diagram, or to keep the original image intact while experimenting with overlays.

Here's how to build a rectangle footage onto an image:

from matplotlib import pyplot as plt from matplotlib.patches import Rectangle from PIL import Image # Read in the image img = Image.open('your_image.jpg') # Present the image plt.imshow(img) # Rectangle patchwork rect = Rectangle((50, 50), 150, 150, linewidth=2, edgecolor='r', facecolor='none') # Get the rectangle on the image pitch plt.gca().add_patch(rect) # Keep it natural with equal aspect plt.axis('equal') # Pull back the curtain plt.show()

Alternate tools: PIL and ImageDraw

When OpenCV and matplotlib aren't quite the right fit, the Pillow library (a.k.a. PIL) provides the ImageDraw module for direct drawings.

from PIL import Image, ImageDraw # Open an image in reading mode with Image.open('your_image.jpg') as img: draw = ImageDraw.Draw(img) # Here be top-left and bottom-right corners draw.rectangle(((50, 50), (200, 200)), outline='red', width=2) # This thin red line img.show()

Drawing several rectangles and saving the masterpiece

With multiple rectangles in play, or a need to preserve your rendering, optimized handling is the way to go:

import cv2 # Collection of top-left and bottom-right corners for all rectangles coordinates = [((50, 50), (100, 100)), ((150, 150), (200, 200))] image = cv2.imread('your_image.jpg') # Drawing every rectangle in the coordinates list for rect in coordinates: cv2.rectangle(image, rect[0], rect[1], (0, 255, 0), 2) # Instant grass. Just add water. # Save the scenery with all the rectangular revelations cv2.imwrite('multiple_rectangles.jpg', image)

The devil is in the detail

Small details make a big difference

Remember, padawan, every little detail counts in image drawing. Check your image path and use cv2.imshow() or plt.imshow() to confirm it's all good before adding rectangles.

Custom styles and coloring

Matplotlib and Pillow let you give your rectangles a personal touch with parameters such as edgecolor, facecolor, and width .

Consistent image proportions

Keep the proportions natural by keeping the aspect ratio intact. In matplotlib, setting the aspect parameter to 'equal' makes sure your rectangles doesn't get stretched or squished when scaling the image.

Troubleshooting and best practices

Correct rectangle vertex order is key

Ensure the top-left coordinates are the starting point and are lesser than the bottom-right ones in the x and y dimensions.

Direct drawing using matplotlib 'plot'

With matplotlib, you can use plot for directly sketching rectangles into your plot. Quick and easy when rectangles are a part of the visualization itself.

Performance optimizations for large images

Consider using optimized algorithms or graphics hardware acceleration to tackle large images or boost performance.

Advanced image processing with PIL and OpenCV

Hunt down specialized tutorials or Q&A threads for complex image handling tasks using your chosen library.