簡體   English   中英

快速提取3D numpy數組中的ROI的方法

[英]Fast way to extract ROIs in 3D numpy array

我有一個包含一些視頻數據的一維數組:

data=np.random.randint(0,high=255,size=(500*500*100),dtype=np.uint8)
imgs=np.reshape(data,(100, 500,500)) # 100 frames, 500x500 pixels

我想沿所有幀提取某些感興趣的區域(ROI)

idx=np.random.randint(0,high=500*500,size=(49, 300)) #300 rois, 49 points each
rois=imgs.reshape(100, -1)[:,idx]

我弄平每個幀,然后沿1維方向移動rois。 實際的imgs數組大於此處顯示的數組,並且以前的索引操作可能會有點慢。 如果我以不同的方式重塑imgs (請rois.size下文),則rois.size相同,並且索引rois.size要快得多,但這會檢索錯誤的數據

%timeit imgs.reshape(100, -1)[:,idx] # 13 ms
%timeit imgs.reshape(-1, 100)[idx, :] # 1.2 ms, much faster but wrong data

在我的真實代碼中,差異幾乎是50倍。 有什么方法可以快速索引imgs嗎?

似乎可以通過對ROI像素進行排序並使用轉置坐標來節省至少一點時間:

>>> def f_pp(im2D, idx):
...     s = np.argsort(idx.ravel())
...     out = np.empty((*idx.shape, im2D.shape[0]), im2D.dtype)
...     out.reshape(-1, im2D.shape[0])[s] = im2D.T[idx.ravel()[s]]
...     return out
... 

# results are the same:
>>> np.all(f_pp(imgs.reshape(100, -1), idx) == np.moveaxis(imgs.reshape(100, -1)[:, idx], 0, 2))
True

>>> timeit("imgs.reshape(100, -1)[:, idx]", globals=globals(), number=100)
1.3392871069954708
# transposing alone is not enough:
>>> timeit("imgs.reshape(100, -1).T[idx]", globals=globals(), number=100)
1.3336799899989273
# but together with sorting I see a 2x speedup
>>> timeit("f_pp(imgs.reshape(100, -1), idx)", globals=globals(), number=100)
0.5874412529956317
# still much worse than if we had a more favorable memory layout in
# the first place
>>> timeit("imgs.reshape(-1, 100)[idx]", globals=globals(), number=100)
0.06296327701420523

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM