[英]How can I simplify the following code so it runs faster?
我有一個包含許多二維圖像(幀)的三維數組。 我想通過考慮每個像素值的閾值來刪除背景,並在新的 3D 數組中復制新元素。 我編寫了以下代碼行,但運行起來成本太高。 我怎樣才能加快這段代碼?
ss = stack #3D array (571, 1040, 1392)
T,ni,nj = ss.shape
Background_intensity = np.ones([T,ni,nj])
Intensity = np.zeros([T,ni,nj])
DeltaF_F_max = np.zeros([T,ni,nj])
for t in range(T):
for i in range(ni):
for j in range(nj):
if ss[t,i,j]<12:
Background_intensity[t,i,j] = ss[t,i,j]
if Background_intensity[t,i,j] == 0 :
Background_intensity[t,i,j] = 1
else:
Intensity[t,i,j] = ss[t,i,j]
DeltaF_F_max[t,i,j]=(((Intensity[t,i,j] - Background_intensity[t,i,j])))/(Background_intensity[t,i,j])
我有一個 go 和 Numpy。我不確定你得到了什么結果,但在我的 Mac 上大約需要 20 秒。 即使在我將所有大小都減少了 8 倍之后,它還是一頭 memory 豬,因為您不需要int64
來存儲1
或小於12
或255
的數字。
我想知道您是否需要在一個 go 中全部處理 571 張圖像,或者您是否可以在獲取圖像時“即時”處理它們,而不是將它們全部收集在一個巨大的塊中。
您還可以考慮使用Numba執行此操作, for
它非常擅長優化循環 - 嘗試將[numba]
放在上面的搜索框中,或查看此示例 - 使用prange
來並行化跨 CPU 內核的循環。
無論如何,這是我的代碼:
#!/usr/bin/env python3
# https://stackoverflow.com/q/71460343/2836621
import numpy as np
T, ni, nj = 571, 1040, 1392
# Create representative input data, such that around 1/3 of it is < 12 for testing
ss = np.random.randint(0,36,(T,ni,nj), np.uint8)
# Ravel into 1-D representation for simpler indexing
ss_r = ss.ravel()
# Create extra arrays but using 800MB rather than 6.3GB each, also ravelled
Background_intensity = np.ones(T*ni*nj, np.uint8)
Intensity = np.zeros(T*ni*nj, np.uint8)
# Make Boolean (True/False) mask of elements below threshold
mask = ss_r < 12
# Quick check here - print(np.count_nonzero(mask)/np.size(ss)) and check it is 0.333
# Set Background_intensity to "ss" according to mask
Background_intensity[mask] = ss_r[mask]
# Make sure no zeroes present
Background_intensity[Background_intensity==0] = 1
# This corresponds to the "else" of your original "if" statement
Intensity[~mask] = ss_r[~mask]
# Final calculation and reshaping back to original shape
DeltaF_F_max = (Intensity - Background_intensity)/Background_intensity
DeltaF_F_max.reshape((T,ni,nj))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.