Skip to content

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 array slicing to extract the region you want to crop. Finally, 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:

Crop an image in OpenCV using Python and cv2 module

python
import cv2

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

# Check if the image was loaded successfully
if image is None:
    print("Error: Could not load image.")
else:
    # Define the crop coordinates (top-left and bottom-right)
    x1, y1 = 50, 50
    x2, y2 = 200, 200

    # Crop the image using array slicing
    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 region you want to crop, respectively. You can adjust these values to specify the area you want to extract.

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).

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.