Crop an image with OpenCV in Python

Python OpenCV – Crop Image

To crop an image using specific region of interest with OpenCV in Python, you can use Python slicing technique on the source image array.

In this tutorial, you will learn how to use slicing technique to crop an image, with examples.

Syntax of slicing an image

If x, y represent the top-left corner of the Region Of Interest (ROI), and w, h represent the width and heigh of the ROI, then the syntax to slice the ROI from the source image img is

img[y:y+h, x:x+w]

Steps to crop an image

  1. Read an image into an array using cv2.imread() function.
  2. Define an ROI.
  3. Crop the image (2D array) using ROI with slicing technique.
  4. Save the cropped image using cv2.imwrite() function.

Examples

In the following examples, we take an image, and crop it.

The input image test_image_house.jpg we are taking is shown below.

1. Crop the image using ROI of 150, 100, 200, 300

In the following program, we take an image test_image_house.jpg, crop this image using an ROI defined by (150, 100) as XY-coordinates of top left corner, 200 as width, and 300 as height, then save the cropped image to cropped_image.jpg.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Define the region of interest (ROI)
x, y, w, h = 150, 100, 200, 300

# Crop the image using ROI
cropped_img = img[y:y+h, x:x+w]

# Save cropped image
cv2.imwrite('cropped_img.jpg', cropped_img)

cropped_img.jpg

Python OpenCV - Crop the image using ROI

2. Crop the central part of image with 200×200 shape

In the following program, we crop the central part of the image with required crop region having a width of 200, and a heigh of 200.

Width and height of the crop is given. But XY coordinates are not mentioned. Since we have to crop the central part, you can compute the XY coordinates of the top left corner of the crop using the image shape and required crop shape.

Python Program

import cv2

# Load the image
img = cv2.imread('test_image_house.jpg')

# Define the region of interest (ROI)
w, h = 200, 200

# Calculate the XY of top left corner of ROI
img_h, img_w = img.shape[:2]
x, y = int(img_w/2 - w/2), int(img_h/2 - h/2)
print(x, y, w, h)

# Crop the image using ROI
cropped_img = img[y:y+h, x:x+w]

# Save cropped image
cv2.imwrite('cropped_img.jpg', cropped_img)

cropped_img.jpg

Python OpenCV - Crop the central part of image

Summary

In this Python OpenCV Tutorial, we have seen how to crop an image using slicing technique.

Code copied to clipboard successfully 👍