def test_constructor5(self): bx = [3,2,5,1,2] by = [8,5,23,8,4,3] bz = None with self.assertRaises(RuntimeError): phantom.phantom(bx, by, bz)
def showPhantom(self, value): size = int(value) self.phantomSize = size img = phantom(size) img = img * 255 self.img = img self.PD = img self.T1 = phantom(size, 'T1') self.T2 = phantom(size, 'T2') self.originalPhantom = img self.pixelsClicked = [(0, 0), [0, 0], [0, 0]] self.showPhantomImage()
def test_solver_cpu(): ''' Test the coil decomposition method ''' import phantom N = 256 a = phantom.phantom(N).astype(numpy.complex64) # a += numpy.random.randn(256,256) + 1j*numpy.random.randn(256,256) # a = scipy.misc.ascent() n_coil = 8 coil_sensitivity = create_fake_coils(N, n_coil) # tuple multi_image = apply_coil_sensitivities(a, coil_sensitivity) # tuple # multi_image = remove_low_frequency_phase(multi_image) result_coil_sensitivity =image2coilprofile(multi_image) print(type(result_coil_sensitivity)) # A = svd_coil_sense(multi_image) for pp in range(0,n_coil): matplotlib.pyplot.subplot(6,4,pp+1) matplotlib.pyplot.imshow(result_coil_sensitivity[pp][...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.subplot(6,4,pp+9) matplotlib.pyplot.imshow(multi_image[pp][...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.subplot(6,4,pp+17) matplotlib.pyplot.imshow(coil_sensitivity[pp][...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.show()
def showPhantom(self, value): size = int(value) self.phantomSize = size img = phantom(size) img = img * 255 self.img = img self.originalPhantom = img self.showPhantomImage()
def test_constructor1(self): bx = [1,2,3,4,5] by = [3,2,5,1,6] bz = [8,5,23,9,4,3] ph = phantom.phantom(bx, by, bz) self.assertTrue(phandim.phandim.check_sorted(ph.bx())) self.assertTrue(phandim.phandim.check_sorted(ph.by())) self.assertTrue(phandim.phandim.check_sorted(ph.bz()))
def gen_projs(image, a_min = 0, a_max = 180, a_inc = 1, size = 512): if image == 'phantom': image = phantom.phantom (size) else: image = pim.imread(image) angle = np.arange (a_min, a_max, a_inc) projections = pb.radon (image, angle) return projections
def test_access1(self): bx = [3,2,5,1,2] by = [8,5,23,8,4,3] bz = [8,5,23,9,4,3,90] ph = phantom.phantom(bx, by, bz) self.assertTrue( ph.nx() == len(bx)-1 ) self.assertTrue( ph.ny() == len(by)-1 ) self.assertTrue( ph.nz() == len(bz)-1 )
def test_tensor(): ''' Test the coil decomposition method ''' import phantom N = 256 a = phantom.phantom(N).astype(numpy.complex64) # a += numpy.random.randn(256,256) + 1j*numpy.random.randn(256,256) # a = scipy.misc.ascent() n_coil = 8 coil_sensitivity = create_fake_coils(N, n_coil) # tuple multi_image = apply_coil_sensitivities(a, coil_sensitivity) # tuple import Nd_tensor coil_array = numpy.empty((N, N, n_coil), dtype=numpy.complex) for pp in range(0, n_coil): coil_array[:, :, pp] = multi_image[pp] # multi_image = remove_low_frequency_phase(multi_image) # result_coil_sensitivity =image2coilprofile2(multi_image) sos = numpy.sum(coil_array**2, 2)**0.5 for pp in range(0, n_coil): coil_array[:, :, pp] /= sos H = Nd_tensor.htensor() H.factorise(coil_array, (5, 5, n_coil)) core = H.dot(coil_array) core[numpy.abs(core) < 0.5] = 0 recovered = H.adjoint(core) # sos = numpy.sum(recovered**2, 2) result_coil_sensitivity = () for pp in range(0, n_coil): result_coil_sensitivity += (recovered[:, :, pp], ) print(type(result_coil_sensitivity)) # A = svd_coil_sense(multi_image) for pp in range(0, n_coil): matplotlib.pyplot.subplot(6, 4, pp + 1) matplotlib.pyplot.imshow(result_coil_sensitivity[pp][...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.subplot(6, 4, pp + 9) matplotlib.pyplot.imshow(multi_image[pp][...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.subplot(6, 4, pp + 17) matplotlib.pyplot.imshow(coil_sensitivity[pp][...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.show()
import phantom import astra import numpy as np import os nd = 256 na = 32 # Create ASTRA geometries vol_geom = astra.create_vol_geom(nd,nd) proj_geom = astra.create_proj_geom('parallel',1.0,nd,np.linspace(0,np.pi,na,False)) pi = astra.create_projector('linear', proj_geom, vol_geom) # change 'linear' to 'cuda' for GPU p = astra.OpTomo(pi) # Load the phantom from disk testPhantom = phantom.phantom(nd) # Calculate the forward projection of the phantom testSino = (p*testPhantom).reshape((na,nd)) # Add some noise to the sinogram testSino = astra.add_noise_to_sino(testSino,10**3) # Register plugin with ASTRA astra.plugin.register(sirtfbp.plugin) # Reconstruct the image using SIRT-FBP, FBP, and SIRT. sfbpRec = p.reconstruct('SIRT-FBP',testSino,200, extraOptions={'filter_dir':os.getcwd()}) if astra.projector.is_cuda(pi): fbpRec = p.reconstruct('FBP_CUDA',testSino) sirtRec = p.reconstruct('SIRT_CUDA',testSino,200)
import scipy.ndimage.interpolation import scipy.ndimage.fourier import matplotlib.pyplot import numpy # def affine_shift(a, shift_tuple): fa = numpy.fft.fft2(a) a= scipy.ndimage.fourier.fourier_shift(fa,shift = shift_tuple) a=numpy.fft.ifft2(a).real return a # # N = 128 a=phantom.phantom(N) # theta = 0.0 cosT= numpy.cos(theta*numpy.pi/180) sinT= numpy.sin(theta*numpy.pi/180) mymat = [[cosT, -sinT],[sinT, cosT]] print(mymat) b = affine_shift(a, (N/2, N/2)) # b=scipy.ndimage.interpolation.affine_transform(numpy.real(a),mymat,mode = 'wrap' ) # # a= affine_shift(a, (-N/2, -N/2)) # b = affine_shift(b, (-N/2, -N/2)) #
import numpy as np from PIL import Image from phantom import phantom import cv2 img = cv2.imread('128.png', cv2.IMREAD_GRAYSCALE) img = phantom(1500) f_img = np.fft.fft2(img) reconstructed = np.fft.ifft2(f_img).real f_img = np.fft.fft2(img) reconstructed = np.fft.ifft2(f_img) reconstructed2 = np.zeros(np.shape(img), dtype=np.complex_) for i in range(0, np.shape(img)[0]): reconstructed2[:, i] = np.fft.fft(f_img[:, i]) for i in range(0, np.shape(img)[0]): reconstructed2[i, :] = np.fft.fft(f_img[i, :]) # reconstructed = np.abs(reconstructed) reconstructed2 = np.abs(reconstructed2) img1 = Image.fromarray(f_img, 'L') img2 = Image.fromarray(reconstructed2, 'L') img3 = Image.fromarray(img, 'L')
import sys import read_dump import phantom as p import time #import resource start = time.time() p.phantom(read_dump.main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))) end = time.time() duration = end - start if duration < 60: print("Duration: %f seconds" % (duration)) elif duration < 3600: print("Duration: %f minutes" % (duration / 60)) else: print("Duration: %f hours" % ((duration / 60) / 60)) #This information is only available on linux. #print("Max RAM usage: %f gb" % (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1000000))
import phantom import numpy import scipy.fftpack import scipy.misc import matplotlib.pyplot def test(): pass if __name__ == "__main__": test() a = phantom.phantom(512)*1.0 d =scipy.misc.imrotate(a, - 23.4, interp = 'bilinear') b =scipy.misc.imrotate(d, 23.4, interp = 'bilinear') b = b -a*256 # a = scipy.fftpack.fftshift(a) # b = scipy.fftpack.fft2(a) # b = scipy.fftpack.fftshift(b) matplotlib.pyplot.imshow(b, norm = matplotlib.pyplot.Normalize(0,256)) matplotlib.pyplot.show()
def make_simple_phantom(pdim, liA, liB, liC, mats, z_range): """ Make phantom given dimensions and curves. Pretty much follows original simple design logic Parameters ---------- pdim: phandim phantom dimensions liA: linint inner cup curve liB: linint outer cup inner curve liC: linint outer cup outer curve mats: materials containes materials z_range: (float,float) tuple Z coordinates range returns: phantom pahntom filled with materials and densities """ phntom = phantom.phantom(pdim.bx(), pdim.by(), pdim.bz()) nx = phntom.nx() ny = phntom.ny() nz = phntom.nz() bx = phntom.bx() by = phntom.by() bz = phntom.bz() dens = phntom.data() idxs = phntom.mats() air = mats[1] water = mats[2] ss = mats[3] poly = mats[4] d_air = air[1] d_water = water[1] d_ss = ss[1] d_poly = poly[1] z_min, z_max = z_range for iz in range (0, nz): z = 0.5 * (bz[iz] + bz[iz+1]) ra = liA.extrapolate(z) rb = liB.extrapolate(z) rc = liC.extrapolate(z) for iy in range (0, ny): y = 0.5 * (by[iy] + by[iy+1]) for ix in range (0, nx): x = 0.5 * (bx[ix] + bx[ix+1]) r = math.sqrt(x*x + y*y) # default material: air m = 1 d = d_air if z <= z_max and z > XcConstants.COUCH_BOTTOM: if r <= ra: m = 2 # water d = d_water elif r <= rb: m = 1 # air d = d_air elif r <= rc: m = 4 # poly d = d_poly else: if not (z <= z_max and z > (XcConstants.COUCH_BOTTOM+XcConstants.COUCH_THICKNESS)): m = 4 # poly d = d_poly elif z <= XcConstants.COUCH_BOTTOM: m = 2 # water d = d_water idxs[ix,iy,iz] = m dens[ix,iy,iz] = d return phntom
def make_complex_phantom(pdim, liA, liB, liC, mats, z_range): """ Make phantom given dimensions and curves. Partial voxel volumes Basic formulas from http://mathworld.wolfram.com/CircularSegment.html Parameters ---------- pdim: phandim phantom dimensions liA: linint inner cup curve liB: linint outer cup inner curve liC: linint outer cup outer curve mats: materials containes materials z_range: (float,float) tuple Z coordinates range returns: phantom pahntom filled with materials and densities """ phntom = phantom.phantom(pdim.bx(), pdim.by(), pdim.bz()) nx = phntom.nx() ny = phntom.ny() nz = phntom.nz() bx = phntom.bx() by = phntom.by() bz = phntom.bz() idxs = phntom.mats() dens = phntom.data() air = mats[1] water = mats[2] ss = mats[3] poly = mats[4] d_air = air[1] d_water = water[1] d_ss = ss[1] d_poly = poly[1] z_min, z_max = z_range for iz in range (0, nz): z = 0.5 * (bz[iz] + bz[iz+1]) ra = liA.extrapolate(z) rb = liB.extrapolate(z) rc = liC.extrapolate(z) for iy in range (0, ny): ymin = by[iy] ymax = by[iy+1] y = 0.5 * (ymin + ymax) for ix in range (0, nx): xmin = bx[ix] xmax = bx[ix+1] x = 0.5 * (xmin + xmax) r = math.sqrt(x*x + y*y) # default material: air m = 1 d = d_air if z <= z_max and z > XcConstants.COUCH_BOTTOM: if r <= ra: m = 2 # water q = voxarea.vaInner(ra, xmin, ymin, xmax, ymax) if q < 0.0 and q > -EPS: q = 0.0 if q > 1.0 and q < 1.0+EPS: q = 1.0 p = voxarea.vaInner(ra, xmin, ymin, xmax, ymax) if p < 0.0 and p > -EPS: p = 0.0 if p > 1.0 and p < 1.0+EPS: p = 1.0 w_w = q w_a = p - q w_p = 1.0 - p if w_w < 0.0 or w_w > 1.0 or w_a < 0.0 or w_a > 1.0 or w_p < 0.0 or w_p > 1.0: print("RA: {0} {1} {2}".format(w_W, w_a, w_p)) d = w_w * d_water + w_a * d_air + w_p * d_poly elif r <= rb: m = 1 # air p = voxarea.vaOuter(ra, xmin, ymin, xmax, ymax) if p < 0.0 and p > -EPS: p = 0.0 if p > 1.0 and p < 1.0+EPS: p = 1.0 q = voxarea.vaInner(rb, xmin, ymin, xmax, ymax) if q < 0.0 and q > -EPS: q = 0.0 if q > 1.0 and q < 1.0+EPS: q = 1.0 w_w = p w_a = q - p w_p = 1.0 - q if w_w < 0.0 or w_w > 1.0 or w_a < 0.0 or w_a > 1.0 or w_p < 0.0 or w_p > 1.0: print("RB: {0} {1} {2}".format(w_w, w_a, w_p)) d = w_w * d_water + w_a * d_air + w_p * d_poly elif r <= rc: m = 4 # poly p = voxarea.vaOuter(rb, xmin, ymin, xmax, ymax) if p < 0.0 and p > -EPS: p = 0.0 if p > 1.0 and p < 1.0+EPS: p = 1.0 q = voxarea.vaInner(rc, xmin, ymin, xmax, ymax) if q < 0.0 and q > -EPS: q = 0.0 if q > 1.0 and q < 1.0+EPS: q = 1.0 w_a = p w_p = q - p w_aa= 1.0 - q if w_a < 0.0 or w_a > 1.0 or w_p < 0.0 or w_p > 1.0 or w_aa < 0.0 or w_aa > 1.0: print("RC: {0} {1} {2}".format(w_a, w_p, w_aa)) d = w_a * d_air + w_p * d_poly + w_aa * d_air else: if not (z <= z_max and z > (XcConstants.COUCH_BOTTOM+XcConstants.COUCH_THICKNESS)): m = 4 # poly p = voxarea.vaOuter(rc, xmin, ymin, xmax, ymax) if p < 0.0 and p > -EPS: p = 0.0 if p > 1.0 and p < 1.0+EPS: p = 1.0 if p < 0.0 or p > 1.0: print("RD: {0}".format(p)) d = p*d_poly + (1.0-p)*d_air elif z <= XcConstants.COUCH_BOTTOM: m = 2 # water d = d_water idxs[ix,iy,iz] = m dens[ix,iy,iz] = d return phntom
def generate_phantom(): theta = range(0, 180) data = np.rot90(radon(phantom.phantom(n=100), theta=theta)) data1 = np.zeros((data.shape[0], 1, data.shape[1])) data1[:, 0, :] = data return theta, data1
0, 1, 2, 3, 4, 6, 8, 11, 15, 17, 20, 23, 24, 25, 27, 30, 32 ] N = 256 # The image will be NxN # sparsity = 0.1 # use only 25% on the K-Space data for CS mu = 1.0 etl = 28 new_etl, phase_encode = sparse2blade_conf(etl, vardense) # F,R = sparse2blade_conf(input_k, new_etl,phase_encode) LMBD = 1.0 gamma = mu / 1000 image = phantom.phantom(N) kspace = numpy.fft.fft2(image) # R = numpy.zeros((N,new_etl)) raw_blade = numpy.zeros((N, etl), dtype=numpy.complex) for jj in xrange(0, etl): print('phase_encode[jj] = ', jj, phase_encode[jj]) # R[:,phase_encode[jj]-1]= numpy.ones((N,)) raw_blade[:, jj] = kspace[:, phase_encode[jj] - 1] # Form the CS data raw_blade = numpy.fft.fftshift(raw_blade, axes=0) F, R = sparse2blade_init(raw_blade, etl, new_etl, phase_encode) recovered = mrics(R, F, mu, LMBD, gamma, 5, 10)
def proto_rFOV_2D(): ''' prototype for subprocess ''' import time import numpy import matplotlib #.pyplot cm = matplotlib.cm.gray # load example image # norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1.0) # norm2=matplotlib.colors.Normalize(vmin=0.0, vmax=0.5) N = 384 Nd = (N, N) # image space size import phantom image = phantom.phantom(Nd[0]) Kd = (2 * N, 2 * N) # k-space size Jd = (6, 6) # interpolation size import KspaceDesign.Propeller nblade = 32 # numpy.round(N*3.1415/24/2) # print('nblade',nblade) theta = 180.0 / nblade #111.75 # propObj = KspaceDesign.Propeller.Propeller(N, 24, nblade, theta, 1, -1) om = propObj.om NufftObj = pynufft(om, Nd, Kd, Jd) precondition = 2 factor = 0.01 NufftObj.factor = factor NufftObj.precondition = precondition # simulate "data" data = NufftObj.forward(image) data_shape = (numpy.shape(data)) power_of_data = numpy.max(numpy.abs(data)) data = data + 1.0e-3 * power_of_data * ( numpy.random.randn(data_shape[0], data_shape[1]) + 1.0j * numpy.random.randn(data_shape[0], data_shape[1])) mu = 1 gamma = 0.001 LMBD = 1 nInner = 2 nBreg = 25 # now get the original image #reconstruct image with 0.1 constraint1, 0.001 constraint2, # 2 inner iterations and 10 outer iterations NufftObj.st['senseflag'] = 1 n_x = 1 n_y = 1 xdim, ydim, center_of_tiles = calculate_dim_index(n_x, n_y, N) xdim = 192 ydim = 192 center_of_tiles = (0, 0) # xdim = numpy.floor(N/n_x) +2 # ydim = numpy.floor(N/n_y) +2 #128 kdim = N * 2 NufftObj = pynufft(om, (xdim, ydim), (kdim, kdim), Jd, n_shift=(0, 0)) # NufftObj.linear_phase(om, (32,32), NufftObj.st['M'])# = pynufft(om, (64,64),(512,512),Jd,n_shift=(0,32)) # NufftObj.linear_phase(om, (-84, 0), NufftObj.st['M'])# = pynufft(om, (64,64),(512,512),Jd,n_shift=(0,32)) # import cPickle # f = open('Nufftobj.pickle','wb') # cPickle.dump(NufftObj ,f,2) # f.close() # f = open('data.pickle','wb') # # cPickle.dump(data ,f,2) # f.close() # del NufftObj # confirm that cPickle works # del data # confirm that cPickle works # t = time.time() # image_recon= pp_load_file_gpu_recon(NufftObj, data, LMBD, gamma,nInner, nBreg,(-84,0)) # image_blur = pp_load_file_dc(NufftObj,data)[...,0] import pp job_server = pp.Server() jobs = [] jobs2 = [] t = time.time() for tt in xrange(0, n_x * n_y): # # # if tt == 0: # my_shift = (0,0) # else: # my_shift = (-84,0) # my_shift = (-center_of_tiles[tt,0], -center_of_tiles[tt,1]) my_shift = (-84, 0) NufftObj.linear_phase(my_shift) jobs.append( job_server.submit( pp_load_file_gpu_recon, (NufftObj, data, LMBD, gamma, nInner, nBreg), # modules = ('pyfftw','numpy','pynufft','scipy','reikna'), globals=globals())) jobs2.append( job_server.submit( pp_load_file_dc, (NufftObj, data), # modules = ('pyfftw','numpy','pynufft','scipy','reikna'), globals=globals())) # jobs.append(job_server.submit(pp_recon,(NufftObj, my_shift,data, LMBD, gamma,nInner, nBreg ))) for tt in range(0, n_x * n_y): # if tt ==0: image_recon = jobs[tt]() image_blur = jobs2[tt]()[..., 0] # (tmp_imag, tmp_imag2) = jobs[tt]() image_recon = Normalize(numpy.real(image_recon)) #* 1.1# *1.3 image_blur = Normalize(numpy.real(image_blur)) #*1.15 # matplotlib.pyplot.figure(0) # fig, ax =matplotlib.pyplot.subplot(n_x,n_y,tt) # cax = ax.imshow( numpy.abs(-image_recon.real + image), # cmap= cm,interpolation = 'nearest') # cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) # cbar.ax.set_yticklabels(['< 0', '0.5', '> 1'])# vertically oriented colorbar matplotlib.pyplot.figure(1) matplotlib.pyplot.subplot(1, 2, 1) matplotlib.pyplot.imshow((image_recon.real), norm=norm, cmap=cm, interpolation='nearest') matplotlib.pyplot.subplot(1, 2, 2) matplotlib.pyplot.imshow((image_blur.real), norm=norm, cmap=cm, interpolation='nearest') # else: # image_blur = jobs[tt]() job_server.wait() job_server.destroy() # image_recon = Normalize(numpy.real(image_recon))#* 1.1# *1.3 # image_blur=Normalize(numpy.real(image_blur[...,0]))#*1.15 elapsed = time.time() - t print("time is ", elapsed) matplotlib.pyplot.show()
def phantom(self): self.theta = range(0, 180) self.data = dict(zip(self.theta, radon(phantom.phantom())))
blade=[128,25] #size of each blade, probably [128,25],[128,51] nblades=4 #number of blades, probably 4,8 M_py=[blade[0],blade[1]*nblades] #data size else: #radial M_py=[128,64] #ONLY SQUARE OUTPUT IMAGES!!! N_py=[128,128] #input/output image size num_iters=20 #CG iterations to perform ro_loc_pad=2 #weighting padding, don't change!!! sensefactor=2 #sense factor for propeller phase encode spacing ncoils=4 #number of coils #generate the phantom phan=phantom(N_py[0])+1j*0 #complex but no real complex information #initialize the sampling locations if use_propeller==1: locs_vec,locs=propeller_sampling_location_generator(blade,nblades,sense_factor=sensefactor) else: locs_vec,locs=projection_sampling_location_generator(M_py) #FOV support fov=comp_fov(N_py,thresh=1) phan*=fov #limit the FOV, not really necessary with a digital phantom
Return: tuple: coeffs useful for pywt.waverec2 """ nc = int(np.log2(len(xvec))) / 2 coeffs = [xvec[0].reshape(1, 1)] for i in range(nc): c1 = xvec[4**i:2 * 4**i].reshape(2**i, 2**i) c2 = xvec[2 * 4**i:3 * 4**i].reshape(2**i, 2**i) c3 = xvec[3 * 4**i:4 * 4**i].reshape(2**i, 2**i) coeffs.append((c1, c2, c3)) return coeffs if __name__ == '__main__': nx = 64 p = phantom(n=nx) frac = float(np.count_nonzero(p.ravel())) / nx**2 msg1 = 'phantom density %3.2f' % frac print(msg1) # deconstruct into wavelets coeffs = pywt.wavedec2(p, 'haar') # flatten coefficients xvec = flatten_coeffs(coeffs) frac = float(np.count_nonzero(xvec)) / len(xvec) msg2 = 'wavelet density %3.2f' % frac print(msg2) ## check raveled coefficients #coeffs1 = build_coeffs(xvec) ## reconstruct wavelets
-2 , -1 , 0 , 1 , 2 , 3 , 4 , 6 , 8 , 11, 15, 17 , 20, 23 , 24 , 25 , 27, 30, 32] N = 256# The image will be NxN # sparsity = 0.1 # use only 25% on the K-Space data for CS mu = 1.0 etl = 28 new_etl,phase_encode = sparse2blade_conf(etl,vardense) # F,R = sparse2blade_conf(input_k, new_etl,phase_encode) LMBD = 1.0 gamma = mu/1000 image=phantom.phantom(N) kspace = numpy.fft.fft2(image) # R = numpy.zeros((N,new_etl)) raw_blade = numpy.zeros((N,etl),dtype=numpy.complex) for jj in xrange(0,etl): print('phase_encode[jj] = ',jj,phase_encode[jj]) # R[:,phase_encode[jj]-1]= numpy.ones((N,)) raw_blade[:, jj ] = kspace[:, phase_encode[jj]-1 ] # Form the CS data raw_blade = numpy.fft.fftshift(raw_blade,axes = 0) F,R = sparse2blade_init(raw_blade, etl,new_etl, phase_encode)
def changePhantomMode(self, value): self.img = phantom(self.phantomSize, value) self.img = self.img * (255 / np.max(self.img)) self.originalPhantom = self.img self.showPhantomImage()
def test_2D(): import numpy import matplotlib#.pyplot cm = matplotlib.cm.gray # load example image norm=matplotlib.colors.Normalize(vmin=-0.0, vmax=1) norm2=matplotlib.colors.Normalize(vmin=0.0, vmax=0.5) import cPickle # image = numpy.loadtxt('phantom_256_256.txt') # matplotlib.pyplot.imshow(image[224-128:224, 64:192] , # norm = norm,cmap= cm,interpolation = 'nearest') # matplotlib.pyplot.show() # image[128,128]= 1.0 N = 256 Nd =(N,N) # image space size import phantom image = phantom.phantom(Nd[0]) Kd =(2*N,2*N) # k-space size Jd =(6,6) # interpolation size import KspaceDesign.Propeller nblade = 16#numpy.round(N*3.1415/24/2) # print('nblade',nblade) theta=180.0/nblade #111.75 # propObj=KspaceDesign.Propeller.Propeller( N ,24, nblade, theta, 1, -1) om = propObj.om NufftObj = pynufft(om, Nd,Kd,Jd ) # # f = open('nufftobj.pkl','wb') # cPickle.dump(NufftObj,f,2) # f.close() # # # # f = open('nufftobj.pkl','rb') # NufftObj = cPickle.load(f) # f.close() # f2 = open('dense_density.pkl','wb') # cPickle.dump(NufftObj.st['w'],f2,-1) # f2.close() # print('size of sparse amtrix',NufftObj.st['p'].data.nbytes + NufftObj.st['p'].indptr.nbytes + NufftObj.st['p'].indices.nbytes) # print('size of dense matrix', NufftObj.st['w'].nbytes) # NufftObj = pynufft(om, (64,64),(512,512),Jd) precondition = 0 factor = 0.001 NufftObj.factor = factor NufftObj.precondition = precondition # simulate "data" data= NufftObj.forward(image ) # data= NufftObj.true_forward(image ) data_shape = (numpy.shape(data)) power_of_data= numpy.max(numpy.abs(data)) # purpose = 2 # noisy purpose = 1 # noisy # purpose = 0 # noise-free data = data + purpose*1e-3*power_of_data*(numpy.random.randn(data_shape[0],data_shape[1])+1.0j*numpy.random.randn(data_shape[0],data_shape[1])) LMBD =1 nInner=2 nBreg = 25 mu=1.0 gamma = 0.001 # now get the original image #reconstruct image with 0.1 constraint1, 0.001 constraint2, # 2 inner iterations and 10 outer iterations rFOV = 96 NufftObj = pynufft(om, (rFOV,rFOV),Kd,Jd,n_shift=(0,0)) # Shift the center of the image by applying a linear phase on k-space NufftObj.linear_phase( (-128, 0) ) NufftObj.st['senseflag'] = 1 NufftObj.initialize_gpu() NufftObj.debug=2 #depicting the intermediate images # NufftObj = pynufft(om, (64,64),(96,96),Jd)#,n_shift=(192,96)) # NufftObj = pynufft(om, (256,256),(512,512),Jd) # Setting reduced FOV image_blur = NufftObj.backward2(data) # image_recon_inner_10 = NufftObj.pseudoinverse(data, 1.0, LMBD, gamma, 10, nBreg) image_recon = NufftObj.pseudoinverse(data, 1.0, LMBD, gamma,nInner, nBreg) image_recon = Normalize(image_recon.real) image_blur=Normalize(numpy.real(image_blur[...,0]))*1.2 #4.9 # my_scale = numpy.mean( image_blur[round(25*N/256):round(46*N/256), round(109*N/256):round(149*N/256)].flatten()) # image_blur =image_blur / my_scale /5.0 my_scale = numpy.mean( image_recon[round(25*N/256):round(46*N/256), round(109*N/256):round(149*N/256)].flatten()) image_recon =image_recon / my_scale /5.0 # print(my_scale) # image_recon = NufftObj.pseudoinverse2(data) # image_blur = NufftObj.backward2(data) # if purpose == 0: # image_recon = Normalize(image_recon.real)*1.05#2.2 # *1.3 # elif purpose == 1: # image_recon = Normalize(image_recon.real)*1.1#54#2.2 # *1.3 # # image_recon_inner_10 = Normalize(numpy.real(image_recon_inner_10))#* 1.1# *1.3 # image_blur=Normalize(numpy.real(image_blur[...,0]))*1.2#4.9 # if purpose == 0: # image_recon = Normalize(image_recon.real)*1.3#2.2 # *1.3 # elif purpose == 1: # image_recon = Normalize(image_recon.real)*1.0#54#2.2 # *1.3 # elif purpose == 2: # image_recon = Normalize(image_recon.real)*1.1#54#2.2 # *1.3 # image_recon_inner_10 = Normalize(numpy.real(image_recon_inner_10))#* 1.1# *1.3 disp_image = numpy.concatenate( ( # numpy.concatenate( (( image_recon.real) , numpy.real(-image_recon + image) ), axis = 0 ), numpy.concatenate( (( image_recon.real) , numpy.abs(image_recon - image) ), axis = 0 ), numpy.concatenate( (( image_blur.real) ,numpy.abs(image_blur - image) ), axis = 0 ) ), axis =1 ) import scipy.misc scipy.misc.imsave('/home/sram/Cambridge_2012/WORD_PPTS/PROP/generalize_inverse/MRM/FIGS/noise_XX.png',disp_image) fig, ax = matplotlib.pyplot.subplots() cax = ax.imshow( disp_image , norm = norm, cmap= cm,interpolation = 'nearest') cbar = fig.colorbar(cax, ticks=[0, 0.5, 1]) cbar.ax.set_yticklabels(['< 0', '0.5', '> 1'])# vertically oriented colorbar matplotlib.pyplot.savefig('/home/sram/Cambridge_2012/WORD_PPTS/PROP/generalize_inverse/MRM/FIGS/noise_XX.eps', bbox_inches='tight') # matplotlib.pyplot.figure(1) # matplotlib.pyplot.subplot(n_x,n_y,tt) # matplotlib.pyplot.imshow(numpy.abs(image_recon.real) , # norm = norm, # cmap= cm,interpolation = 'nearest') matplotlib.pyplot.show()
Dn = center_kspace[:,:,pj] Chi_n[pj]= numpy.sum(numpy.real( DA*Dn.conj() ).flatten()) max_Chi_n = numpy.max(Chi_n) min_Chi_n = numpy.min(Chi_n) Chi_n = ( Chi_n - min_Chi_n )/(max_Chi_n -min_Chi_n ) Pn = Chi_n**rho for pj in xrange(0,nblades): input_strips[:,:,pj] = input_strips[:,:,pj]*Pn[pj] # input_strips[:,:,pj]=input_strips[:,:,pj]* return input_strips if __name__ == "__main__": import phantom a=phantom.phantom(34) import cProfile import Im2Polar cProfile.run('tt = Im2Polar.Im2Polar(a,0,1,64,512).real') matplotlib.pyplot.imshow(tt) matplotlib.pyplot.show() b =numpy.roll(a,-10,axis =0) b =numpy.roll(b,10,axis =1) # import scipy.misc # b = scipy.misc.imrotate(b,15, 'cubic') ka = scipy.fftpack.fftshift(a) ka = scipy.fftpack.fft2(ka)
import phantom import numpy import scipy.fftpack import scipy.misc import matplotlib.pyplot def test(): pass if __name__ == "__main__": test() a = phantom.phantom(512) * 1.0 d = scipy.misc.imrotate(a, -23.4, interp='bilinear') b = scipy.misc.imrotate(d, 23.4, interp='bilinear') b = b - a * 256 # a = scipy.fftpack.fftshift(a) # b = scipy.fftpack.fft2(a) # b = scipy.fftpack.fftshift(b) matplotlib.pyplot.imshow(b, norm=matplotlib.pyplot.Normalize(0, 256)) matplotlib.pyplot.show()
def rfov_2D(gpu_type): import numpy N = 384 Nd =(N,N) # image space size # create Shepp-Logan phantom import phantom image = phantom.phantom(Nd[0]) Kd =(2*N,2*N) # k-space size Jd =(6,6) # interpolation size import KspaceDesign.Propeller nblade =26# numpy.round(N*3.1415/24) # print('nblade',nblade) theta=180.0/nblade #111.75 # propObj=KspaceDesign.Propeller.Propeller( N ,24, nblade, theta, 1, -1) om = propObj.om # print('m',numpy.size(om)) # load k-space points # om = numpy.loadtxt('om.txt') # om = numpy.loadtxt('om.gold') #create object # import cPickle NufftObj = pynufft(om, Nd,Kd,Jd ) # f = open('nufftobj.pkl','wb') # cPickle.dump(NufftObj,f,2) # f.close() # # # # f = open('nufftobj.pkl','rb') # NufftObj = cPickle.load(f) # f.close() # precondition = 2 # factor = 0.01 # NufftObj.factor = factor # NufftObj.precondition = precondition # simulate "data" data= NufftObj.forward(image ) data_shape = numpy.shape(data) power_of_data= numpy.max(numpy.abs(data)) data = data + 1e-3*power_of_data*(numpy.random.randn(data_shape[0],data_shape[1])+1.0j*numpy.random.randn(data_shape[0],data_shape[1])) LMBD =1 nInner=2 nBreg = 25 mu=1.0 gamma = 0.001 # Setting reduced FOV rFOV = 96 NufftObj = pynufft(om, (rFOV,rFOV),Kd,Jd,n_shift=(0,0)) # Shift the center of the image by applying a linear phase on k-space NufftObj.linear_phase( (-128, 0) ) # now get the original image #reconstruct image with 0.1 constraint1, 0.001 constraint2, # 2 inner iterations and 10 outer iterations NufftObj.st['senseflag'] = 0 # shrinkage threshold NufftObj.beta = 1 # Attempt to set GPU computing (warning: cuda hardware and reikna/pyopencl are needed!) if gpu_type=='GPU': NufftObj.initialize_gpu() else: pass # debug level NufftObj.debug = 2 # 2 for showing splitting variables and text outputs, 1 for text outputs image_blur = NufftObj.backward2(data) image_recon = NufftObj.pseudoinverse(data, 1.0, LMBD, gamma,nInner, nBreg) # Normalize the contrast of images mean_image_recon = numpy.mean(numpy.real(image_recon[41:62, 8:24 ].flatten())) image_recon = numpy.real(image_recon)/mean_image_recon/5.0# *1.3 mean_image_blur = numpy.mean(numpy.real(image_blur[41:62, 8:24 ].flatten())) image_blur=numpy.real(image_blur[...,0])/mean_image_blur/5.0#*1.15 # Display images import matplotlib#.pyplot # Set grey color maps cm = matplotlib.cm.gray # Set image window norm2=matplotlib.colors.Normalize(vmin=0.0, vmax=0.5) norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1) matplotlib.pyplot.figure(3) matplotlib.pyplot.subplot(1,2,1) matplotlib.pyplot.imshow((image_recon).real, norm = norm,cmap= cm,interpolation = 'nearest') matplotlib.pyplot.title('denoising by shrinkage') matplotlib.pyplot.subplot(1,2,2) matplotlib.pyplot.imshow(numpy.real(image_blur).real, norm = norm,cmap= cm,interpolation = 'nearest') matplotlib.pyplot.title('density compensation') matplotlib.pyplot.show() return NufftObj.gpu_flag # return the GPU to see whether GPU computing has been used
def proto_rFOV_2D(): ''' prototype for subprocess ''' import time import numpy import matplotlib#.pyplot cm = matplotlib.cm.gray # load example image # norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1.0) # norm2=matplotlib.colors.Normalize(vmin=0.0, vmax=0.5) N = 384 Nd =(N,N) # image space size import phantom image = phantom.phantom(Nd[0]) Kd =(2*N,2*N) # k-space size Jd =(6,6) # interpolation size import KspaceDesign.Propeller nblade = 32# numpy.round(N*3.1415/24/2) # print('nblade',nblade) theta=180.0/nblade #111.75 # propObj=KspaceDesign.Propeller.Propeller( N ,24, nblade, theta, 1, -1) om = propObj.om NufftObj = pynufft(om, Nd,Kd,Jd ) precondition = 2 factor = 0.01 NufftObj.factor = factor NufftObj.precondition = precondition # simulate "data" data= NufftObj.forward(image ) data_shape = (numpy.shape(data)) power_of_data= numpy.max(numpy.abs(data)) data = data + 1.0e-3*power_of_data*(numpy.random.randn(data_shape[0],data_shape[1])+1.0j*numpy.random.randn(data_shape[0],data_shape[1])) mu= 1 gamma = 0.001 LMBD =1 nInner=2 nBreg = 25 # now get the original image #reconstruct image with 0.1 constraint1, 0.001 constraint2, # 2 inner iterations and 10 outer iterations NufftObj.st['senseflag'] = 1 n_x =1 n_y =1 xdim, ydim, center_of_tiles= calculate_dim_index(n_x,n_y,N) xdim = 192 ydim = 192 center_of_tiles = (0,0) # xdim = numpy.floor(N/n_x) +2 # ydim = numpy.floor(N/n_y) +2 #128 kdim = N*2 NufftObj = pynufft(om, (xdim,ydim),(kdim,kdim),Jd,n_shift=(0,0)) # NufftObj.linear_phase(om, (32,32), NufftObj.st['M'])# = pynufft(om, (64,64),(512,512),Jd,n_shift=(0,32)) # NufftObj.linear_phase(om, (-84, 0), NufftObj.st['M'])# = pynufft(om, (64,64),(512,512),Jd,n_shift=(0,32)) # import cPickle # f = open('Nufftobj.pickle','wb') # cPickle.dump(NufftObj ,f,2) # f.close() # f = open('data.pickle','wb') # # cPickle.dump(data ,f,2) # f.close() # del NufftObj # confirm that cPickle works # del data # confirm that cPickle works # t = time.time() # image_recon= pp_load_file_gpu_recon(NufftObj, data, LMBD, gamma,nInner, nBreg,(-84,0)) # image_blur = pp_load_file_dc(NufftObj,data)[...,0] import pp job_server = pp.Server() jobs = [] jobs2 = [] t = time.time() for tt in xrange(0,n_x*n_y): # # # if tt == 0: # my_shift = (0,0) # else: # my_shift = (-84,0) # my_shift = (-center_of_tiles[tt,0], -center_of_tiles[tt,1]) my_shift = (-84,0) NufftObj.linear_phase( my_shift ) jobs.append(job_server.submit( pp_load_file_gpu_recon, (NufftObj, data, LMBD, gamma,nInner, nBreg ), # modules = ('pyfftw','numpy','pynufft','scipy','reikna'), globals = globals())) jobs2.append(job_server.submit( pp_load_file_dc, (NufftObj, data), # modules = ('pyfftw','numpy','pynufft','scipy','reikna'), globals = globals())) # jobs.append(job_server.submit(pp_recon,(NufftObj, my_shift,data, LMBD, gamma,nInner, nBreg ))) for tt in range(0,n_x*n_y): # if tt ==0: image_recon = jobs[tt]() image_blur = jobs2[tt]()[...,0] # (tmp_imag, tmp_imag2) = jobs[tt]() image_recon = Normalize(numpy.real(image_recon))#* 1.1# *1.3 image_blur=Normalize(numpy.real(image_blur ))#*1.15 # matplotlib.pyplot.figure(0) # fig, ax =matplotlib.pyplot.subplot(n_x,n_y,tt) # cax = ax.imshow( numpy.abs(-image_recon.real + image), # cmap= cm,interpolation = 'nearest') # cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) # cbar.ax.set_yticklabels(['< 0', '0.5', '> 1'])# vertically oriented colorbar matplotlib.pyplot.figure(1) matplotlib.pyplot.subplot(1,2,1) matplotlib.pyplot.imshow( (image_recon.real) , norm = norm, cmap= cm,interpolation = 'nearest') matplotlib.pyplot.subplot(1,2,2) matplotlib.pyplot.imshow( (image_blur.real) , norm = norm, cmap= cm,interpolation = 'nearest') # else: # image_blur = jobs[tt]() job_server.wait() job_server.destroy() # image_recon = Normalize(numpy.real(image_recon))#* 1.1# *1.3 # image_blur=Normalize(numpy.real(image_blur[...,0]))#*1.15 elapsed = time.time() - t print("time is ",elapsed) matplotlib.pyplot.show()
def make_phantom(pdim, liA, liB, liC, mats, z_range): """ Make QA phantom given dimensions and curves Parameters ---------- pdim: phandim phantom dimensions liA: linint inner cup curve liB: linint outer cup inner curve liC: linint outer cup outer curve mats: materials containes materials z_range: (float,float) tuple Z coordinates range returns: phantom pahntom filled with materials and densities """ phntom = phantom.phantom(pdim.bx(), pdim.by(), pdim.bz()) nx = phntom.nx() ny = phntom.ny() nz = phntom.nz() bx = phntom.bx() by = phntom.by() bz = phntom.bz() # denity and material indeces idxs = phntom.mats() dens = phntom.data() air = mats[1] water = mats[2] ss = mats[3] poly = mats[4] pmma = mats[5] d_air = air[1] d_water = water[1] d_ss = ss[1] d_poly = poly[1] d_pmma = pmma[1] z_min, z_max = z_range for iz in range (0, nz): z = 0.5 * (bz[iz] + bz[iz+1]) for iy in range (0, ny): y = 0.5 * (by[iy] + by[iy+1]) for ix in range (0, nx): x = 0.5 * (bx[ix] + bx[ix+1]) # default material: air m = 1 d = d_air r = math.sqrt(x*x + y*y) # as lifted from qa/make_cups # all units are in mm if z > 15.0 and z <= 15.0+46.0 and r <= 77.0: m = 5 # PMMA d = d_pmma elif z > 15.0+46.0 and z <= 15.0+115.0 and math.sqrt(squared(r)+squared(z-(15.0+46.0))) <= 77.0: m = 5 # PMMA d = d_pmma idxs[ix,iy,iz] = m dens[ix,iy,iz] = d return phntom
# Run a fast fast MC import antea.fastfastmc.fastfastmc as ffmc from errmat import errmat from phantom import phantom Nevts = 1000 # Construct the phantom object. phtm = phantom( "/Users/jrenner/local/jerenner/ANTEA/antea/fastfastmc/phantom/phantom_NEMAlike.npz" ) # Construct the error matrix objects. errmat_r = errmat( '/Users/jrenner/local/jerenner/ANTEA/antea/fastfastmc/errmat/errmat_r.npz') errmat_phi = errmat( '/Users/jrenner/local/jerenner/ANTEA/antea/fastfastmc/errmat/errmat_phi.npz' ) errmat_z = errmat( '/Users/jrenner/local/jerenner/ANTEA/antea/fastfastmc/errmat/errmat_z.npz') # Run the simulation. events = ffmc.run_fastfastmc(Nevts, phtm, errmat_r, errmat_phi, errmat_z) # Save the results to file. events.to_hdf("sim.h5", "fastfastsim")