Cropping an Image is one of the most basic image operations that we perform in our projects. In this article, we will discuss how to crop images using OpenCV in Python.
Stepwise Implementation
For this, we will take the image shown below.
Step 1: Read the image
cv2.imread() method loads an image from the specified file. If the image cannot be read (because of the missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix.
Note: When we load an image in OpenCV using cv2.imread(), we store it as a Numpy n-dimensional array.
Example: Python program to read the image
Python3
import cv2 # Read Input Image img = cv2.imread( "test.jpeg" ) # Check the type of read image print ( type (img)) # Display the image cv2.imshow( 'image' , img) cv2.waitKey( 0 ) cv2.destroyAllWindows() |
Output:
Step 2: Get the image Dimensions
We can see the type of ‘img‘ as ‘numpy.ndarray‘. Now, we simply apply array slicing to our NumPy array and produce our cropped image, So we have to find the dimensions of the image. For this we will use the image.shape attribute.
Syntax:
image.shape
where image is the input image
Example: Python code to find the dimensions of the image,
Python3
import cv2 # read the image img = cv2.imread( "test.jpeg" ) print ( type (img)) # Check the shape of the input image print ( "Shape of the image" , img.shape) |
Output:
Step 3: Slice the image
Now we can apply array slicing to produce our final result.
Syntax :
image[rows,columns]
where
- rows are the row slice
- columns is the column slice
Example:
Python3
import cv2 img = cv2.imread( "test.jpeg" ) print ( type (img)) # Shape of the image print ( "Shape of the image" , img.shape) # [rows, columns] crop = img[ 50 : 180 , 100 : 300 ] cv2.imshow( 'original' , img) cv2.imshow( 'cropped' , crop) cv2.waitKey( 0 ) cv2.destroyAllWindows() |
Output: