How can I crop images, like I\'ve done before in PIL, using OpenCV.
Working example on PIL
im = Image.open(\'0.png\').convert(\'L\')
im = im.crop((1
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.