Python 一种用不同的 dtype(单元 8 和单元 16)屏蔽两个数组的方法



我有 2 个数组:

掩码:值为 0 和 1,dtype=uint8

>>> mask
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [1, 1, 1, ..., 0, 0, 0],
       ..., 
       [1, 1, 1, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)

和prova_clip

>>> prova_clip
array([[289, 281, 271, ..., 257, 255, 255],
       [290, 284, 268, ..., 260, 260, 259],
       [294, 283, 264, ..., 265, 263, 257],
       ..., 
       [360, 359, 360, ..., 335, 338, 331],
       [359, 364, 369, ..., 337, 342, 339],
       [358, 363, 368, ..., 332, 331, 332]], dtype=uint16)

我希望使用代码保存方法来用掩码屏蔽prova_clip,以便

array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [294, 283, 264, ..., 0, 0, 0],
       ..., 
       [360, 359, 360, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16)

我错过了什么吗? 这似乎很简单:

prova_clip*mask

下面是一个示例:

>>> a = np.arange(10,dtype=np.uint16)
>>> mask = np.ones(10,dtype=np.uint8)
>>> mask[1:3] = 0
>>> a*mask
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)

您也可以以复杂的方式执行此操作,这将就地修改数组。

>>> b = np.arange(10,dypte=np.uint16)
>>> b[~mask.astype(bool)] = 0
>>> b
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)

最后,还有numpy.where

>>> c = np.arange(10,dtype=np.uint8)
>>> np.where(mask==0,0,c)
array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9], dtype=uint16)

最新更新