Home > Backend Development > Python Tutorial > How Can I Efficiently Crop Images Using OpenCV and NumPy in Python?

How Can I Efficiently Crop Images Using OpenCV and NumPy in Python?

Mary-Kate Olsen
Release: 2024-12-01 04:46:12
Original
980 people have browsed it

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)
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template