How to crop an image in OpenCV using Python
i had this question and found another answer here: copy region of interest
If we consider (0,0) as top left corner of image called im
with left-to-right as x direction and top-to-bottom as y direction. and we have (x1,y1) as the top-left vertex and (x2,y2) as the bottom-right vertex of a rectangle region within that image, then:
roi = im[y1:y2, x1:x2]
here is a comprehensive resource on numpy array indexing and slicing which can tell you more about things like cropping a part of an image. images would be stored as a numpy array in opencv2.
:)
This code crops an image from x=0,y=0 to h=100,w=200.
import numpy as np
import cv2
image = cv2.imread('download.jpg')
y=0
x=0
h=100
w=200
crop = image[y:y+h, x:x+w]
cv2.imshow('Image', crop)
cv2.waitKey(0)
Note that, image slicing is not creating a copy of the cropped image
but creating a pointer
to the roi
. If you are loading so many images, cropping the relevant parts of the images with slicing, then appending into a list, this might be a huge memory waste.
Suppose you load N images each is >1MP
and you need only 100x100
region from the upper left corner.
Slicing
:
X = []
for i in range(N):
im = imread('image_i')
X.append(im[0:100,0:100]) # This will keep all N images in the memory.
# Because they are still used.
Alternatively, you can copy the relevant part by .copy()
, so garbage collector will remove im
.
X = []
for i in range(N):
im = imread('image_i')
X.append(im[0:100,0:100].copy()) # This will keep only the crops in the memory.
# im's will be deleted by gc.
After finding out this, I realized one of the comments by user1270710 mentioned that but it took me quite some time to find out (i.e., debugging etc). So, I think it worths mentioning.
It's very simple. Use numpy slicing.
import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)