Home > Backend Development > Python Tutorial > How to Crop an Image Using OpenCV in Python?

How to Crop an Image Using OpenCV in Python?

Barbara Streisand
Release: 2024-12-04 08:02:11
Original
711 people have browsed it

How to Crop an Image Using OpenCV in Python?

Crop an Image using OpenCV in Python

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

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!

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