簡體   English   中英

我想比較兩個 numpy 數組並創建第三個數組

[英]I want to compare two numpy arrays and create a third array

就像標題所說的那樣,我想比較兩個以 1 和 0 作為元素的 sitk 數組,並創建一個具有 1 的第三個數組,其中兩個數組在任何其他情況下都有 1 和 0。 數組大小相同並且是 3 維的,但是有沒有比使用嵌套的 for 循環遍歷它們更有效的方法呢?

import numpy as np

a = np.random.randint(low=0, high=2, size=(2,3,4), dtype=np.int)
print(a)

b = np.random.randint(low=0, high=2, size=(2,3,4), dtype=np.int)
print(b)

c = np.logical_and(a,b).astype(int)
print(c)

這就是你要找的嗎?

arr_shape = (1,4,3)
a = np.random.randint(low=0,high=2, size=arr_shape)
print(a)
b = np.random.randint(low=0,high=2, size=arr_shape)
print(b)
# the new array. subtract a and b and get the absolute value.
# then invert to get the required array
d = (~abs(b - a).astype(bool)).astype(int)
print(d)

輸出:

[[[1 1 0]
  [1 0 0]
  [0 1 1]
  [1 1 0]]]
[[[0 1 0]
  [0 1 0]
  [1 0 0]
  [0 0 1]]]
array([[[0, 1, 1],
        [0, 0, 1],
        [0, 0, 0],
        [0, 0, 0]]])

如果您有 SimpleITK 圖像,則可以使用 And 函數。

import SimpleITK as sitk
result = sitk.And(image1, image2)

這是 AndImageFilter 的功能版本。 您可以在此處閱讀該課程的文檔: https : //simpleitk.org/doxygen/latest/html/classitk_1_1simple_1_1AndImageFilter.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM