Crop Images

Download the source code

NOTE: Please reload the page when you jump from one lecture to another so that the code highlighter is loaded! Sorry for the inconvenience.

In OpenCV, images are simply Numpy arrays. So we can use Numpy array slicing to crop an image and remove the part we are not interested in.

The image below will be used as an example throughout this tutorial.

Sample image

Crop an Image Using OpenCV

The first dimension of a Numpy array represents the rows of the array (which is the height of the image or the y-coordinates) and the second dimension represents the columns of the array (which is the width of the image or the x-coordinates).

So to crop an image, we can use the following syntax:

cropped_img = img[y_start:y_end, x_start:x_end]

Let's jump straight to an example so you don't get lost.

import cv2

# read the image
image = cv2.imread("image.jpg")

cropped_img = image[50:200, 100:400]

cv2.imshow("Original image", image)
cv2.imshow("Cropped image", cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

When slicing a Numpy array we start with the height (the rows of the array) and then the width (the columns of the array).

Take a look at the image below to see the region we'll keep after cropping. The image also shows us the coordinates that will be used for cropping:

Cropped image y=50-200 x=100-400

Here is the result:

Cropped image

Let's see another example.

image = cv2.imread("image.jpg")
cropped_img = image[30:350, 270:450]

cv2.imshow("Original image", image)
cv2.imshow("Cropped image", cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Again, here are the coordinates and the region that we will keep after cropping :

Cropped image y=30-350 x=270-450

and here is the cropped image:

Cropped image 2

Here is a last example of cropping which will keep only the region of the flower:

image = cv2.imread("image.jpg")
cropped_img = image[30:365, 104:450]

cv2.imshow("Original image", image)
cv2.imshow("Cropped image", cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Cropped-flower

I think I've included enough examples so that you don't get lost. Hopefully, with these examples, you will get a better understanding of how cropping works.

Summary

Cropping is an important image processing operation and is also very simple to use. Maybe you can get confused with the starting and ending points of the slicing or you can reverse the x and y-coordinates but with some practice, this will become natural.

Complete and Continue  
Discussion

0 comments