Home >Backend Development >Python Tutorial >How to Crop Images in OpenCV Using Python: Numpy Slicing vs. getRectSubPix?

How to Crop Images in OpenCV Using Python: Numpy Slicing vs. getRectSubPix?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 18:12:17663browse

How to Crop Images in OpenCV Using Python: Numpy Slicing vs. getRectSubPix?

How to Crop Images in OpenCV Using Python

In image processing, cropping is a fundamental operation to extract specific regions from an image. OpenCV, a popular computer vision library in Python, provides various methods for cropping, including numpy slicing and functions like getRectSubPix.

Using numpy slicing for Cropping

The simplest and most straightforward approach for cropping images in OpenCV is using numpy slicing. Numpy arrays represent images in OpenCV, and you can access specific regions of the array using slicing operations.

import cv2

# Read the original image
img = cv2.imread("image.jpg")

# Crop a region using numpy slicing
cropped_img = img[y:y+h, x:x+w]

# Display the cropped image
cv2.imshow('Cropped Image', cropped_img)
cv2.waitKey(0)

Using getRectSubPix for Cropping

In certain scenarios, such as when precise sub-pixel cropping is required, OpenCV's getRectSubPix function can be utilized. It extracts a rectangular portion of the image while interpolating the pixel values.

import cv2

# Read the original image
img = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)

# Crop a region using getRectSubPix
cropped_img = cv2.getRectSubPix(img, (w, h), (x, y))

# Display the cropped image
cv2.imshow('Cropped Image', cropped_img)
cv2.waitKey(0)

Example Code (PIL vs. OpenCV)

To illustrate the difference between PIL and OpenCV, let's create an example similar to the one provided in the question.

PIL:

import PIL.Image as Image

im = Image.open('0.png').convert('L')
im = im.crop((1, 1, 98, 33))
im.save('_0.png')

OpenCV:

import cv2

# Read the image
img = cv2.imread('0.png', cv2.IMREAD_GRAYSCALE)

# Crop the image using numpy slicing
cropped_img = img[1:33, 1:98]

# Save the cropped image
cv2.imwrite('_0.png', cropped_img)

In this example, OpenCV uses numpy slicing to crop the image specified by the coordinates (1, 1, 98, 33). The resulting cropped image is saved as '_0.png.'

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