- Given an image stored at
- a target
heightin pixels, and
- a target starting point (upper-left)
yin 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:
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
height=190 pixels and upper-left starting points
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:
And here’s the cropped image:
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:
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?
- Join the free Finxter email academy to boost your basic Python skills via email video lessons.
- Join the OpenCV image recognition course—along with dozens of additional courses—at the Finxter Computer Science Academy.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.