Open Source Computer Vision (OpenCV) is an
Note: You can 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
[[[255, 0, 146], [0, 255, 45]],[[0, 0, 255], [255, 255, 69]]]
Cropping an image means selecting and extracting a specific rectangular region from the original image. Python library OpenCV can do this job efficiently as follows:
import cv2 # Load the original image original_image = cv2.imread('image.jpg') # Define the dimensions of the output image output_width = 400 output_height = 300 # Calculate the starting coordinates for cropping start_x = (original_image.shape[1] - output_width) // 2 start_y = (original_image.shape[0] - output_height) // 2 # Perform the cropping cropped_image = original_image[start_y : start_y + output_height, start_x : start_x + output_width] # Display or save the cropped image cv2.imshow('Original Image',original_image) cv2.imshow('Cropped Image', cropped_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: Loads the image (named image.jpg
) that's supposed to be cropped and stores it in original_image
. This image has the dimensions of
Lines 7–8: output_width
and output_height
store the dimensions of the resultant cropped image.
Lines 11–12: start_x
stores the starting x-coordinate of the point from where the image will be cropped. start_y
does the same thing for y-coordinate.
Line 15: Slices the original image matrix (original_image
) and stores it in cropped_image
. Now, the cropped_image
variable contains the image matrix of the cropped image.
Line 18: Displays the uncropped image.
Line 19: Displays the cropped image.
Line 20: waitKey()
method waits for the user to press any key to close all the windows.
Line 21: Closes all the opened windows at the end of the program.
and storing it in original_image
variable.
Learn more about it:
Free Resources