相关疑难解决方法(0)

与最后一个索引相比,numpy数组的访问时间受到最后一个索引的影响更大

这是对我之前的问题的回答的后续跟进将数千个图像读入一个大的numpy数组的最快方法.

第2.3章"ndarray的内存分配"中,Travis Oliphant写了以下关于如何在内存中访问C-ordered numpy数组的索引.

...按顺序移动计算机内存,最后一个索引首先递增,然后是倒数第二个索引,依此类推.

这可以通过对两个第一个或最后两个索引的二维数组的访问时间进行基准测试来确认(对于我的目的,这是加载500个大小为512x512像素的图像的模拟):

import numpy as np

N = 512
n = 500
a = np.random.randint(0,255,(N,N))

def last_and_second_last():
    '''Store along the two last indexes'''
    imgs = np.empty((n,N,N), dtype='uint16')
    for num in range(n):
        imgs[num,:,:] = a
    return imgs

def second_and_third_last():
    '''Store along the two first indexes'''
    imgs = np.empty((N,N,n), dtype='uint16')
    for num in range(n):
        imgs[:,:,num] = a
    return imgs
Run Code Online (Sandbox Code Playgroud)

基准

In [2]: %timeit last_and_second_last()
136 ms ± 2.18 ms per loop (mean …
Run Code Online (Sandbox Code Playgroud)

python memory arrays performance numpy

8
推荐指数
1
解决办法
293
查看次数

从文件夹中的图像序列获取 numpy 数组

我有一个文件夹,里面video1有一堆按顺序排列的图像frame_00.png, frame_01.png, ...

我想要的是格式为 4D numpy 数组(number of frames, w, h, 3)

这就是我所做的,但我认为它很慢,有没有更快或更有效的方法来实现同样的事情?

folder = "video1/"

import os
images = sorted(os.listdir(folder)) #["frame_00", "frame_01", "frame_02", ...]

from PIL import Image 
import numpy as np 

video_array = []
for image in images:
    im = Image.open(folder + image)
    video_array.append(np.asarray(im)) #.transpose(1, 0, 2))

video_array = np.array(video_array)
print(video_array.shape)
#(75, 50, 100, 3)
Run Code Online (Sandbox Code Playgroud)

python numpy image-processing python-imaging-library keras

2
推荐指数
1
解决办法
7043
查看次数