Cropping images

From Lofaro Lab Wiki
Jump to: navigation, search

Cropping is sometime very important for image processing. Cropping means to remove the outer parts of an image, and keeping only the parts you are interested in. Image cropping is easier using the Numpy arrays. Let’s see the sample code and understand what’s going on in a cropping,

import cv2
import numpy as np
image = cv2.imread('hubo.jpg',0)
cv2.imshow("Original", image)
cropped = image[30:180 , 150:300]
cv2.imshow("Hubo", cropped)

First we imported the packages, and loaded the image we want to crop. Just to remind that, the image must be within the folder you are working with your code.

You don’t need any special function to perform the crop operation. Slicing using the Numpy arrays is good enough. Here we cropped an image that starts at (150,30) and ends at (300,180). It should be kept in mind that OpenCV represents images as Numpy arrays with the height first and width second. That just means we need to provide our y-axis values before the x-axis values.

In our code 30 is starting y coordinate value, and 180 is ending y coordinate value. We gave the x-axis value after that. 150 is the staring x axis value and 300 is the ending y axis value.

After executing our code we can get our cropped image like below,