Crop image using Opencv in python

In this post we will discuss how to crop an image in python. Opencv convert images to numpy array. That is the trick. You just have to select the locaions you want like below.

img = cv2.imread(file_path)
crop_img = img[0:400, 0:300]

If you read your image from file path and save it to img variable. Then you can save the 400*300 pixels of img into crop_image. 0:400 means from zero pixel to 400 pixel. you can run the below code in colab to practice more.

from google.colab.patches import cv2_imshow
import cv2
file = "/content/YRkw2o9L0XmYHICE467aUSE1Ciy2rdGvkgtc2lUG.png"
img = cv2.imread(file)
crop_img = img[0:400, 0:300] # Crop from {x, y, w, h } => {0, 0, 300, 400}
Originalimage befor applying crop algorithm
Original image
Cropped image after applying crop algorithm

More information

If you are new in opencv with python we recommend you to take a look here.