我正在使用NumPy和Pillow处理图像,我有32G的RAM,但所有内存都在使用。我该怎么做才能改进我的计划?这是我的部分代码:
import os
import numpy as np
from PIL import Image
from numpy import *
img_rows,img_cols,img_depth=240,240,30
X_tr=[]
path = '/home/lt/Spyder/data1/brushing teeth/Depth1/'
imlist = os.listdir(path)
imlist.sort(key= lambda x:int(x[:-4]))
im = np.array(Image.open(path+imlist[0]))
m,n = im.shape[0:2]
imbr = len(imlist)
num = imbr-30
i = 0
while i<num :
frames=[]
for k in range(30):
im=np.array(Image.open(path+imlist[k+i]))
frames.append(im)
i=i+5
input=np.array(frames)
ipt = np.rollaxis(np.rollaxis(input,2,0),2,0)
X_tr.append(ipt) #265
X_tr
变量的大小为3751行,我的内存为99%。我该怎么办?也许我应该处理100000张图片,但这只是数据的四分之一!
答案 0 :(得分:0)
您正在将所有文件作为Image实例加载到内存中。因此,您的图像太大,无法放入记忆中。您应该处理较少的图像,或者图像的尺寸应该更小。
然而,你似乎只是循环它,因此如果你使用发电机你应该没事。
您的代码令人困惑,因为您希望处理所有内容,但每隔5帧只执行一次?无论如何,这里有一些优化:
# drop this, not needed
# i = 0
# better memory data structure
# this should fix your memory problem
frames = collections.deque(maxlen=30)
# process every 5th frame?
# there seems to be a flaw in that you cut the last 30 but you
# when you start you also do not have 30. (can add if len(frames) < 30)
for file_name in files[::5]:
frames.append(np.array(Image.open(path + file_name))
input = np.array(frames)
ipt = np.rollaxis(np.rollaxis(input,2,0),2,0)
X_tr.append(ipt) #265