Python 将大量图像帧numpy数据存储并加载到内存中

Python 将大量图像帧numpy数据存储并加载到内存中,python,python-3.x,numpy,opencv,Python,Python 3.x,Numpy,Opencv,我想以优化的方式存储图像帧数据以及使用OpenCV提取的图像帧时间戳,然后将其加载回处理,下面是代码: import cv2 import pickle video_capture = cv2.VideoCapture('/tmp/abc.mp4') success, frame = video_capture.read() fps = video_capture.get(5) frame_number = 0 success = True frames_arr = [] while su

我想以优化的方式存储图像帧数据以及使用OpenCV提取的图像帧时间戳,然后将其加载回处理,下面是代码:

import cv2
import pickle

video_capture = cv2.VideoCapture('/tmp/abc.mp4')
success, frame = video_capture.read()
fps = video_capture.get(5)
frame_number = 0

success = True
frames_arr = []

while success:
   timestamp = 1000 * float(frame_number) / fps

   '''
   frame is a numpy ndarray, Sample data given
   {'matrix': array([[[0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.]],

    [[0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.]],

    [[0., 0., 0.],
     [0., 0., 0.],
     [0., 0., 0.]]]), 'timstamp': 123}
   '''

   frame_dict = {
       'timestamp': timestamp,
       'frame_matrix': frame
   }


   # Appending to frame array  
   # Conveting each dictionary to string and encoding it
   frames_arr.append(str(frame_dict).encode('utf-8'))

   success, frame = video_capture.read()
   frame_number += 1

# Storing all frames data into one pickle file
with open('/tmp/frame_data.pkl', 'wb') as bf:
    pickle.dump(frames_arr, bf)
如果我直接保存字典,它需要时间和大量空间(1700帧为2.2GB,视频文件为1min),因此我考虑将其存储为字符串(1.5mb),然后再次转换回字典

我可以加载
.pkl
文件并访问数据,但无法将其转换回字典,以下是加载和访问数据的代码

with open('/tmp/frames_data.pkl', 'rb') as f:
    data = pickle.load(f)

for i, single in enumerate(data):
    print(single.decode('utf-8'), type(single.decode('utf-8')))
我得到了
类型(single.decode('utf-8'))
作为
,所以我尝试了
ast.literal\u eval
,但它抛出了

ValueError: malformed node or string: <_ast.Call object at 0x7fa53e2c15c0>
ValueError:节点或字符串格式错误:
如果不是这样的话,还有什么其他的解决办法,我有4Gb的RAM,如果我不转换为字符串并尝试保存direct dictionary,则在保存3-4分钟的视频时它会挂起


请提供帮助。

无法保证pickle表示不会包含换行符。您是否尝试过
numpy.save
?为什么不在图像文件名中编码时间戳。使其复杂化的动机是什么?@ZdaR您的意思是使用带有时间戳的
cv2.imwrite()
,然后再次从文件名中检索它?@user2699我确实尝试过
numpy.save
,它会抛出相同的错误。