Cropping is a common image processing task that involves extracting a desired portion of the original image. OpenCV, a popular image processing library, offers various ways to crop images. Here's a simple and practical method using NumPy slicing:
import cv2 # Read the original image img = cv2.imread("lenna.png") # Define the coordinates of the cropping rectangle x = 100 # Starting x-coordinate y = 100 # Starting y-coordinate w = 200 # Width of the rectangle h = 150 # Height of the rectangle # Perform cropping using NumPy slicing crop_img = img[y:y+h, x:x+w] # Display the cropped image cv2.imshow("Cropped Image", crop_img) cv2.waitKey(0) cv2.destroyAllWindows()
This code efficiently crops the specified portion of the original image and displays the cropped result. Adjust the values of x, y, w, and h to crop different parts of the image.
The above is the detailed content of How to Crop an Image Using OpenCV in Python?. For more information, please follow other related articles on the PHP Chinese website!