📅  最后修改于: 2023-12-03 15:34:02.979000             🧑  作者: Mango
Opencv is an open-source computer vision library which consists of various image and video analysis functions. One of the most widely used functions in OpenCV is "imresize" which is used to resize the given image.
To use opencv in Python, you'll need to install it first. There are various methods to install opencv for Python, but here is the most common way via pip:
pip install opencv-python
The function imresize
takes two arguments: the input image and the desired output size. The output size can be specified in different formats, such as a tuple of (width, height)
or a scaling factor as a single float value.
resized_image = cv2.resize(input_image, output_size[, interpolation])
The third argument interpolation
is optional which specifies the method that should be used during resizing. The default interpolation method is cv2.INTER_LINEAR
which uses linear interpolation.
Here is a code snippet that shows how to resize an image by a scaling factor of 0.5 using OpenCV.
import cv2
input_image = cv2.imread('input_image.jpg')
scale_percent = 0.5
# calculate the new dimensions
width = int(input_image.shape[1] * scale_percent)
height = int(input_image.shape[0] * scale_percent)
output_size = (width, height)
# resize image
resized_image = cv2.resize(input_image, output_size)
cv2.imshow('Input Image', input_image)
cv2.imshow('Resized Image', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here is a code snippet that shows how to resize an image to a specific width and height using OpenCV.
import cv2
input_image = cv2.imread('input_image.jpg')
output_size = (500, 400) # (width, height)
# resize image
resized_image = cv2.resize(input_image, output_size)
cv2.imshow('Input Image', input_image)
cv2.imshow('Resized Image', resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Here is a code snippet that shows how to resize an image with different interpolation methods using OpenCV.
import cv2
input_image = cv2.imread('input_image.jpg')
output_size = (500, 400) # (width, height)
# resize image with different interpolation methods
interpolation_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_AREA,
cv2.INTER_CUBIC, cv2.INTER_LANCZOS4]
for method in interpolation_methods:
resized_image = cv2.resize(input_image, output_size, interpolation=method)
cv2.imshow(f'Resized Image ({method})', resized_image)
cv2.imshow('Input Image', input_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
In the above code, we have used various interpolation methods such as cv2.INTER_NEAREST
, cv2.INTER_LINEAR
, cv2.INTER_AREA
, cv2.INTER_CUBIC
, and cv2.INTER_LANCZOS4
to resize the input image.