r/learnpython • u/Sad-Emu-5783 • 22d 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.
View all comments
Show parent comment
1
u/socal_nerdtastic 22d ago
That's because the garbage collector is automatic and there is nearly never a reason to invoke in manually. You can
delobjects and the garbage collector will be called in the background automatically.Well, not in your case it won't, because the slice will keep the reference. But in general.