Cropping an Image using OpenCV in Python

Python | Cropping an Image: Here, we will see how can we crop an image using OpenCV in Python?
Submitted by Abhinav Gangrade, on June 20, 2020

What is Cropping?

Cropping is the removal of unwanted outer areas from a photographic or illustrated image. The process usually consists of the removal of some of the peripheral areas of an image to remove extraneous trash from the picture, to improve its framing, to change the aspect ratio, or to accentuate or isolate the subject matter from its background.

We will be using these functions of OpenCV - python(cv2),

  1. imread(): This function is like it takes an absolute path of the file and reads the whole image, and after reading the whole image it returns us the image and we will store that image in a variable.
  2. imshow(): This function will be displaying a window (with a specified window name) which contains the image that is read by the imread() function.
  3. shape: This function will return the height, width, and layer of the image

Let’s take an example,

Let there be a list a=[1,2,3,4,5,6,7,8,9]

Now, here I just wanted the elements between 4 and 8
(including 4 and 8) so what we will do is :

The result will be like : [4,5,6,7,8]

Python program to crop an image

# importing the module
import cv2


# Reading the image with the help of
# (specified the absolute path)
# imread() function and storing it in the variable img
cv2.imshow("Original Image",img)

# Displaying the Original Image Window 
# named original image
# with the help of imshow() function

# storing height and width with the help
# of shape function as shape return us
# three things(height,width,layer) in the form of list
# but we wanted only height and width

# start_row and start_col are the cordinates 
# from where we will start cropping
# end_row and end_col is the end coordinates 
# where we stop

# using the idexing method cropping 
# the image in this way
# using the imshow() function displaying 
# another window of
# the cropped picture as cropped contains 
# the part of image


Python | cropping an image

You can see the Cropped Image and the Original Image(the cropping is done like 0.25 to 0.75 with row and with column 0.25 to 0.75, and you can change the number).

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.