Crop Image with OpenCV-Python
Cropping an Image is one of the most basic image operations that we perform in our projects. In this article, w will discuss how to crop images using OpenCV in Python.
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
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.
where image is the input image
Example: Python code to find the dimensions of the image,
Step 3: Slice the image
Now we can apply array slicing to produce our final result.
- rows are the row slice
- columns is the column slice