Menu Close

How to crop an image in OpenCV using Python?

Sometimes, we want to crop an image in OpenCV using Python.

In this article, we’ll look at how to crop an image in OpenCV using Python.

How to crop an image in OpenCV using Python?

To crop an image in OpenCV using Python, we can slice the image list.

For instance, we write

import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

to open the image with

cv2.imread("lenna.png")

Then we crop the image by slicing the pixels with

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

Next we shouw the cropped image with imshow.

Conclusion

To crop an image in OpenCV using Python, we can slice the image list.

Posted in Python, Python Answers