计算图像和矢量的“点”积

2024-09-30 08:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算向量和图像与形状的点积:

  • (三)
  • (310801080)

输出应为(110801080)

img = torch.rand((3,1080,1080))
R_coefficient=float(0.2126)
G_coefficient=float(0.7152)
B_coefficient=float(0.0722)
Y = img[0,...]*R_coefficient + img[1,...]*G_coefficient img[2,...]*B_coefficient

上面的代码给出了我要查找的结果,但我想使用PyTorchutils,如torch.dottorch.matmul

我试过这些

TensorImage(torch.dot(img[:,...],RGB_vector[:]))
TensorImage(torch.matmul(img,RGB_vector[:]))

这两个选项给了我一个连接形状的错误,我拒绝了它们

RGB_vector = torch.tensor([[[0.2126, 0.7152, 0.0722]]], dtype=img.dtype).permute(2,1,0)
    #     torch.t(RGB_vector)
        print(RGB_vector.shape)
        print(img.shape)
        return TensorImage(img[:,...]*RGB_vector)#.unsqueeze_(0)

上面的这个示例可以工作,但是我得到的图像是shape(310801080),但是我需要在第一个形状的维度上得到1而不是3

当前工作示例

import torch
img = torch.rand((3,1080,1080))
RGB_vector = torch.tensor([[[0.2126, 0.7152, 0.0722]]], dtype=img.dtype).permute(2,1,0)
print(RGB_vector.shape)
print(img.shape)
TensorImage(img[:,...]*RGB_vector).unsqueeze_(0)

您好, DA


Tags: 图像imgrgbtorchfloatdot形状print
3条回答

谢谢你的回答,我已经处理了torch.einsum,最后看起来

import torch
img = torch.rand((3,1080,1080))
vec = torch.tensor([1, 2, 3]).t()
result = torch.einsum("i,ijk->jk", vec, img))

要尽可能少地修改示例,请执行以下操作:

import torch
img = torch.rand((3,1080,1080))
RGB_vector = torch.tensor([[[0.2126, 0.7152, 0.0722]]], dtype=img.dtype).permute(2,1,0)

return torch.mean(img * RGB_vector, axis=0).unsqueeze(0)

这将返回一个(110801080)张量

(这可以提供正确的形状,但我不确定这是否是您需要的)

第二个张量有dim>;当第一张量的最后一维等于第二张量的第二维时,2似乎起作用

v = torch.rand(3).unsqueeze(0)
m = torch.rand(3, 1080, 1080).transpose(0, 1)
r = torch.matmul(v, m).transpose(0, 1)

print(r.shape)
>>> torch.Size([1, 1080, 1080])

相关问题 更多 >

    热门问题