Open Source Computer Vision (OpenCV) is an
Note: learn more about OpenCV.
An image is typically represented as a two-dimensional matrix, where each element corresponds to a pixel value within the image. These pixel values store information regarding the color intensity of each pixel.
In the case of grayscale images, each pixel value ranges from
[[135, 150, 120, 100],[50, 80, 200, 90],[200, 180, 220, 75]]
However, for colored images, each pixel value is represented by an RGB (Red, Green, Blue) matrix in the form [R, G, B]
. The R
, G
, and B
values individually range from
For example, a colored image of dimensions
[[[255, 0, 146], [0, 255, 45]],[[0, 0, 255], [255, 255, 69]]]
Resizing an image means changing the dimensions of the image while retaining its original form. Python library OpenCV can do this job efficiently using the resize()
method. Its syntax is as follows:
resize(x,y)
where:
x
is the image matrix of the image being resized.
y
is a tuple containing the new dimensions of the resultant resized image.
The following image has the dimensions of
The code below will resize this image and change its dimensions from
import cv2 # Load the image image = cv2.imread('image.jpg') # Define the new dimensions for the resized image new_width = 600 new_height = 300 # Resize the image resized_image = cv2.resize(image, (new_width, new_height)) # Display the resized image cv2.imshow('Original Image', image) cv2.imshow('Resized Image', resized_image) cv2.waitKey(0) cv2.destroyAllWindows()
Note: You can drag the image windows to have a better comparison.
Line 1: Imports cv2
library.
Line 4: imread()
method loads the image and stores its matrix in image
variable.
Lines 7–9: Defines new dimensions.
Line 11: Uses resize()
method of cv2
library and stores the resized image matrix in the resized_image
variable.
Line 14: Displays the original image with the label Original Image
.
Line 15: Displays the resized image with the label resized_image
.
Line 16: waitKey(0)
waits for the user to press any key to close all the windows.
Line 17: distroyAllWindows()
function closes every opened window.
The resultant resized image will be as follow: