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 call cv.imread
to read the image file.
Then we take a slice of the image file object with the square bracket notation.
And then we call cv2.imshow
to display the image in a window.
For instance, we write:
import cv2
img = cv2.imread("test1.png")
crop_img = img[0:100, 0:150]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
We call cv2.imread
with the path string for the image and assign it to img
.
Then we crop the image by passing the start and end pixels of the y-axis, and start and end pixels of the x-axis respectively.
Both numbers are in pixels.
Next, we call cv2.imshow
with the crop_img
image to display the cropped image in a window.
Conclusion
To crop an image in OpenCV using Python, we can call cv.imread
to read the image file.
Then we take a slice of the image file object with the square bracket notation.
And then we call cv2.imshow
to display the image in a window.