How to crop an image in OpenCV using Python

You can use the cv2.imread() function to read an image into memory, and then use the cv2.rectangle() function to draw a rectangle around the region you want to crop. Then you can use the cv2.imwrite() function to save the cropped image to a file.

Here's an example of how you could do this:

import cv2

# Read the image into memory
image = cv2.imread("my_image.jpg")

# Draw a rectangle around the region you want to crop
cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)

# Crop the image to the rectangle
cropped_image = image[y1:y2, x1:x2]

# Save the cropped image to a file
cv2.imwrite("cropped_image.jpg", cropped_image)

In this example, (x1, y1) and (x2, y2) are the coordinates of the top-left and bottom-right corners of the rectangle, respectively. You can adjust these values to specify the region you want to crop.

Watch a course Python - The Practical Guide

Note that the image[y1:y2, x1:x2] syntax is used to crop the image in the y direction first, and then in the x direction. This is because images are represented as 2D arrays in OpenCV, with the first dimension corresponding to the y axis (row) and the second dimension corresponding to the x axis (column).