在PyTorch中新增重投影誤差(Reprojection Error)作為損失函式通常用於計算機視覺任務,特別是涉及多檢視幾何(如立體視覺或多視角重建)的問題。重投影誤差衡量了3D點在投影到不同視角後的影像平面上的偏差。以下是如何在PyTorch中實現和使用重投影誤差作為損失函式的步驟:
定義重投影誤差函式:
重投影誤差通常是2D影像點的實際位置與透過投影矩陣計算得到的預測位置之間的距離。
實現損失函式:
使用PyTorch的操作來計算重投影誤差,並將其封裝在一個損失函式中。
假設你有以下變數:
points_3d: 原始的3D點,形狀為 (N, 3)
camera_matrix: 相機的內參矩陣,形狀為 (3, 3)
extrinsics: 相機的外參矩陣,形狀為 (3, 4)
points_2d: 實際2D影像點,形狀為 (N, 2)
以下是一個簡單的示例程式碼:
import torch import torch.nn as nn import torch.nn.functional as F class ReprojectionLoss(nn.Module): def __init__(self): super(ReprojectionLoss, self).__init__() def forward(self, points_3d, points_2d, camera_matrix, extrinsics): # 新增一個列 [1] 到 3D 點的末尾 (N, 3) -> (N, 4) ones = torch.ones(points_3d.shape[0], 1, device=points_3d.device) points_3d_h = torch.cat([points_3d, ones], dim=1) # (N, 4) # 計算投影點 projected_points_2d_h = camera_matrix @ extrinsics @ points_3d_h.T # (3, N) projected_points_2d = projected_points_2d_h[:2] / projected_points_2d_h[2] # 歸一化 (2, N) projected_points_2d = projected_points_2d.T # (N, 2) # 計算重投影誤差 (實際2D點和預測2D點之間的距離) reprojection_error = torch.norm(points_2d - projected_points_2d, dim=1) # (N,) # 返回平均誤差作為損失 return reprojection_error.mean() # 示例資料 points_3d = torch.rand((10, 3), requires_grad=True) points_2d = torch.rand((10, 2)) camera_matrix = torch.eye(3) extrinsics = torch.cat([torch.eye(3), torch.zeros(3, 1)], dim=1) # 例項化並計算損失 loss_fn = ReprojectionLoss() loss = loss_fn(points_3d, points_2d, camera_matrix, extrinsics) print("Loss:", loss.item()) # 使用最佳化器最小化損失 optimizer = torch.optim.Adam([points_3d], lr=0.01) optimizer.zero_grad() loss.backward() optimizer.step()
在這個示例中,我們定義了一個自定義的損失函式 ReprojectionLoss,計算了實際2D點和預測2D點之間的歐幾里得距離作為重投影誤差,並返回平均誤差作為損失。在訓練過程中,你可以使用這個損失函式來更新你的模型引數。、
可以將結構相似性指數(SSIM)損失與重投影誤差結合起來作為總損失函式。在此示例中,我們將兩者的權重設定為50%,即兩者各佔50%的權重。你可以使用PyTorch實現SSIM損失。
首先,我們需要實現或引入SSIM損失函式。然後,我們可以將兩個損失結合起來進行訓練。
實現SSIM損失函式
下面是一個簡單的SSIM損失實現:
import torch import torch.nn.functional as F import numpy as np class SSIMLoss(nn.Module): def __init__(self, window_size=11, size_average=True): super(SSIMLoss, self).__init__() self.window_size = window_size self.size_average = size_average self.channel = 1 self.window = self.create_window(window_size, self.channel) def create_window(self, window_size, channel): def gaussian(window_size, sigma): gauss = torch.Tensor( [np.exp(-(x - window_size // 2)**2 / float(2 * sigma**2)) for x in range(window_size)]) return gauss / gauss.sum() _1D_window = gaussian(window_size, 1.5).unsqueeze(1) _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) window = _2D_window.expand(channel, 1, window_size, window_size).contiguous() return window def _ssim(self, img1, img2, window, window_size, channel, size_average=True): mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel) mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel) mu1_sq = mu1.pow(2) mu2_sq = mu2.pow(2) mu1_mu2 = mu1 * mu2 sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2 C1 = 0.01 ** 2 C2 = 0.03 ** 2 ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)) if size_average: return ssim_map.mean() else: return ssim_map.mean(1).mean(1).mean(1) def forward(self, img1, img2): (_, channel, _, _) = img1.size() window = self.window.type_as(img1) return 1 - self._ssim(img1, img2, window, self.window_size, channel, self.size_average)
結合兩種損失函式
假設你有以下變數:
images_pred: 預測的影像
images_gt: 真實影像
我們可以將SSIM損失和重投影誤差結合起來:
import torch import torch.nn as nn class CombinedLoss(nn.Module): def __init__(self, reprojection_loss_weight=0.5, ssim_loss_weight=0.5): super(CombinedLoss, self).__init__() self.reprojection_loss_weight = reprojection_loss_weight self.ssim_loss_weight = ssim_loss_weight self.reprojection_loss_fn = ReprojectionLoss() self.ssim_loss_fn = SSIMLoss() def forward(self, points_3d, points_2d, camera_matrix, extrinsics, images_pred, images_gt): reprojection_loss = self.reprojection_loss_fn(points_3d, points_2d, camera_matrix, extrinsics) ssim_loss = self.ssim_loss_fn(images_pred, images_gt) combined_loss = (self.reprojection_loss_weight * reprojection_loss + self.ssim_loss_weight * ssim_loss) return combined_loss # 示例資料 points_3d = torch.rand((10, 3), requires_grad=True) points_2d = torch.rand((10, 2)) camera_matrix = torch.eye(3) extrinsics = torch.cat([torch.eye(3), torch.zeros(3, 1)], dim=1) images_pred = torch.rand((1, 1, 256, 256), requires_grad=True) images_gt = torch.rand((1, 1, 256, 256)) # 例項化並計算損失 combined_loss_fn = CombinedLoss() loss = combined_loss_fn(points_3d, points_2d, camera_matrix, extrinsics, images_pred, images_gt) print("Combined Loss:", loss.item()) # 使用最佳化器最小化損失 optimizer = torch.optim.Adam([points_3d, images_pred], lr=0.01) optimizer.zero_grad() loss.backward() optimizer.step()
在這個示例中,我們定義了一個 CombinedLoss 類,它結合了重投影誤差和SSIM損失。然後,我們使用這個組合損失函式來計算總損失,並用最佳化器最小化損失。你可以根據需要調整重投影誤差和SSIM損失的權重。