NumPy + PyTorch 张量赋值
NumPy + PyTorch Tensor assignment
假设我们有一个 tensor
表示形状为 (910, 270, 1)
的图像,它为宽度 = 910 和高度 = 270 的每个像素分配了一个数字(某个索引)。
我们还有一个大小为 (N, 3)
的 numpy
数组,它将一个 3 元组映射到一个索引。
我现在想创建一个新的形状为 (920, 270, 3)
的 numpy 数组,它有一个基于原始张量索引和 mapping-3-tuple-numpy 数组的三元组。我如何在没有 for 循环和其他消耗迭代的情况下执行此分配?
这看起来像:
color_image = np.zeros((self._w, self._h, 3), dtype=np.int32)
self._colors = np.array(N,3) # this is already present
indexed_image = torch.tensor(920,270,1) # this is already present
#how do I assign it to this numpy array?
color_image[indexed_image.w, indexed_image.h] = self._colors[indexed_image.flatten()]
假设您有 _colors
和 indexed_image
。类似于:
>>> indexed_image = torch.randint(0, 10, (920, 270, 1))
>>> _colors = np.random.randint(0, 255, (N, 3))
将密集图转换为 RGB 图的一种常见方法是遍历标签集:
>>> _colors = torch.FloatTensor(_colors)
>>> rgb = torch.zeros(indexed_image.shape[:-1] + (3,))
>>> for lbl in range(N):
... rgb[lbl == indexed_image[...,0]] = _colors[lbl]
假设我们有一个 tensor
表示形状为 (910, 270, 1)
的图像,它为宽度 = 910 和高度 = 270 的每个像素分配了一个数字(某个索引)。
我们还有一个大小为 (N, 3)
的 numpy
数组,它将一个 3 元组映射到一个索引。
我现在想创建一个新的形状为 (920, 270, 3)
的 numpy 数组,它有一个基于原始张量索引和 mapping-3-tuple-numpy 数组的三元组。我如何在没有 for 循环和其他消耗迭代的情况下执行此分配?
这看起来像:
color_image = np.zeros((self._w, self._h, 3), dtype=np.int32)
self._colors = np.array(N,3) # this is already present
indexed_image = torch.tensor(920,270,1) # this is already present
#how do I assign it to this numpy array?
color_image[indexed_image.w, indexed_image.h] = self._colors[indexed_image.flatten()]
假设您有 _colors
和 indexed_image
。类似于:
>>> indexed_image = torch.randint(0, 10, (920, 270, 1))
>>> _colors = np.random.randint(0, 255, (N, 3))
将密集图转换为 RGB 图的一种常见方法是遍历标签集:
>>> _colors = torch.FloatTensor(_colors)
>>> rgb = torch.zeros(indexed_image.shape[:-1] + (3,))
>>> for lbl in range(N):
... rgb[lbl == indexed_image[...,0]] = _colors[lbl]