How to Crop an Image Using OpenCV?

3/5 - (2 votes)

Problem Formulation

  • Given an image stored at image.jpeg,
  • a target width and height in pixels, and
  • a target starting point (upper-left) x and y in the coordinate system.

How to crop the given image in Python OpenCV so that the resulting image has width * height size?

Here’s an example of how the original image is cropped to a smaller area from (100, 20) upper-left to (540, 210) bottom-right:

How to Crop an Image Using OpenCV?

Solution: Slicing

To crop an image to a certain area with OpenCV, use NumPy slicing img[y:y+height, x:x+width] with the (x, y) starting point on the upper left and (x+width, y+height) ending point on the lower right. Those two points unambiguously define the rectangle to be cropped.

Here’s the example of how to crop an image with width=440 and height=190 pixels and upper-left starting points x=100 and y=20 pixels as shown in the graphic before.

import cv2

# Load Image
img = cv2.imread("image.jpg")

# Prepare crop area
width, height = 440, 190
x, y = 100, 20

# Crop image to specified area using slicing
crop_img = img[y:y+height, x:x+width]

# Show image
cv2_imshow("cropped", crop_img)
cv2.waitKey(0)

Here’s the original image:

image.jpg

And here’s the cropped image:

cropped_image.jpg

To succeed as a programmer, you need to focus. Find a specific niche and master it! In other words, crop yourself a new and valuable skillset in the data science and machine learning era: learn OpenCV!

Master OpenCV with our new FINXTER ACADEMY course:

*** An Introduction to Face and Object Detection Using OpenCV ***

Alternative Crop Image Using PIL

You can also use the standard PILLOW library to crop an image in Python. Here‘s my blog post that shows you how to accomplish this and here’s the video guide:

How to Crop an Image Using PIL?

You can find the full article about how to crop an image with PIL here:

[Article] How to Crop an Image With PIL

Thanks for studying the whole article. Where to go from here?