受到接受的答案的啓發,我找到了一種合併蒙版數組的簡單方法。它可以在掩碼上進行一些邏輯操作,並簡單地添加0填充的數組。
import numpy as np
a = np.zeros((1000, 1000), dtype=np.int16)
a[:500, :500] = 2
am = np.ma.masked_equal(a, 0)
b = np.zeros((1000, 1000), dtype=np.int16)
b[250:750, 250:750] = 3
bm = np.ma.masked_equal(b, 0)
c = np.zeros((1000, 1000), dtype=np.int16)
c[500:1000, 500:1000] = 5
cm = np.ma.masked_equal(c, 0)
bm.mask = np.logical_or(np.logical_and(am.mask, bm.mask), np.logical_not(am.mask))
am = np.ma.array(am.filled(0) + bm.filled(0), mask=(am.mask * bm.mask))
cm.mask = np.logical_or(np.logical_and(am.mask, cm.mask), np.logical_not(am.mask))
am = np.ma.array(am.filled(0) + cm.filled(0), mask=(am.mask * cm.mask))
plt.imshow(am)
我希望有人發現這是很有幫助的某個時候。掩蓋的數組似乎不是非常有效的。所以,如果有人發現一個合併數組的替代品,我很樂意知道。
更新:基於@morningsun評論此實現30%的速度更快,更簡單:
import numpy as np
a = np.zeros((1000, 1000), dtype=np.int16)
a[:500, :500] = 2
am = np.ma.masked_equal(a, 0)
b = np.zeros((1000, 1000), dtype=np.int16)
b[250:750, 250:750] = 3
bm = np.ma.masked_equal(b, 0)
c = np.zeros((1000, 1000), dtype=np.int16)
c[500:1000, 500:1000] = 5
cm = np.ma.masked_equal(c, 0)
am[am.mask] = bm[am.mask]
am[am.mask] = cm[am.mask]
plt.imshow(am)
什麼是毫無遮攔的速度? – hpaulj
在你的真實數據中,數組中的數字總是像這樣的常量?你實際上是否需要乘以數字,還是僅僅是你真正關心的口罩? –
我打算用這個代表圖像的數組。理想情況下,我想保留原始數組的值(我知道我的代碼不會保留這些值,因爲它們會在交集中相乘)... – MonkeyButter