def test_tvgen_nd(): """Test that the general solver does not crash for high-d tensors""" for _ in range(20): dims = np.random.randint(3, 5) shape = np.random.randint(2, 10, size=dims) x = np.random.randn(*shape) w = np.random.randn(dims) tvgen(x, w, list(range(1, dims+1)), np.ones(dims))
def test_tvgen_nd(): """Test that the general solver does not crash for high-d tensors""" for _ in range(20): dims = np.random.randint(3, 5) shape = np.random.randint(2, 10, size=dims) x = np.random.randn(*shape) w = np.random.randn(dims) tvgen(x, w, list(range(1, dims + 1)), np.ones(dims))
def TTVOneIteration(x, z, t, imgs, A, s0, args): tikh = args.tikh * s0 # SGD r = x.reshape([-1, x.shape[-1]]).T c = imgs.reshape([-1, imgs.shape[-1]]).T q1 = A @ r - c q2 = tikh * r q1 = A.T @ q1 q2 = tikh * q2 aq1 = A @ q1 aq2 = tikh * q2 s = np.sum((q1 + q2)**2) / (np.sum(aq1**2) + np.sum(aq2**2)) zNew = r - s * (q1 + q2) zNew = np.reshape(zNew.T, x.shape) # TV zNew = prox_tv.tvgen(zNew, args.betas, [1,2,3], [1,1,1], n_threads = 8, max_iters = 10) # acceleration tNew = (1 + np.sqrt(1 + 4 * t * t)) / 2 xNew = zNew + ((t - 1) / tNew) * (zNew - z) return xNew, zNew, tNew
def test_tvgen_2d(): """Tests that the general solver returns correct 2d solutions""" for _ in range(20): x = _generate2D() w = 20 * np.random.rand() specific = tv1_2d(x, w, max_iters=1000) general = tvgen(x, [w, w], [1, 2], [1, 1], max_iters=1000) assert np.allclose(specific, general, atol=1e-2)
def test_tvgen_2d(): """Tests that the general solver returns correct 2d solutions""" for _ in range(20): x = _generate2d() w = 20*np.random.rand() specific = tv1_2d(x, w, max_iters=1000) general = tvgen(x, [w, w], [1, 2], [1, 1], max_iters=1000) assert np.allclose(specific, general, atol=1e-2)
def test_tvgen_1d(): """Tests that the general solver returns correct 1d solutions""" for _ in range(20): dimension = np.random.randint(1e1, 3e1) x = 100 * np.random.randn(dimension) w = 20 * np.random.rand() specific = tv1_1d(x, w) general = tvgen(x, [w], [1], [1]) assert np.allclose(specific, general, atol=1e-3)
def test_tvgen_1d(): """Tests that the general solver returns correct 1d solutions""" for _ in range(20): dimension = np.random.randint(1e1, 3e1) x = 100*np.random.randn(dimension) w = 20*np.random.rand() specific = tv1_1d(x, w) general = tvgen(x, [w], [1], [1]) assert np.allclose(specific, general, atol=1e-3)
def test_tvgen_multireg(): """Test applying several regularizers on same dimension""" for _ in range(20): x = _generate2D() w = 20 * np.random.rand() specific = tv1_2d(x, w, max_iters=1000) general = tvgen(x, [w / 2., w / 2., w / 3., w / 3., w / 3.], [1, 1, 2, 2, 2], [1, 1, 1, 1, 1], max_iters=1000) print("Max diff: " + str((specific - general).max())) assert np.allclose(specific, general, atol=1e-2)
def prox_FL(a, beta, lamda, p=1, symmetric=False, use_matlab=False, optimize=True): """Fused Lasso prox. It is calculated as the Total variation prox + soft thresholding on the solution, as in http://ieeexplore.ieee.org/abstract/document/6579659/ """ # if any([any(np.diag(x) < 0) for x in a]): # for a_i in a: # np.fill_diagonal(a_i, np.sum(np.abs(a_i), axis=1)) if optimize: Y = tvgen(a, [beta], [1], [p], n_threads=32, max_iters=30) else: Y = np.empty_like(a) # if use_matlab: # from regain.wrapper.tv_condat import wrapper # func = wrapper.total_variation_condat # else: func = tv1_1d if p == 1 else partial(tvp_1d, p=p) if symmetric: x, y = np.triu_indices_from(a[0]) b = np.vstack(a.transpose(1, 2, 0)) upper_ind = x * a.shape[1] + y Z = np.zeros_like(b) Z[upper_ind] = [func(row, beta) for row in b[upper_ind]] e = np.array(np.split(Z, a.shape[1], axis=0)).transpose(2, 0, 1) Y = (e + e.transpose(0, 2, 1)) / ( np.array([np.eye(a.shape[1]) for i in range(a.shape[0])]) + 1) else: for i in range(np.power(a.shape[1], 2)): solution = func(a.flat[i::np.power(a.shape[1], 2)], beta) Y.flat[i::np.power(a.shape[1], 2)] = solution # fused-lasso (soft-thresholding on the solution) Y_soft = soft_thresholding(Y, lamda) # restore diagonal for y_s, y_fv in zip(Y_soft, Y): np.fill_diagonal(y_s, np.diag(y_fv)) return Y_soft
def test_tvgen_multireg(): """Test applying several regularizers on same dimension""" for _ in range(20): x = _generate2d() w = 20*np.random.rand() specific = tv1_2d(x, w, max_iters=1000) general = tvgen( x, [w/2., w/2., w/3., w/3., w/3.], [1, 1, 2, 2, 2], [1, 1, 1, 1, 1], max_iters=1000 ) print("Max diff: " + str((specific-general).max())) assert np.allclose(specific, general, atol=1e-2)
def trendFilter3D(tensor, lamb, k=0): if isinstance(lamb, tuple): lamb_x, lamb_y, lamb_z = lamb else: lamb_x, lamb_y, lamb_z = lamb, lamb, lamb if k == 0: filtered_block = ptv.tvgen(tensor, [lamb_x, lamb_y, lamb_z], [1, 2, 3], [1, 1, 1]) elif k == 1: pass elif k == 2: pass else: raise NotImplementedError return filtered_block
def _prox_s(x, reg): return tvgen(x, [reg, reg, reg], [1, 2, 3], [1, 1, 1])
from skimage import io, util import numpy as np # Load color image (3 dimensions: length, width and color) X = io.imread('colors.png') X = ski.img_as_float(X) # Introduce noise noiseLevel = 0.2 N = util.random_noise(X, mode='gaussian', var=noiseLevel) # Filter using 3D TV-L1: we only want to penalize X and Y dims (not color) lam = 100. / 255. print('Filtering image...') start = time.time() F = ptv.tvgen(N, np.array([lam, lam]), [1, 2], np.array([1, 1])) # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end - start)) # Any dimension can be penalized under any norm. By also penalizing the color dimension under TV-L2 we get a "decolored" image lam2 = 50. / 255. print('Color filtering...') start = time.time() F2 = ptv.tvgen(N, np.array([lam, lam, lam2]), [1, 2, 3], np.array([1, 1, 2])) # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end - start)) # Plot results plt.subplot(2, 2, 1)
from skimage import io, util import numpy as np # Load color image (3 dimensions: length, width and color) X = io.imread('colors.png') X = ski.img_as_float(X) # Introduce noise noiseLevel = 0.2 N = util.random_noise(X, mode='gaussian', var=noiseLevel) # Filter using 3D TV-L1: we only want to penalize X and Y dims (not color) lam=100./255.; print('Filtering image...') start = time.time() F = ptv.tvgen(N, np.array([lam, lam]), [1, 2], np.array([1, 1])) # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end-start)) # Any dimension can be penalized under any norm. By also penalizing the color dimension under TV-L2 we get a "decolored" image lam2=50./255.; print('Color filtering...') start = time.time() F2 = ptv.tvgen(N, np.array([lam, lam, lam2]), [1, 2, 3], np.array([1, 1, 2])); # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end-start)) # Plot results plt.subplot(2, 2, 1)
import skimage as ski from skimage import data, io, filters, color, util # Load color image (3 dimensions: length, width and color) X = io.imread('colors.png') X = ski.img_as_float(X) # Introduce noise noiseLevel = 0.2 N = util.random_noise(X, mode='gaussian', var=noiseLevel) # Filter using 3D TV-L1: we only want to penalize X and Y dims (not color) lam = 100. / 255. print('Filtering image...') start = time.time() F = ptv.tvgen(N, [lam, lam], [1, 2], [1, 1]) # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end - start)) # Any dimension can be penalized under any norm. By also penalizing the color dimension under TV-L2 we get a "decolored" image lam2 = 50. / 255. print('Color filtering...') start = time.time() F2 = ptv.tvgen(N, [lam, lam, lam2], [1, 2, 3], [1, 1, 2]) # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end - start)) # Plot results plt.subplot(2, 2, 1)
input_filename = sys.argv[1] basename = os.path.basename(input_filename) filename = os.path.splitext(basename)[0] output_folder = sys.argv[2] output_extension = "nrrd" lam = float(sys.argv[3]) output_filename = os.path.join(output_folder, filename + "_tv" + str(lam) + "." + output_extension) # PixelType = itk.F # PixelType = itk.UC # Dimension = 3 # ImageType = itk.Image[PixelType, Dimension] # reader = itk.ImageFileReader[ImageType].New(FileName=input_filename) reader = itk.ImageFileReader.New(FileName=input_filename) reader.Update() image = reader.GetOutput() image_array = itk.GetArrayViewFromImage(image) norm = 1 dimensions_to_penalyze = [1,2,3] tv_array = ptv.tvgen(image_array, np.array([lam,lam,lam]), dimensions_to_penalyze, np.array([norm,norm,norm])) tv_array = np.ascontiguousarray(tv_array, dtype=image_array.dtype) # modifiedImage = itk.PyBuffer[ImageType].GetImageViewFromArray(tv_array) modifiedImage = itk.GetImageViewFromArray(tv_array) itk.ImageFileWriter.New(Input=modifiedImage, FileName=output_filename).Update() # from subprocess import Popen # testDriver = "/home/phc/tmp/IsotropicWaveletsTestDriver" # pin = Popen([testDriver, 'runViewImage', input_filename, 'input']) # pout = Popen([testDriver, 'runViewImage', output_filename, 'TV'])
uft = UFT(samp0, axes=ax, scale=True) forward = uft.forward_ortho inverse = uft.inverse_ortho y = forward(x) # view(y, log=True) imspace_u = inverse(y) # from mr_utils.cs import SpatioTemporalTVSB # recon, err = SpatioTemporalTVSB( # samp0, y, betaxy=1/4, betat=1, mu=1, lam=1, gamma=1/2, # nInner=1, niter=3, x=x) # view(recon) w = 50 recon_l1 = ptv.tvgen( np.abs(imspace_u), np.array([w]), [3], np.array([1])) recon_l2 = ptv.tvgen( np.abs(imspace_u), np.array([w]), [3], np.array([2])) recon_sort = np.zeros_like(imspace_u) roi_cnt = 0 for idx in tqdm(np.ndindex((sx, sy)), total=sx*sy, leave=False): ii, jj = idx[:] # TODO: # Mask out small ROIs to do run ordinator in if roi[ii, jj]: # sord = ordinator1d( # np.abs(imspace_true[ii, jj, :]), k=10, # forward=S.forward_wvlt, inverse=S.inverse_wvlt, # chunksize=10, pdf=None, pdf_metric=None,
import skimage as ski from skimage import data, io, filters, color, util # Load color image (3 dimensions: length, width and color) X = io.imread('colors.png') X = ski.img_as_float(X) # Introduce noise noiseLevel = 0.2 N = util.random_noise(X, mode='gaussian', var=noiseLevel) # Filter using 3D TV-L1: we only want to penalize X and Y dims (not color) lam=100./255.; print('Filtering image...') start = time.time() F = ptv.tvgen(N, [lam, lam], [1, 2], [1, 1]) # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end-start)) # Any dimension can be penalized under any norm. By also penalizing the color dimension under TV-L2 we get a "decolored" image lam2=50./255.; print('Color filtering...') start = time.time() F2 = ptv.tvgen(N, [lam, lam, lam2], [1, 2, 3], [1, 1, 2]); # Image | Penalty in each dimension | Dimensions to penalize | Norms to use end = time.time() print('Elapsed time ' + str(end-start)) # Plot results plt.subplot(2, 2, 1)