def test_resample(self, input_param, input_data, expected_val): warp_layer = Warp(**input_param) result = warp_layer(**input_data) np.testing.assert_allclose(result.cpu().numpy(), expected_val.cpu().numpy(), rtol=1e-4, atol=1e-4)
def test_grad(self): for b in GridSampleMode: for p in GridSamplePadMode: warp_layer = Warp(mode=b.value, padding_mode=p.value) input_image = torch.rand( (2, 3, 20, 20), dtype=torch.float64) * 10.0 ddf = torch.rand((2, 2, 20, 20), dtype=torch.float64) * 2.0 input_image.requires_grad = True ddf.requires_grad = False # Jacobian mismatch for output 0 with respect to input 1 gradcheck(warp_layer, (input_image, ddf), atol=1e-2, eps=1e-2)
def test_ill_shape(self): warp_layer = Warp(spatial_dims=2) with self.assertRaisesRegex(ValueError, ""): warp_layer( image=torch.arange(4).reshape((1, 1, 1, 2, 2)).to(dtype=torch.float), ddf=torch.zeros(1, 2, 2, 2) ) with self.assertRaisesRegex(ValueError, ""): warp_layer( image=torch.arange(4).reshape((1, 1, 2, 2)).to(dtype=torch.float), ddf=torch.zeros(1, 2, 1, 2, 2) ) with self.assertRaisesRegex(ValueError, ""): warp_layer(image=torch.arange(4).reshape((1, 1, 2, 2)).to(dtype=torch.float), ddf=torch.zeros(1, 2, 3, 3))
def monai_warp(img, ddf): """ warp with MONAI Args: img: numpy array of shape (D, H, W) ddf: numpy array of shape (3, D, H, W) Returns: warped_img: numpy arrap of shape (D, H, W) """ warp_layer = Warp(padding_mode="zeros") # turn to tensor and add channel dim monai_img = torch.tensor(img).unsqueeze(0) ddf = torch.tensor(ddf) # img -> batch -> img warped_img = warp_layer(monai_img.unsqueeze(0), ddf.unsqueeze(0)).squeeze(0) # remove channel dim warped_img = np.asarray(warped_img.squeeze(0)) return warped_img
def test_ill_opts(self): with self.assertRaisesRegex(ValueError, ""): Warp(spatial_dims=4)