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

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

如何將兩個for循環內計算的結果存儲在np數組中?

如何將兩個for循環內計算的結果存儲在np數組中?

楊__羊羊 2023-12-08 17:08:26
我想迭代圖像并將限制性 (x,y) 像素與點 (300,600) 之間的計算距離保存在 numpy 數組 np_dist 中。目前,所有 dist 值的結果都保存在數組的一個元素中。如何填充每個元素存儲一個值的數組?dist_arr = np.empty((width, height))for x in range(0, width):     for y in range(0, height):         pixel = (x, y)         dist = math.sqrt((300 - pixel[0])**2 + (600 - pixel[1])**2)         dist_arr[pixel[0], pixel[1]] = dist
查看完整描述

2 回答

?
Cats萌萌

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

你的循環沒有什么:


In [26]: width, height = 4,4

    ...: dist_arr = np.empty((width, height))

    ...: for x in range(0, width):

    ...:     for y in range(0, height):

    ...:         dist = math.sqrt((300 - x)**2 + (600 - y)**2)

    ...:         dist_arr[x, y] = dist

    ...: 

In [27]: dist_arr

Out[27]: 

array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],

       [670.37377634, 669.47890183, 668.58432527, 667.69004785],

       [669.92835438, 669.03288409, 668.13771036, 667.24283436],

       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])

有一些方法可以更快地做到這一點,但它們確實有效。


與整個數組numpy計算相同的值:


In [28]: np.sqrt((300-np.arange(4)[:,None])**2 + (600 - np.arange(4))**2)

Out[28]: 

array([[670.82039325, 669.92611533, 669.03213675, 668.1384587 ],

       [670.37377634, 669.47890183, 668.58432527, 667.69004785],

       [669.92835438, 669.03288409, 668.13771036, 667.24283436],

       [669.48412976, 668.58806451, 667.6922944 , 666.79682063]])


查看完整回答
反對 回復 2023-12-08
?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

嘗試np.indices?+?np.hypot

x,?y?=?np.indices((width,?height))
np_dist?=?np.hypot(x?-?300,?y?-?600)?#?or?np.hypot(300?-?x,?600?-?y)


查看完整回答
反對 回復 2023-12-08
  • 2 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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