Home > Backend Development > Python Tutorial > How to Crop Images Efficiently with OpenCV and NumPy Slicing in Python?

How to Crop Images Efficiently with OpenCV and NumPy Slicing in Python?

Patricia Arquette
Release: 2024-12-03 01:28:10
Original
738 people have browsed it

How to Crop Images Efficiently with OpenCV and NumPy Slicing in Python?

Cropping Images with OpenCV Using Python

In image processing tasks, cropping is a fundamental technique for extracting specific regions of interest from an image. If you're familiar with cropping images using PIL library in Python, you may wonder how to achieve the same functionality with OpenCV.

To crop an image using OpenCV, you can utilize numpy slicing, which offers a straightforward and efficient approach. Consider the following code snippet:

import cv2

# Read the input image
img = cv2.imread("lenna.png")

# Define the cropping coordinates (x, y, width, height)
x = 100
y = 100
w = 200
h = 200

# Perform cropping using numpy slicing
crop_img = img[y:y+h, x:x+w]

# Display the cropped image
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)
Copy after login

By specifying the desired cropping coordinates, you can easily extract the specified region of the image using numpy slicing. This approach is simple, computationally efficient, and provides a level of control similar to what you're accustomed to with PIL.

The above is the detailed content of How to Crop Images Efficiently with OpenCV and NumPy Slicing in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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