用 3D 替换 2D numpy 数组(元素到向量)

Replace 2D numpy array with 3D (elements to vectors)

之前可能有人问过这个问题,所以我很高兴能找到答案,但我找不到。

我有一个 TrueFalse 的二维 numpy 数组。现在我需要将它转换成黑白图像(一个 3D numpy 数组),也就是说,我需要 [0,0,0] 代替每个 False 和 [1,1,1]每个 True。最好的方法是什么?例如,

Input:

[[False, True],
 [True, False]]

Output:
[[[0, 0, 0], [1, 1, 1]],
 [[1, 1, 1], [0, 0, 0]]]

(您可能知道,3D 图像是形状为 (height, width, 3) 的数组,其中 3 是深度维度,即通道数。)

如果有人能告诉我如何将其转换回来,即加分,即如果我有纯黑白图像(纯 [0,0,0] 和 [0,0,1] 像素),如何获得具有相同高宽尺寸但用 True 代替白色像素 ([1,1,1]) 并用 False 代替黑色像素 ([0, 0,0]).

最便宜的方法是将您的 bool 数据查看为 np.uint8,并添加一个假维度:

img = np.lib.stride_tricks.as_strided(mask.view(np.uint8),
                                      strides=mask.strides + (0,),
                                      shape=mask.shape + (3,))

不像mask.astype(np.uint8), mask.view(np.uint8) does not copy the data, instead harnesses the fact that bool_ is stored in a single byte. Similarly, the new dimension created by np.lib.stride_tricks.as_strided是一个不复制任何数据的视图。

您可以通过手动创建新的 array object 来绕过 as_stridedview

img = np.ndarray(shape=mask.shape + (3,), dtype=np.uint8,
                 strides=mask.strides + (0,), buffer=mask)

我认为最清楚的方法是这样的:

a = np.array([[False, True], [True, False]])
out = np.zeros((*a.shape, 3), dtype=np.uint8)
out[a.nonzero()] = 1

>>> out
array([[[0, 0, 0],
        [1, 1, 1]],

       [[1, 1, 1],
        [0, 0, 0]]], dtype=uint8)