Cropping images

From Lofaro Lab Wiki
Revision as of 23:26, 12 November 2014 by Kanik (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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)
cv2.waitKey(0)


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,


Crop.jpg