How to Crop Image with OpenCV Python

Using OpenCV, it is straightforward to capture an image in Python and define an arbitrary part of the image by slicing, First OpenCV reads the image using the cv2.imread() function. Next You perform the cropping operation by defining the region of interest (ROI) using array slicing in the format [startY:endY, startX:endX], where startY and endY define the vertical range, and startX and endX define the horizontal range of pixels. Afterward, you store the cropped portion in another variable. Then You can use cv2.imshow() to display the cropped image, which opens a window to display the results. Furthermore To ensure the program waits until it detects a key press, you use cv2.waitKey(0) and finally close the windows with cv2.destroyAllWindows(). Overall This method enables precise cropping by adjusting the coordinates based on the pixel resolution of the original image. Therefore you commonly use it for image preprocessing in computer vision applications.

Crop Image with OpenCV Python

Let’s learn this with simple example

First is to Import the OpenCV library and Load the image, Replace ‘example.jpg’ with the path to your image file, `cv2.imread()` function reads the image from the specified file.

import cv2  
image = cv2.imread('example.jpg')

In the second step we have to define the cropping coordinates. Slicing is used to crop the image. Here, the region starts at Y=50 and ends at Y=200, # and starts at X=100 and ends at X=300. Adjust these values as needed for your image.

cropped_image = image[50:200, 100:300]

In the third step we have to display the cropped image, the`cv2.imshow()` function opens a window to display the cropped image.

cv2.imshow('Cropped Image', cropped_image)

Fourth step we will confirm the dimensions of the cropped image with the following command.

print("Cropped Image Dimensions:", cropped_image.shape)

In the fifth step we have to close the image window with the help of `cv2.destroyAllWindows()` function. This function closes all OpenCV image display windows.

cv2.destroyAllWindows()
Output:
The code provided doesn't directly generate output in text form but displays a cropped section of the image in a pop-up window using OpenCV

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top