How to Crop an image in python using OpenCV : 5 Steps Only

Crop an image in python using OpenCV

Do you want to crop an image in python? If yes then this tutorial is for you. You will know how to crop an image in python using the OpenCV packages. OpenCV is the best library for image processing and transformation. There are many inbuilt functions in it and using one of the functions you will crop an image in python.

Steps to Crop an image in python

In this section, you will know all the steps to crop an image in python. You have to just follow the steps for deep understanding.

Step 1: Import all the required libraries

The first step is to import all the necessary libraries required for this tutorial. In our example, We are using OpenCV only so let’s import it with the import statement.

import cv2

Step 2: Read the image

The second step is to read the image for cropping. In OpenCV, you can read the image using the cv2.imread() method.  It will read the image as an array. Let’s read it using the following line of code.

img = cv2.imread("bird2.jpg")

I am reading the following image. An image of a bird.

Bird image
Bird image

Step 3: Define the dimensions

After reading the image, let’s define from where you want to crop the image and for how much height and width. It will be used to crop the image to the defined dimensions.

x =100
y = 50
h = 300
w= 300

Here x and y are the starting point for cropping and h and w is the height and width for the image.

Step 4: Crop the image

To crop the image you have to just pass the dimensions inside the img[] array. Use the following lines of code to crop the image.

cropped_image = img[y:y+h,x:x+w]

Step 5: Show the image

Now after cropping let’s compare the original image and the cropped image.  In OpenCV, you can show the image using the cv2.imshow() function. Add the following lines of code.

cv2.imshow("Cropped Image",cropped_image)
cv2.imshow("OriginalImage",img)

If you want to save the cropped image to your disk then you can use the cv2.imwrite() function.

Full Code

import cv2
img = cv2.imread("bird2.jpg")
x =100
y = 50
h = 300
w= 300
cropped_image = img[y:y+h,x:x+w]
cv2.imshow("Cropped Image",cropped_image)
cv2.imshow("OriginalImage",img)
cv2.imwrite("Cropped Image.jpg", cropped_image)
cv2.waitKey(0)

Output

Cropped image
Cropped image of a bird

Conclusion

OpenCV is a great library for manipulating images. You can do most of the complex work on images using it. These are the steps to crop an image in python using OpenCV. I hope you have liked this tutorial. If you have any doubt then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Share via
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner