Python OpenCV Example | Crop an Image

In this python opencv example code, we will show you how to crop an image in python opencv. It is very easy.

Step 1. import python opencv library

import cv2

Step 2: open an image using python opencv

We will use cv2.imread() to open an image in opencv.

For example:

img = cv2.imread("bird2.jpg")

Step 3: crop the image by an area

img is an numpy ndarray, we can select some data to save.

For example:

x = 100
y = 100
h = 300
w = 300
cropped_image = img[y:y+h,x:x+w]

Step 4: show and save cropped image

cv2.imshow("Cropped Image",cropped_image)

cv2.imwrite("Cropped Image.jpg", cropped_image)

Finally, we will see an image below:

OpenCV Example | Crop an Image