亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Python 中快速求和多個數組中的一系列索引?

如何在 Python 中快速求和多個數組中的一系列索引?

飲歌長嘯 2022-11-01 16:08:33
我試圖使用一個方程重建 HDR 圖像,其中我必須對每個 i 值的分子和分母中的 j 個值 (0-15) 求和。有沒有更快的方法來做到這一點?也許使用 np.sum?g 是一個 255 長的一維數組,它重新映射所有像素值。lEks 是 15 張圖像的日志曝光時間Z 是一個大小為 [95488, 15] 的數組,第一維是像素索引,第二維是圖像編號def genHDR(Z,g,lEks):    Zi, Zj = Z.shape        #[95488, 15]    HDRimage= np.zeros(Zi)    for i in range(Zi):        numerator   = 0        denominator = 0        for j in range(Zj):            numerator   +=(Z[i,j])*(g[Z[i,j]] - lEks[j])            denominator +=(Z[i,j])        HDRimage[i] = numerator/denominator    return HDRimage
查看完整描述

2 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

可能最好的方法是使用 np.Array.sum(axis=1)。假設 g(Z[i,j]) 調用有效。你實際上甚至不需要任何循環:


import numpy as np


Z = np.random.randint(0,255,(10,15))

g=np.random.randint(0,10,(256))

lEks = np.random.rand((15))


def genHDR(Z,g,lEks):

    numerator = (Z*(g[Z]-lEks.view().reshape((1,)+ lEks.shape))).sum(axis=1)

    denominator = Z.sum(axis=1)

    HDRimage = numerator/denominator

    return HDRimage


查看完整回答
反對 回復 2022-11-01
?
森欄

TA貢獻1810條經驗 獲得超5個贊

也許您仍然可以使用以下內容來了解如何構建它。我喜歡逐步思考。


import numpy as np


Z=  np.random.randint(low=0,high=256,size=(6,3))   # assume just 3 images with 6 pixels each

print(f' Z= {Z}')


lEks=np.random.rand(3)

print(f'lEks = {lEks}')


g0=np.arange(255)   #some example mapping; here from byte to half byte

g= g0//2        # // integer division



npxl,nimage=np.shape(Z)

print(f'npxl={npxl} nimage={nimage}')


# vectorize just one operation at first, easier to visualize

hdr=np.zeros(npxl)


for i in np.arange(npxl):

    #print(Z[i])

    denom=np.sum(Z[i])

    hdr[i]= np.sum(Z[i] *(g[Z[i]]- lEks))/denom 

    # Z[i] is just a vector of length 3, just like lEks


print(hdr)


# this would do it, but still be slower than necessary, as your remaining loop has many more elements that 

# the one we dealt with



# now vectorize the other coordinate (remove the remaining for-loop)

hdr=np.zeros(npxl)

hdr=  np.sum(Z *(g[Z]- lEks), axis=1)/ np.sum(Z,axis=1)   # which axis to sum over is critical

print(hdr)


#final code


def genHDR(Z, g, lEks):

    npxl,nimage=np.shape(Z)

    hdr=np.zeros(npxl)

    hdr=  np.sum(Z *(g[Z]- lEks), axis=1)/ np.sum(Z,axis=1) 

    return hdr



print(genHDR(Z,g,lEks))

輸出:


 Z= [[199 101  67]

 [134  16 137]

 [219   5 135]

 [153  19  17]

 [238  41 120]

 [ 93  50 179]]

lEks = [0.57778608 0.18113957 0.85257974]

npxl=6 nimage=3

[72.94714613 63.50130665 91.04028102 62.58551969 90.46303414 65.97390417]

[72.94714613 63.50130665 91.04028102 62.58551969 90.46303414 65.97390417]

[72.94714613 63.50130665 91.04028102 62.58551969 90.46303414 65.97390417]


查看完整回答
反對 回復 2022-11-01
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號