简体   繁体   English

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

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

This question has probably been asked before so I'm happy to be pointed to the answer but I couldn't find it.这个问题之前可能已经被问过,所以我很高兴被指出答案,但我找不到它。

I have a 2D numpy array of True and False .我有一个TrueFalse的二维 numpy 数组。 Now I need to convert it into a black and white image (a 3D numpy array), that is, I need [0,0,0] in place of every False and [1,1,1] in place of every True .现在我需要将其转换为黑白图像(一个 3D numpy 数组),也就是说,我需要 [0,0,0] 代替每个False和 [1,1,1] 代替每个True What's the best way to do this?最好的方法是什么? For example,例如,

Input:

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

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

(As you probably know, 3D images are arrays of shape (height, width, 3) where 3 is the depth dimension ie number of channels.) (您可能知道,3D 图像是 arrays 形状(height, width, 3) ,其中 3 是深度维度,即通道数。)

Bonus points if someone can tell me how to also convert it back, ie, if I have a pure black and white image (purely [0,0,0] and [0,0,1] pixels), how do I get a 2D matrix of the same height-width dimensions but with True in place of white pixels ([1,1,1]) and False in place of black pixels ([0,0,0]).如果有人能告诉我如何将其转换回来,即如果我有一个纯黑白图像(纯 [0,0,0] 和 [0,0,1] 像素),我如何获得具有相同高度-宽度尺寸的二维矩阵,但用True代替白色像素 ([1,1,1]),用False代替黑色像素 ([0,0,0])。

The cheapest way is to view your bool data as np.uint8 , and add a fake dimension:最便宜的方法是将您的bool数据查看为np.uint8 ,并添加一个假维度:

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

Unlike 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.mask.astype(np.uint8)不同, mask.view(np.uint8)不复制数据,而是利用bool_存储在单个字节中的事实。 Similarly, the new dimension created by np.lib.stride_tricks.as_strided is a view which does not copy any data.同样,由np.lib.stride_tricks.as_strided创建的新维度是一个不复制任何数据的视图。

You can bypass as_strided and view by creating a new array object manually:您可以通过手动创建新数组 object来绕过as_stridedview

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

I think the clearest way is this:我认为最清晰的方法是:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM