Home > Backend Development > Python Tutorial > How to Crop Images in OpenCV Using NumPy Slicing?

How to Crop Images in OpenCV Using NumPy Slicing?

Mary-Kate Olsen
Release: 2024-12-01 05:21:54
Original
786 people have browsed it

How to Crop Images in OpenCV Using NumPy Slicing?

Image Cropping in OpenCV with Python

To crop images in OpenCV, unlike with PIL, you can use NumPy slicing. Here's how:

  1. Load the image:
import cv2
img = cv2.imread("image.jpg")
Copy after login
  1. Define the crop parameters:
  • x: Starting column
  • y: Starting row
  • w: Width of the crop
  • h: Height of the crop
  1. Crop the image using NumPy slicing:
crop_img = img[y:y+h, x:x+w]
Copy after login
  1. Display the cropped image:
cv2.imshow("Cropped Image", crop_img)
cv2.waitKey(0)
Copy after login

Incorrect Usage of getRectSubPix

In your attempt, getRectSubPix was incorrectly used. This function is meant for drawing rectangles on an image and not cropping it.

The above is the detailed content of How to Crop Images in OpenCV Using NumPy Slicing?. 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