Is it possible to immediately reduce memory usage by deleting variables?

asked 2019-09-11 08:09:03 -0500

SagRU gravatar image

Hello,

I have an OpenCV Python script that processes batches of color images of different sizes. The script is quite 'heavy', because every input image is copied, rotated and transposed multiple times. Everything works fine until I receive a large image (e.g. 1600 x 1600 px). When the script tries to process such an image, it crashes on one of transposing operations with "Insufficient memory" error.

I understand that I have to reduce memory usage somehow. Is it possible to immediately reduce memory usage by deleting variables?

Here's a rough representation of my script as it is now:

source_image = cv2.imread("large_image.jpg",1)
source_image_1 = source_image.copy()
source_image_2 = source_image.copy()

source_image_new = cv2.flip(source_image, 0)
source_image_1_new = cv2.flip(source_image_1, 0)
source_image_2_new = cv2.flip(source_image_2, 0)

source_image_t = cv2.transpose(source_image)
source_image_1_t = cv2.transpose(source_image_1)
source_image_2_t = cv2.transpose(source_image_2)

I'm planning to rewrite it in a following way:

source_image = cv2.imread("large_image.jpg",1)
source_image_1 = source_image.copy()
source_image_2 = source_image.copy()

source_image_new = cv2.flip(source_image, 0)
source_image_t = cv2.transpose(source_image)
cv2.imwrite("source_image_new", source_image_new)
cv2.imwrite("source_image_t", source_image_t)
del source_image, source_image_new, source_image_t

source_image_1_new = cv2.flip(source_image_1, 0)
source_image_1_t = cv2.transpose(source_image_1)
cv2.imwrite("source_image_1", source_image_1)
cv2.imwrite("source_image_1_new", source_image_1_new)
cv2.imwrite("source_image_1_t ", source_image_1_t)
del source_image_1, source_image_1_new, source_image_1_t 

source_image_2_new = cv2.flip(source_image_2, 0)
source_image_2_t = cv2.transpose(source_image_2)
cv2.imwrite("source_image_2", source_image_2)
cv2.imwrite("source_image_2_new", source_image_2_new)
cv2.imwrite("source_image_2_t ", source_image_2_t)
del source_image_2, source_image_2_new, source_image_2_t

I'm planning to save all needed images as files instead of holding them in the memory and then delete unused variables. Will it help? I can't simply test it because in reality the script is much more complicated.

edit retag flag offensive close merge delete