Search code examples
pythonarraysnumpyopencvcrop

Crop array of images more efficiently python cv2


I have some code that crops an ROI on a 3D array of images (so an array of image arrays) in python. I have code running now using a while loop, but it seems to be really slow. I was wondering if there was a more efficient way of doing this process as this seems to be taking quite some time for my large amount of imagery. Information and code below:

  • dimensions of my images are 512x640
  • I'm trying to crop out an ROI of 460x213
  • training_images is the original array of images with shape (n, 512, 640)

code:

train_shape = training_images.shape

## Select ROI:
x1 = 175            # These values are the upper right of the image
x2 = x1 + 213       # Height
y1 = 4
y2 = y1 + 460       # Width

## Generate a blank array to input the values into
i = 0
training_imagesROI = np.empty(shape=(train_shape[0], x2-x1, y2-y1), dtype=float)
 while i < train_shape[0]:
   im = training_images[i]
   im = im[x1:x2, y1:y2]
   training_imagesROI[i] = im
   i+=1

Solution

  • It's as simple as

    training_imagesROI = training_images[:, x1:x2, y1:y2]
    

    https://numpy.org/doc/stable/user/basics.indexing.html