spatial transformer network (STN)

1.F.affine_grid
作用: 根据仿射变换矩阵,生成该变换相对应的逐像素偏移矩阵;
输入:theta:尺寸为(batch_size,2,3)的矩阵,表示每张图像的仿射变换矩阵
size:输出图像的尺寸
输出:根据theta变化得到的逐像素偏移矩阵

2.F.grid_sample 则是根据这个偏移矩阵将原始图片逐像素扭曲warp到目标位置处形成一个新的图片。
输入:img:要warp的图像
grid:逐像素偏移矩阵
输出:偏移后的图像

例子:

#将图像扭转45度
img = ToTensor()(img).unsqueeze(0)  # img→tensor 3维→4维
M = torch.tensor(                   # 仿射变换矩阵
    [[[0.7071, -0.7071, 0],
      [0.7071, 0.7071, 0]]]
)
grid = F.affine_grid(M, size=(1, 3, 500, 500))
warp_img = F.grid_sample(img, grid)             # 扭转图片
tensor_to_pil = ToPILImage()                    # tensor→img
tensor_to_pil(warp_img.data.squeeze(0)).show()  # 4维→3维
根据指定角度扭转图像
#feature.size()[0]就是batch size
            theta = torch.zeros((feature.size()[0], 2, 3), requires_grad=False, device=feature.device)
            with torch.no_grad():
                # 指定要旋转的角度
                angle = rotate_angle * math.pi / 180.0          
                #计算放射变换矩阵theta   
                theta[:, 0, 0] = torch.tensor(math.cos(angle), requires_grad=False, device=feature.device)
                theta[:, 0, 1] = torch.tensor(math.sin(-angle), requires_grad=False, device=feature.device)
                theta[:, 1, 0] = torch.tensor(math.sin(angle), requires_grad=False, device=feature.device)
                theta[:, 1, 1] = torch.tensor(math.cos(angle), requires_grad=False, device=feature.device)
			#根据放射变换矩阵得到逐像素偏移矩阵
            grid = F.affine_grid(theta, feature.size())
            #根据这个偏移矩阵将原始图片逐像素扭曲warp到目标位置处形成一个新的图片
            transformed_feature = F.grid_sample(feature, grid).to(feature.device)

STN可以参考blibli的李宏毅的教学

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值