我有2個Numpy數組,我需要對它們執行一些基本的數學運算。
但由於最終numpy數組的類型(uint8
)(名爲magnitude
),我也無法將此操作的結果大於255。任何想法?除了通過遍歷數組...用兩個Numpy數組執行數學運算 - 限制數
# Notice that the data type is "np.uint8", also arrays are 2D
magnitude = np.zeros((org_im_width,org_im_height), dtype=np.uint8)
# "numpy_arr_1" and "numpy_arr_2" both of the same size & type as "magnitude"
# In the following operation, I should limit the number to 255
magnitude = ((np.int_(numpy_arr_1))**2 + (np.int_(numpy_arr_2))**2)**0.5
# The following doesn't work obviously:
# magnitude = min(255,((np.int_(numpy_arr_1))**2+(np.int_(numpy_arr_2))**2)**0.5)
1.爲什麼會選擇使用'np.sqrt'代替** 0.5'? 2.關於信息丟失 - 我瞭解 - 我的目標是,Numpy數組中的數據最終將成爲'uint8',而忽略信息丟失。 3。我**不得**執行線性縮放!它會改變其他值,這些值不會高於255. 我的目標是執行該數學運算,並確保只有**值超過255的值將被更改爲255.這是因爲我最後的Numpy數組應該包含其類型爲「uint8」的數據。 謝謝! – Dor
'np.sqrt'和'** 0.5'做同樣的事,都是有效的。我只是更喜歡'np.sqrt',因爲它更具可讀性。由於我不知道你的手術的最終目標,我試圖展示所有可能的選擇。那麼'np.minimum'應該適合你。 –
這是行不通的:如果'a'和'b'是dint'uint8',當你做'a ** 2 + b ** 2'時,任何超過'255'的結果都會溢出,只有LSB位將被保留,例如如果你有'a = np.array([15,17],dtype = np.uint8)',那麼'a ** 2'的值爲'array([225,33],dtype = uint8)',其中'33 = 17 * 17%256'。因此,除非原始數組被轉換,否則正確解釋的剪切不起作用。在執行這些操作之前,先將它們'浮動'dtype。 – Jaime