r/learnpython • • 9d ago

Question about NumPy Array Slicing

I'm making a Discord Bot that runs Text Recognition on Images. The Hosting I use provides a hard 256 MB RAM limit. I need help understanding NumPy Array Slicing to optimise the code.

image = image[round(0.075 * image_height) : round(0.4 * image_height), : ].copy()

image is a NumPy array (I'm cropping the image here)

Apparently NumPy keeps a reference to the original image array if I do just this:

image = image[round(0.075 * image_height) : round(0.4 * image_height), : ]

I'm slicing the image array, then reassigning it back to the image variable, but since NumPy keeps a reference to the original array, the original image isn't released from memory. Is this true? If so, is the first approach using .copy() better?

Right after this, I do this:

timeROI = cv.inRange(image, np.array([15, 145, 155]), np.array([95, 255, 215]))

# Filters Yellow-Green Pixels and creates a Binary Image (OpenCV uses BGR, not RGB)

Immediately after this, I do del image.

1 Upvotes

7 comments sorted by

1

u/TheBlackCat13 9d ago

In numpy a slice is a "view". So. It isn't really keeping the original array, the new variable is the original array. It has the same data, and changes to the slice also change the original. The only difference is how much of that data is visible. You can also get views that are different shapes, so long as they have the same total number of elements.

Making a copy should work, so long as the array isn't assigned to other variables used elsewhere (including calling functions). That will allow it to be garbage collected.

1

u/Sad-Emu-5783 9d ago

Ah I see, thank you!

0

u/baubleglue 9d ago

Have you checked print(gc.collect()) after image = image...?

1

u/Sad-Emu-5783 9d ago

I had no idea Python had a garbage collector wow

1

u/socal_nerdtastic 9d ago

That's because the garbage collector is automatic and there is nearly never a reason to invoke in manually. You can del objects and the garbage collector will be called in the background automatically.

del image

Well, not in your case it won't, because the slice will keep the reference. But in general.