从文件逐像素读取numpy数组?

2024-04-26 11:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有数千个2D numpy数组(每个数组的形状为600x600)保存在一个文本文件中。我想逐像素读取每个数组的文件,并对这些像素的1D数组进行操作,而不必加载整个文件,因为这样会占用大量内存。你知道吗

例如,如果这在我的文件中:

array([[1, 42, 98, ..., 2], ..., [89, 10, 76, ..., 2]]), array([[36, 79, 13, ..., 11], [81, 101, 34, ..., 109]]), ...

然后我想要(对于[0][0]位置)[1, 36, ...],对于[0][1]我想要[42, 79, ...],依此类推。在我完成对每个1D数组的操作之后,我想从内存中删除它,然后继续阅读下一个数组。这可能吗?它也不必来自文本文件,如果其他类型的文件可以更好地工作。你知道吗


Tags: 文件内存numpy类型像素数组array形状
1条回答
网友
1楼 · 发布于 2024-04-26 11:15:35

您可以使用numpy memmap。像往常一样使用np.load加载数组,mmap_mode参数设置为True。从文档中:

Create a memory-map to an array stored in a binary file on disk.

Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory. NumPy’s memmap’s are array-like objects.

相关问题 更多 >