将部分numpy数组复制到另一个具有额外维度的数组

Copying parts of numpy array to another array with extra dimension

我正在尝试使用机器学习进行语义分割,我设法找到了一种方法来获得正确的热编码(使用这个:https://www.jeremyjordan.me/semantic-segmentation/)但是我获得的代码非常糟糕而且我我确信 numpy 具有可以提供更优雅解决方案的功能。

想法如下:从一个标签数组 (88,240,240) 创建一个新数组 (88,240,240,3),每个通道中都有适当的值。

我想到了这个:

def data_reshape(train_image_list, train_label_list, img_size):
    temp = np.empty(shape=[train_label_list.shape[0], img_size[1], img_size[0], 3])
    temp[:,:,:,0] = train_label_list
    temp[temp[:,:,:,0] > 0] = 2
    temp[temp[:,:,:,0] == 0] = 1
    temp[temp[:,:,:,0] == 2] = 0

    temp[:,:,:,1] = train_label_list
    temp[temp[:,:,:,1] == 2] = 0

    temp[:,:,:,2] = train_label_list
    temp[temp[:,:,:,2] < 2] = 0
    temp[temp[:,:,:,2] == 2] = 1
    train_image_list = np.reshape(train_image_list, newshape=[-1, img_size[1], img_size[0], 1])
    train_label_list = np.reshape(temp, newshape=[-1, img_size[1], img_size[0], 3])

    return train_image_list, train_label_list

编辑:

它实际上没有 运行 它应该

我会重新制定:

我有一个 numpy 数组:(88,240,240),其中包含 88 张图像中每张图像上 3 个不同标签的信息(0 代表 label_0 的像素,1 代表 label_1 的像素,2 代表label_2).

的像素

我想用一个 numpy 数组从我的函数中出来,该数组还有 3 个通道,每个通道包含不同的信息:

有人有什么建议吗?

亲切的问候,

Unic0

train_label_list 的值为 0、1、2,您希望将其扩展为 3 个通道。那正确吗?

temp = np.zeros(shape=[train_label_list.shape[0], img_size[1], img_size[0], 3])
temp[:, :, :, 0] = train_label_list == 0
temp[:, :, :, 1] = train_label_list == 1
temp[:, :, :, 2] = train_label_list == 2

这应该可以解决问题。