Radon变换的旋转过程可以使用ndimage.rotate()对图像进行特定角度的旋转,但这个过程比较耗时,不利于投影角度较多或者需要对批量图像进行Radon变换的情况。而通过利用PyTorch中的仿射变换相关函数affine_grid()和grid_sample()也可以实现旋转的过程,可以在GPU上进行运算,Radon变换所需的时间大幅减少。
from scipy import ndimage
import numpy as np
import matplotlib.pyplot as plt
import imageio
from cv2 import cv2
import torch
import torchvision.transforms as transforms
from torch.nn import functional as F
import math
def DiscreteRadonTransform(image, viewnum, batchSize):
# image: batchSize*imgSize*imgSize
channels = len(image[0])
res = torch.zeros((channels, viewnum))
res = res.cuda()
for s in range(viewnum):
angle = -math.pi - 180/viewnum*(s+1) * math.pi / 180
A = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
theta = np.array([[A[0, 0], A[0, 1], 0], [A[1, 0], A[1, 1], 0]])
theta = torch.from_numpy(theta).type(torch.FloatTensor)
theta = theta.unsqueeze(0)
theta = theta.cuda()
image_temp = torch.from_numpy(image).type(torch.FloatTensor)
image_temp = image_temp.unsqueeze(1)
image_temp = image_temp.cuda()
theta = theta.repeat(batchSize,1,1)
grid = F.affine_grid(theta, torch.Size((batchSize,1,512,512)))
rotation = F.grid_sample(image_temp, grid)
rotation = torch.squeeze(rotation)
res[:,s] = torch.sum(rotation,dim=0)
return res