How to Crop an Image in OpenCV Python

You can crop an image in OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.

How to crop an image in OpenCV Python
How to crop an image in OpenCV Python

Step 1

Open the Spyder IDE (integrated development environment).

Step 2

Import the OpenCV library. If OpenCV is not installed in your system then first install it using This Method.

import cv2 
#cv2 is used for OpenCV library

Step 3

Now read the image from the location. In my case “F:\\AiHints” is the location and “top30.jpg” is the name of the image. Change it according to your image location and name.

image = cv2.imread("F:\\AiHints\\top30.jpg")
#imread is use to read an image from a location
top30

Step 4

In this step, we will crop the image by giving the four values (x, y, h, and w).

x=50
y=50
h=150
w=300
crop = image[y:y+h, x:x+w]

Step 5

Now, I will save the cropped image with a new name “CropImage.jpg”.

cv2.imwrite('F:\\AiHints\\CropImage.jpg',crop)
CropImage

Step 6

waitKey() open the image for a specific time in milliseconds until you press any key. “destroyAllWindows()” will destroy all the windows that we created.

cv2.waitKey()
cv2.destroyAllWindows()

Leave a Comment

Your email address will not be published.