Home >Backend Development >Python Tutorial >How Can I Efficiently Crop Images Using OpenCV and NumPy in Python?
Image Cropping in OpenCV Using Python
This question discusses how to crop an image using OpenCV in Python, highlighting the differences with a previous approach using PIL. To use OpenCV for image cropping, the preferred method is to utilize NumPy array slicing rather than the getRectSubPix function.
Here's the Python code snippet demonstrating the numpy-based cropping:
import cv2 # Load the image img = cv2.imread("image.png") # Specify the cropping coordinates (x, y, width, height) x = 100 y = 100 w = 200 h = 150 # Perform the cropping using NumPy slicing cropped_img = img[y:y+h, x:x+w] # Display the cropped image cv2.imshow("Cropped Image", cropped_img) cv2.waitKey(0)
This approach eliminates the need for image conversion or explicit region extraction as with getRectSubPix, providing a more straightforward and efficient solution for image cropping in OpenCV.
The above is the detailed content of How Can I Efficiently Crop Images Using OpenCV and NumPy in Python?. For more information, please follow other related articles on the PHP Chinese website!