Cropping Images
Cropping is a useful operation in computer vision that involves taking a subset of an image. Many applications allow user to crop an image on their profiles. Cropping is regularly used in building ML datasets as part of resampling and image to create variations of the same image for ML modelling purposes.
Cropping with Numpy
Index slicing is the easiest way to achieve cropping as demonstrated below
import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
cat = cv2.imread('cat.jpg')
cat = cv2.cvtColor(cat, cv2.COLOR_BGR2RGB)
plt.imshow(cat)
plt.axis('off')
cat.shape
(1280, 1920, 3)
Implementation with Numpy
To crop an image, we use numpy array slicing and pass the range of index location for the height and width to perform the crop. In the example below, the height range is $200:600$ and width range is 700:1090
cropped_cat = cat[ 200:600 , 700:1090 , : ]
plt.imshow(cropped_cat)
plt.axis('off')
cropped_cat.shape
(400, 390, 3)