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
Mary-Kate OlsenOriginal
2024-12-01 05:21:54872browse

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")
  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]
  1. Display the cropped image:
cv2.imshow("Cropped Image", crop_img)
cv2.waitKey(0)

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!

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