Crop image OpenCV
Open Source Computer Vision (OpenCV) is an
Note: You can learn more about OpenCV.
Image matrix
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
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.
Code explanation
Line 1: Imports
cv2library.Line 4: Loads the image (named
image.jpg) that's supposed to be cropped and stores it inoriginal_image. This image has the dimensions ofpixels. Lines 7–8:
output_widthandoutput_heightstore the dimensions of the resultant cropped image.Lines 11–12:
start_xstores the starting x-coordinate of the point from where the image will be cropped.start_ydoes the same thing for y-coordinate.Line 15: Slices the original image matrix (
original_image) and stores it incropped_image. Now, thecropped_imagevariable 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_imagevariable.
Learn more about it:
Free Resources