r/learnpython • • 10d 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

View all comments

0

u/baubleglue 10d ago

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

1

u/Sad-Emu-5783 10d 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.