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
Patricia ArquetteOriginal
2024-12-03 01:28:10717browse

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)

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!

Statement:
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