def test_ifft_and_scale_on_gridded_data(norm, multiprocessing): # problem definition x = shepp_logan_phantom().astype(np.complex64) grid_size = x.shape im_size = [im_dim // 2 for im_dim in grid_size] scaling_coeffs = np.random.randn(*im_size) + 1j * np.random.randn(*im_size) scaling_coeffs = scaling_coeffs.astype(np.complex64) # torch computations torch_x = np.stack((np.real(x), np.imag(x))) torch_x = torch.tensor(torch_x).unsqueeze(0).unsqueeze(0) torch_scaling_coeffs = torch.tensor( np.stack((np.real(scaling_coeffs), np.imag(scaling_coeffs)))) res_torch = torch_fft_functions.ifft_and_scale_on_gridded_data( torch_x, torch_scaling_coeffs, torch.tensor(grid_size).float(), torch.tensor(im_size), norm, ).numpy() res_torch = res_torch[:, :, 0] + 1j * res_torch[:, :, 1] # tf computations res_tf = tf_fft_functions.ifft_and_scale_on_gridded_data( tf.convert_to_tensor(x)[None, None, ...], tf.convert_to_tensor(scaling_coeffs), tf.convert_to_tensor(grid_size), tf.convert_to_tensor(im_size), norm, multiprocessing=multiprocessing, ).numpy() np.testing.assert_allclose(res_torch, res_tf, rtol=1e-4, atol=2)
def test_scale_and_fft_on_image_volume_3d(norm, multiprocessing): # problem definition x = shepp_logan_phantom().astype(np.complex64) x = _crop_center(x, 128, 128) x = x[None, ...] x = np.tile(x, [128, 1, 1]) im_size = x.shape scaling_coeffs = np.random.randn(*im_size) + 1j * np.random.randn(*im_size) scaling_coeffs = scaling_coeffs.astype(np.complex64) grid_size = [2 * im_dim for im_dim in im_size] # torch computations torch_x = np.stack((np.real(x), np.imag(x))) torch_x = torch.tensor(torch_x).unsqueeze(0).unsqueeze(0) torch_scaling_coeffs = torch.tensor( np.stack((np.real(scaling_coeffs), np.imag(scaling_coeffs)))) res_torch = torch_fft_functions.scale_and_fft_on_image_volume( torch_x, torch_scaling_coeffs, torch.tensor(grid_size).float(), torch.tensor(im_size), norm, ).numpy() res_torch = res_torch[:, :, 0] + 1j * res_torch[:, :, 1] # tf computations res_tf = tf_fft_functions.scale_and_fft_on_image_volume( tf.convert_to_tensor(x)[None, None, ...], tf.convert_to_tensor(scaling_coeffs), tf.convert_to_tensor(grid_size), tf.convert_to_tensor(im_size), norm, im_rank=3, multiprocessing=multiprocessing, ).numpy() np.testing.assert_allclose(res_torch, res_tf, rtol=1e-4, atol=2 * 1e-2)
def noisy_shepp_logan(noise_level=0.35, gray=True, channel=1): gt = resize(shepp_logan_phantom(), (512, 512)) noisy = gt + (np.random.rand(*gt.shape) - 0.5) * noise_level def FOCUS(x): return x[350:450, 200:300] return gt, noisy, FOCUS
def test_brain_rotation(self): # initialise a rotation matrix theta = math.pi / 2.0 # 90 degrees R1 = [math.cos(theta), -1.0 * math.sin(theta), 0.0] R2 = [math.sin(theta), math.cos(theta), 0.0] R3 = [0.0, 0.0, 1.0] R = torch.tensor([R1, R2, R3], device=device) # initialise a warp field transformation = identity_grid.permute([0, 4, 1, 2, 3]) for idx_z in range(transformation.shape[2]): for idx_y in range(transformation.shape[3]): for idx_x in range(transformation.shape[4]): p = transformation[0, :, idx_z, idx_y, idx_x] transformation[0, :, idx_z, idx_y, idx_x] = torch.mv(R, p) # load an image an warp it im_moving = np.expand_dims(shepp_logan_phantom(), axis=0) im_moving_arr = np.transpose(im_moving, (2, 1, 0)) padding = (max(im_moving_arr.shape) - np.asarray(im_moving_arr.shape)) // 2 padding = ((padding[0], padding[0]), (padding[1], padding[1]), (padding[2], padding[2])) im_moving_arr_padded = np.pad(im_moving_arr, padding, mode='minimum') im_moving_tensor = torch.from_numpy(im_moving_arr_padded).unsqueeze( 0).unsqueeze(0).float() im_moving = F.interpolate(im_moving_tensor, size=dims, mode='trilinear', align_corners=True) im_moving = rescale_im(im_moving).to(device) im_moving_warped = registration_module(im_moving, transformation) # save the images to disk save_im_to_disk(im_moving[0, 0].cpu().numpy(), './temp/test_output/brain_moving.nii.gz') save_im_to_disk(im_moving_warped[0, 0].cpu().numpy(), './temp/test_output/brain_moving_warped.nii.gz')
def forward_iradon(radon_image, theta=None, output_size=None, filter='ramp', interpolation='linear', circle=True): #image = imageGlobal image = shepp_logan_phantom() image = rescale(image, scale=0.4, mode='reflect', multichannel=False) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4.5)) ax1.set_title("Original") ax1.imshow(image, cmap=plt.cm.Greys_r) theta = np.linspace(0., 180., max(image.shape), endpoint=False) sinogram = radon(image, theta=theta, circle=True) ax2.set_title("Radon transform\n(Sinogram)") ax2.set_xlabel("Projection angle (deg)") ax2.set_ylabel("Projection position (pixels)") ax2.imshow(sinogram, cmap=plt.cm.Greys_r, extent=(0, 180, 0, sinogram.shape[0]), aspect='auto') fig.tight_layout() plt.show()
# Copyright of the Board of Trustees of Columbia University in the City of New York import unittest import matplotlib.pyplot as plt import numpy as np from skimage.data import shepp_logan_phantom from skimage.transform import resize from OCTOPUS.recon.imtransforms import im2ksp, ksp2im, nufft_init # Cartesian data N = 192 ph = resize(shepp_logan_phantom(), (N, N)).astype(complex) cart_ksp = np.fft.fftshift(np.fft.fft2(ph)) # Non-Cartesian data ktraj = np.load('test_data/ktraj_noncart.npy') ktraj_dcf = np.load('test_data/ktraj_noncart_dcf.npy').flatten() noncart_ksp = np.load('test_data/slph_noncart_ksp.npy') acq_params = { 'Npoints': ktraj.shape[0], 'Nshots': ktraj.shape[1], 'N': ph.shape[0], 'dcf': ktraj_dcf } class TestImageTransformation(unittest.TestCase): def test_im2ksp_cart(self): # Image to k-space transformation for Cartesian data
circle=False, filter_name='ramp' if ramp else None) return img_proj def plot_pair(img, N): img_proj_nofilt = radon_then_back_proj(img, N, ramp=False) img_proj_ramp = radon_then_back_proj(img, N, ramp=True) plt.figure(figsize=(15, 5)) plt.subplot(121) plt.imshow(img_proj_nofilt, cmap='gray') plt.title('No filter') plt.subplot(122) plt.imshow(img_proj_ramp, cmap='gray') plt.title('Ramp filter') plt.suptitle( f'Radon Transformed Then Back Projected Image with N = {N} Equally Spaced Angles' ) if __name__ == '__main__': img = data.shepp_logan_phantom() plt.figure() plt.imshow(img, cmap='gray') plt.title('Original Image') plot_pair(img, 4) plot_pair(img, 16) plot_pair(img, 64) plot_pair(img, 256) plt.show()
from matplotlib import pyplot as plt nVoxelX = 128 nVoxelY = 128 nMaterial = 2 nPixel = 182 nView = 90 nEnergy = 150 nChannel = 3 x_shape = [nMaterial, nVoxelX, nVoxelY] l_shape = [nEnergy, nPixel, nView] y_shape = [nPixel, nView] x0 = 2000e-6 * shepp_logan_phantom() x0 = resize(x0, [nVoxelX, nVoxelY]) x0 = tf.convert_to_tensor(x0, dtype=tf.float32) x1 = 10e-6 * aiaiTools.utils.RoiCircle2D( x_shape[1:], 50, 70, 10, dtype=tf.float32) x0 = tf.expand_dims(x0, 0) x1 = tf.expand_dims(x1, 0) x = tf.concat([x0, x1], 0) theta = np.linspace(0.0, 180.0, nView, endpoint=False, dtype=float) def FP(x): return radon(x, theta=theta, circle=False)
from numpy.fft import ifftshift import matplotlib.pyplot as plt from skimage.data import shepp_logan_phantom from skimage.transform import resize FFT = lambda x: fftshift(fft2(ifftshift(x))) IFFT = lambda x: fftshift(ifft2(ifftshift(x))) EPS = 1e-18 ## 1) Linearity # a*f(x) + b*g(x) <== Fourier Transform ==> a*FFT(f(x)) + b*FFT(g(x)) N = 512 X = shepp_logan_phantom() X = resize(X, (N, N), order=0) X_fft = FFT(X) X1 = X * (X > 0.95) * (X < 1.05) X2 = X * (X > 0.35) * (X < 0.45) X3 = X * (X > 0.25) * (X < 0.35) X4 = X * (X > 0.15) * (X < 0.25) X5 = X * (X > 0.05) * (X < 0.15) X0 = X1 + X2 + X3 + X4 + X5 X1_fft = FFT(X1) X2_fft = FFT(X2) X3_fft = FFT(X3) X4_fft = FFT(X4)
def numsim_cartesian(): N = 192 ph = resize(shepp_logan_phantom(), (N, N)) ph = ph.astype(complex) plt.imshow(np.abs(ph), cmap='gray') plt.title('Original phantom') plt.axis('off') plt.colorbar() plt.show() brain_mask = mask_by_threshold(ph) # Floodfill from point (0, 0) ph_holes = ~(flood_fill(brain_mask, (0, 0), 1).astype(int)) + 2 mask = brain_mask + ph_holes ## # Cartesian k-space trajectory ## dt = 10e-6 # grad raster time ktraj_cart = np.arange(0, N * dt, dt).reshape(1, N) ktraj_cart = np.tile(ktraj_cart, (N, 1)) plt.imshow(ktraj_cart, cmap='gray') plt.title('Cartesian trajectory') plt.show() ## # Simulated field map ## fmax_v = [1600, 3200, 4800] # Hz correspontig to 25, 50 and 75 ppm at 3T i = 0 or_corrupted = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_CPR = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_fsCPR = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_MFI = np.zeros((N, N, len(fmax_v)), dtype='complex') for fmax in fmax_v: field_map = fieldmap_sim.realistic(np.abs(ph), mask, fmax) plt.imshow(field_map, cmap='gray') plt.title('Field Map') plt.colorbar() plt.axis('off') plt.show() ## # Corrupted images ## or_corrupted[:, :, i], _ = ORC.add_or_CPR(ph, ktraj_cart, field_map) corrupt = (np.abs(or_corrupted[:, :, i]) - np.abs(or_corrupted[..., i]).min()) / ( np.abs(or_corrupted[:, :, i]).max() - np.abs(or_corrupted[..., i]).min()) #plt.imshow(np.abs(or_corrupted[:,:,i]),cmap='gray') plt.imshow(corrupt, cmap='gray') plt.colorbar() plt.title('Corrupted Image') plt.axis('off') plt.show() ### # Corrected images ### or_corrected_CPR[:, :, i] = ORC.CPR(or_corrupted[:, :, i], 'im', ktraj_cart, field_map) or_corrected_fsCPR[:, :, i] = ORC.fs_CPR(or_corrupted[:, :, i], 'im', ktraj_cart, field_map, 2) or_corrected_MFI[:, :, i] = ORC.MFI(or_corrupted[:, :, i], 'im', ktraj_cart, field_map, 2) i += 1 ## # Plot ## im_stack = np.stack( (np.squeeze(or_corrupted), np.squeeze(or_corrected_CPR), np.squeeze(or_corrected_fsCPR), np.squeeze(or_corrected_MFI))) cols = ('Corrupted Image', 'CPR Correction', 'fs-CPR Correction', 'MFI Correction') row_names = ('-/+ 1600 Hz', '-/+ 3200 Hz', '-/+ 4800 Hz') plot_correction_results(im_stack, cols, row_names)
plt.figure() plt.title(name) if image.ndim == 2: plt.imshow(image, cmap=plt.cm.gray) else: plt.imshow(image) plt.show() ############################################################################ # Thumbnail image for the gallery # sphinx_gallery_thumbnail_number = -1 fig, axs = plt.subplots(nrows=3, ncols=3) for ax in axs.flat: ax.axis("off") axs[0, 0].imshow(data.hubble_deep_field()) axs[0, 1].imshow(data.immunohistochemistry()) axs[0, 2].imshow(data.lily()) axs[1, 0].imshow(data.microaneurysms()) axs[1, 1].imshow(data.moon(), cmap=plt.cm.gray) axs[1, 2].imshow(data.retina()) axs[2, 0].imshow(data.shepp_logan_phantom(), cmap=plt.cm.gray) axs[2, 1].imshow(data.skin()) further_img = np.full((300, 300), 255) for xpos in [100, 150, 200]: further_img[150 - 10:150 + 10, xpos - 10:xpos + 10] = 0 axs[2, 2].imshow(further_img, cmap=plt.cm.gray) plt.subplots_adjust(wspace=-0.3, hspace=0.1)
Created on Thu Oct 15 00:41:11 2020 @author: admin """ from skimage.transform import iradon_sart import numpy as np import matplotlib.pyplot as plt from skimage.data import shepp_logan_phantom from skimage.transform import radon, rescale from skimage.transform import iradon from skimage.transform import resize image = shepp_logan_phantom() ss = [] sIs = [] recons = [] reconIs = [] for numViews in [360, 180, 90, 45, 20]: theta = np.linspace(0., 360., int(numViews), endpoint=False) s = radon(image, theta=theta, circle=True) recon = iradon(s, theta=theta, circle=True) recons.append(recon) ss.append(s) sI = resize(s, (s.shape[0], 360), anti_aliasing=True) sIs.append(sI) theta = np.linspace(0., 360., 360, endpoint=False) reconI = iradon(sI, theta=theta, circle=True)
def main(): dtype = torch.double spokelength = 512 targ_size = (int(spokelength/2), int(spokelength/2)) nspokes = 405 image = shepp_logan_phantom().astype(np.complex) im_size = image.shape grid_size = tuple(2 * np.array(im_size)) # convert the phantom to a tensor and unsqueeze coil and batch dimension image = np.stack((np.real(image), np.imag(image))) image = torch.tensor(image).to(dtype).unsqueeze(0).unsqueeze(0) # create k-space trajectory ga = np.deg2rad(180 / ((1 + np.sqrt(5)) / 2)) kx = np.zeros(shape=(spokelength, nspokes)) ky = np.zeros(shape=(spokelength, nspokes)) kmax = np.pi * ((spokelength/2) / im_size[0]) ky[:, 0] = np.linspace(-kmax, kmax, spokelength) for i in range(1, nspokes): kx[:, i] = np.cos(ga) * kx[:, i - 1] - np.sin(ga) * ky[:, i - 1] ky[:, i] = np.sin(ga) * kx[:, i - 1] + np.cos(ga) * ky[:, i - 1] ky = np.transpose(ky) kx = np.transpose(kx) ktraj = np.stack((ky.flatten(), kx.flatten()), axis=0) ktraj = torch.tensor(ktraj).to(dtype).unsqueeze(0) # sensitivity maps ncoil = 8 smap = np.absolute(np.stack(mrisensesim( im_size, coil_width=64))).astype(np.complex) smap = np.stack((np.real(smap), np.imag(smap)), axis=1) smap = torch.tensor(smap).to(dtype).unsqueeze(0) # operators sensenufft_ob = MriSenseNufft( smap=smap, im_size=im_size, grid_size=grid_size).to(dtype) kdata = sensenufft_ob(image, ktraj) kdata = np.squeeze(kdata.numpy()) kdata = np.reshape(kdata[:, 0] + 1j*kdata[:, 1], (ncoil, nspokes, spokelength)) ktraj = np.squeeze(ktraj.numpy()) ktraj = ktraj / np.max(ktraj) * np.pi ktraj = np.reshape(ktraj, (2, nspokes, spokelength)) smap = np.squeeze(smap.numpy()) smap = smap[:, 0] + 1j*smap[:, 1] smap_new = [] for coilind in range(smap.shape[0]): smap_new.append( resize(np.real(smap[coilind]), targ_size) + 1j*resize(np.imag(smap[coilind]), targ_size) ) smap_new = np.array(smap_new) data = { 'kdata': kdata, 'ktraj': ktraj, 'smap': smap_new } sio.savemat('demo_data.mat', data)
def numsim_epi(): ## # Original image: Shep-Logan Phantom ## N = 128 FOV = 256e-3 ph = resize(shepp_logan_phantom(), (N, N)) #.astype(complex) plt.imshow(np.abs(ph), cmap='gray') plt.title('Original phantom') plt.axis('off') plt.colorbar() plt.show() brain_mask = mask_by_threshold(ph) # Floodfill from point (0, 0) ph_holes = ~(flood_fill(brain_mask, (0, 0), 1).astype(int)) + 2 mask = brain_mask + ph_holes ## # EPI k-space trajectory ## dt = 4e-6 ktraj = ssEPI_2d(N, FOV) # k-space trajectory plt.plot(ktraj[:, 0], ktraj[:, 1]) plt.title('EPI trajectory') plt.show() Ta = ktraj.shape[0] * dt T = (np.arange(ktraj.shape[0]) * dt).reshape(ktraj.shape[0], 1) seq_params = { 'N': N, 'Npoints': ktraj.shape[0], 'Nshots': 1, 't_readout': Ta, 't_vector': T } ## # Simulated field map ## # fmax_v = [50, 75, 100] # Hz fmax_v = [100, 150, 200] i = 0 or_corrupted = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_CPR = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_fsCPR = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_MFI = np.zeros((N, N, len(fmax_v)), dtype='complex') for fmax in fmax_v: # field_map = fieldmap_sim.realistic(np.abs(ph), mask, fmax) SL_smooth = gaussian(ph, sigma=3) field_map = cv2.normalize(SL_smooth, None, -fmax, fmax, cv2.NORM_MINMAX) field_map = np.round(field_map * mask) field_map[np.where(field_map == -0.0)] = 0 plt.imshow(field_map, cmap='gray') plt.title('Field Map +/-' + str(fmax) + ' Hz') plt.colorbar() plt.axis('off') plt.show() ## # Corrupted images ## or_corrupted[:, :, i], EPI_ksp = ORC.add_or_CPR(ph, ktraj, field_map, 'EPI', seq_params) corrupt = (np.abs(or_corrupted[:, :, i]) - np.abs(or_corrupted[..., i]).min()) / ( np.abs(or_corrupted[:, :, i]).max() - np.abs(or_corrupted[..., i]).min()) # plt.imshow(np.abs(or_corrupted[:,:,i]),cmap='gray') plt.imshow(corrupt, cmap='gray') plt.colorbar() plt.title('Corrupted Image') plt.axis('off') plt.show() ### # Corrected images ### or_corrected_CPR[:, :, i] = ORC.correct_from_kdat('CPR', EPI_ksp, ktraj, field_map, seq_params, 'EPI') or_corrected_fsCPR[:, :, i] = ORC.correct_from_kdat('fsCPR', EPI_ksp, ktraj, field_map, seq_params, 'EPI') or_corrected_MFI[:, :, i] = ORC.correct_from_kdat('MFI', EPI_ksp, ktraj, field_map, seq_params, 'EPI') # or_corrected_CPR[:, :, i] = ORC.CPR(or_corrupted[:, :, i], 'im', ktraj, field_map, 'EPI', seq_params) # # or_corrected_fsCPR[:, :, i] = ORC.fs_CPR(or_corrupted[:, :, i], 'im', ktraj, field_map, 2, 'EPI', seq_params) # # or_corrected_MFI[:, :, i] = ORC.MFI(or_corrupted[:, :, i], 'im', ktraj, field_map, 2, 'EPI', seq_params) i += 1 ## # Plot ## im_stack = np.stack( (np.squeeze(or_corrupted), np.squeeze(or_corrected_CPR), np.squeeze(or_corrected_fsCPR), np.squeeze(or_corrected_MFI))) # np.save('im_stack.npy',im_stack) cols = ('Corrupted Image', 'CPR Correction', 'fs-CPR Correction', 'MFI Correction') row_names = ('-/+ 100 Hz', '-/+ 150 Hz', '-/+ 200 Hz') plot_correction_results(im_stack, cols, row_names)
def numsim_spiral(): N = 128 # ph.shape[0] ph = resize(shepp_logan_phantom(), (N, N)) #.astype(complex) plt.imshow(np.abs(ph), cmap='gray') plt.title('Original phantom') plt.axis('off') plt.colorbar() plt.show() brain_mask = mask_by_threshold(ph) # Floodfill from point (0, 0) ph_holes = ~(flood_fill(brain_mask, (0, 0), 1).astype(int)) + 2 mask = brain_mask + ph_holes ## # Spiral k-space trajectory ## dt = 4e-6 ktraj = np.load('sample_data/SS_sprial_ktraj.npy') # k-space trajectory plt.plot(ktraj.real, ktraj.imag) plt.title('Spiral trajectory') plt.show() #ktraj_dcf = np.load('test_data/ktraj_noncart_dcf.npy').flatten() # density compensation factor t_ro = ktraj.shape[0] * dt T = (np.arange(ktraj.shape[0]) * dt).reshape(ktraj.shape[0], 1) seq_params = { 'N': ph.shape[0], 'Npoints': ktraj.shape[0], 'Nshots': ktraj.shape[1], 't_readout': t_ro, 't_vector': T } #, 'dcf': ktraj_dcf} ## # Simulated field map ## fmax_v = [100, 150, 200] # Hz i = 0 or_corrupted = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_CPR = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_fsCPR = np.zeros((N, N, len(fmax_v)), dtype='complex') or_corrected_MFI = np.zeros((N, N, len(fmax_v)), dtype='complex') for fmax in fmax_v: SL_smooth = gaussian(ph, sigma=3) field_map = cv2.normalize(SL_smooth, None, -fmax, fmax, cv2.NORM_MINMAX) field_map = np.round(field_map * mask) field_map[np.where(field_map == -0.0)] = 0 ### plt.imshow(field_map, cmap='gray') plt.title('Field Map +/-' + str(fmax) + ' Hz') plt.colorbar() plt.axis('off') plt.show() ## # Corrupted images ## or_corrupted[:, :, i], ksp_corrupted = ORC.add_or_CPR( ph, ktraj, field_map, 1, seq_params) corrupt = (np.abs(or_corrupted[:, :, i]) - np.abs(or_corrupted[..., i]).min()) / ( np.abs(or_corrupted[:, :, i]).max() - np.abs(or_corrupted[..., i]).min()) #plt.imshow(np.abs(or_corrupted[:,:,i]),cmap='gray') plt.imshow(corrupt, cmap='gray') plt.colorbar() plt.title('Corrupted Image') plt.axis('off') plt.show() ### # Corrected images ### or_corrected_CPR[:, :, i] = ORC.correct_from_kdat('CPR', ksp_corrupted, ktraj, field_map, seq_params, 1) or_corrected_fsCPR[:, :, i] = ORC.correct_from_kdat('fsCPR', ksp_corrupted, ktraj, field_map, seq_params, 1) or_corrected_MFI[:, :, i] = ORC.correct_from_kdat('MFI', ksp_corrupted, ktraj, field_map, seq_params, 1) # or_corrected_CPR[:, :, i] = ORC.CPR(or_corrupted[:, :, i], 'im', ktraj, field_map, 1, seq_params) # # or_corrected_fsCPR[:, :, i] = ORC.fs_CPR(or_corrupted[:, :, i], 'im', ktraj, field_map, 2, 1, seq_params) # # or_corrected_MFI[:,:,i] = ORC.MFI(or_corrupted[:,:,i], 'im', ktraj, field_map, 2, 1, seq_params) i += 1 ## # Plot ## im_stack = np.stack( (np.squeeze(or_corrupted), np.squeeze(or_corrected_CPR), np.squeeze(or_corrected_fsCPR), np.squeeze(or_corrected_MFI))) #np.save('im_stack.npy',im_stack) cols = ('Corrupted Image', 'CPR Correction', 'fs-CPR Correction', 'MFI Correction') row_names = ('-/+ 100 Hz', '-/+ 150 Hz', '-/+ 200 Hz') plot_correction_results(im_stack, cols, row_names)
import itertools import numpy as np import pytest from skimage._shared._warnings import expected_warnings from skimage._shared.testing import test_parallel from skimage._shared.utils import _supported_float_type, convert_to_float from skimage.data import shepp_logan_phantom from skimage.transform import radon, iradon, iradon_sart, rescale PHANTOM = shepp_logan_phantom()[::2, ::2] PHANTOM = rescale(PHANTOM, 0.5, order=1, mode='constant', anti_aliasing=False, channel_axis=None) def _debug_plot(original, result, sinogram=None): from matplotlib import pyplot as plt imkwargs = dict(cmap='gray', interpolation='nearest') if sinogram is None: plt.figure(figsize=(15, 6)) sp = 130 else: plt.figure(figsize=(11, 11)) sp = 221 plt.subplot(sp + 0) plt.imshow(sinogram, aspect='auto', **imkwargs)
the Radon transform, we need to decide how many projection angles we wish to use. As a rule of thumb, the number of projections should be about the same as the number of pixels there are across the object (to see why this is so, consider how many unknown pixel values must be determined in the reconstruction process and compare this to the number of measurements provided by the projections), and we follow that rule here. Below is the original image and its Radon transform, often known as its *sinogram*: """ import numpy as np import matplotlib.pyplot as plt from skimage.data import shepp_logan_phantom from skimage.transform import radon, rescale image = shepp_logan_phantom() image = rescale(image, scale=0.4, mode='reflect', channel_axis=None) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4.5)) ax1.set_title("Original") ax1.imshow(image, cmap=plt.cm.Greys_r) theta = np.linspace(0., 180., max(image.shape), endpoint=False) sinogram = radon(image, theta=theta) dx, dy = 0.5 * 180.0 / max(image.shape), 0.5 / sinogram.shape[0] ax2.set_title("Radon transform\n(Sinogram)") ax2.set_xlabel("Projection angle (deg)") ax2.set_ylabel("Projection position (pixels)") ax2.imshow(sinogram, cmap=plt.cm.Greys_r,
# import matplotlib.pyplot as plt # # from skimage.util import img_as_ubyte # # from skimage import io from skimage.morphology import erosion, dilation # # from skimage.morphology import black_tophat, skeletonize, convex_hull_image from skimage.morphology import disk # from PIL import Image # import numpy as np # from skimage.util import img_as_ubyte import matplotlib.pyplot as plt from skimage import data from skimage.util import img_as_ubyte # from skimage import io orig_phantom = img_as_ubyte(data.shepp_logan_phantom()) fig, ax = plt.subplots() ax.imshow(orig_phantom, cmap=plt.cm.gray) def plot_comparison(original, filtered, filter_name): fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4), sharex=True, sharey=True) ax1.imshow(original, cmap=plt.cm.gray) ax1.set_title('original') ax1.axis('off') ax2.imshow(filtered, cmap=plt.cm.gray) ax2.set_title(filter_name)