Crop Image using OpenCV in Python
One of the most fundamental picture processes we use in our projects is cropping an image. We’ll go through how to crop image in Python using OpenCV in this tutorial.
Crop Image with OpenCV-Python
Cropping is used to eliminate any undesirable elements from a picture or even to draw attention to a certain aspect of a picture.
OpenCV does not have a particular method for cropping; instead, NumPy array slicing is used. A 2D array stores each picture that is read in (for each color channel). Simply define the region to be cropped’s height and breadth (in pixels). And that’s it!
Step-by-Step Execution
The image we will use for our code is:
Step 1: Examine the picture.
An image is loaded using the cv2.imread()
function from the given file. This function produces an empty matrix if the picture cannot be read (due to a missing file, poor permissions, an unsupported or invalid format, etc.).
Note: We save an image’s data as a Numpy n-dimensional array when we load it into OpenCV using cv2.imread()
.
import cv2 # Read the image first actual_img = cv2.imread("1664721752902.jpg") # print type of image print(type(actual_img)) # Show the image cv2.imshow('image',actual_img) cv2.waitKey(0) cv2.destroyAllWindows()
Step 2: Get Picture’s dimensions
The type of “image” is shown as “numpy.ndarray
.” We just use array slicing to our NumPy array at this point to create our cropped image, therefore we must ascertain its dimensions. We’ll make use of the ” image.shape
” property for this.
Syntax :
image[rows,columns]
The output will be:
<class 'numpy.ndarray'> Shape of the actual image (606, 565, 3)
Step 3: Cut the picture up
We can now use array slicing to create our desired outcome.
So our final Python Code will be:
import cv2 actual_img = cv2.imread("1664721752902.jpg") print(type(actual_img)) print("Shape of the actual image", actual_img.shape) crop_img = actual_img[50:180, 100:300] cv2.imshow('original image', actual_img) cv2.imshow('cropped image', crop_img) cv2.waitKey(0) cv2.destroyAllWindows()
The output will be:
Leave a Reply