def __init__(self, dataroot, file, im_size): # Load in nii as a 3d matrix data_nii = nib.load(dataroot + file) data = np.array(data_nii.dataobj) num = np.int(data.shape[2] / num_frame) self.pack = np.zeros([num, 3, im_size, im_size]).astype(np.float32) t1 = time.time() for i in range(num): data_crop = self.Center_Crop(data[:, :, i * num_frame], im_size) # get gradient map diffuse_1 = anisotropic_diffusion(data_crop, niter=15, option=2).astype(np.uint8) diffuse_2 = anisotropic_diffusion(data_crop, niter=30, option=2).astype(np.uint8) gradient_1 = self.Sobel(diffuse_1, 3) gradient_2 = self.Sobel(diffuse_2, 3) self.pack[i, 0, :, :] = data_crop self.pack[i, 1, :, :] = gradient_1 self.pack[i, 2, :, :] = gradient_2 t2 = time.time() print('Processing time: ', np.int(t2 - t1), 's')
def binarize(vol, vol_seg, verbose): h, slc, w = vol.shape # define the output vol_base_1 = np.zeros(vol.shape, dtype=np.uint8) # diffuse+kmeans vol_base_2 = np.zeros(vol.shape, dtype=np.uint8) # diffuse+otsu vol_opt = np.zeros(vol.shape, dtype=np.uint8) # seg+diffuse+otsu idx = random.randint(0, slc - 1) for i in range(slc): # output 1 im = Int8(vol[:, i, :]) vol_base_1[:, i, :] = np.uint8(Kmeans(im)) * 255 # output 2 diffuse = anisotropic_diffusion(im, niter=10, option=2).astype(np.float32) im_enhance = ContrastEnhance(diffuse) otsu_th = threshold_otsu(im_enhance) vol_base_2[:, i, :] = np.uint8(im_enhance > otsu_th) * 255 # proposed im_seg = Int8(vol_seg[:, i, :]) diffuse_seg = anisotropic_diffusion(im_seg, niter=10, option=2).astype(np.float32) im_enhance = ContrastEnhance(diffuse_seg) otsu_th_opt = threshold_otsu(im_enhance) vol_opt[:, i, :] = np.uint8(im_enhance > otsu_th_opt) * 255 if verbose == True and i == idx: top = np.concatenate((im, im_seg), axis=1) bot = np.concatenate( (vol_base_1[:, i, :], vol_base_2[:, i, :], vol_opt[:, i, :]), axis=1) plt.figure(figsize=(10, 5)) plt.axis('off') plt.title('slc:{}'.format(idx), fontsize=15) plt.imshow(top, cmap='gray') # plt.savefig("E:\\OCTA\\result\\vis.jpg") plt.show() plt.figure(figsize=(15, 5)) plt.axis('off') plt.imshow(bot, cmap='gray') # plt.savefig("E:\\OCTA\\result\\vis.jpg") plt.show() return vol_base_1, vol_base_2, vol_opt
def main(): # parse cmd arguments parser = getParser() parser.parse_args() args = getArguments(parser) # prepare logger logger = Logger.getInstance() if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) # check if output image exists (will also be performed before saving, but as the smoothing might be very time intensity, a initial check can save frustration) if not args.force: if os.path.exists(args.output): raise parser.error('The output image {} already exists.'.format( args.output)) # loading image data_input, header_input = load(args.input) # apply the watershed logger.info( 'Applying anisotropic diffusion with settings: niter={} / kappa={} / gamma={}...' .format(args.iterations, args.kappa, args.gamma)) data_output = anisotropic_diffusion(data_input, args.iterations, args.kappa, args.gamma, get_pixel_spacing(header_input)) # save file save(data_output, args.output, header_input, args.force) logger.info('Successfully terminated.')
def main(): # parse cmd arguments parser = getParser() parser.parse_args() args = getArguments(parser) # prepare logger logger = Logger.getInstance() if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) # check if output image exists (will also be performed before saving, but as the smoothing might be very time intensity, a initial check can save frustration) if not args.force: if os.path.exists(args.output): raise parser.error('The output image {} already exists.'.format(args.output)) # loading image data_input, header_input = load(args.input) # apply the watershed logger.info('Applying anisotropic diffusion with settings: niter={} / kappa={} / gamma={}...'.format(args.iterations, args.kappa, args.gamma)) data_output = anisotropic_diffusion(data_input, args.iterations, args.kappa, args.gamma, get_pixel_spacing(header_input)) # save file save(data_output, args.output, header_input, args.force) logger.info('Successfully terminated.')
def __init__(self, dataroot, file, axis): # Load in nii as a 3d matrix data_nii = nib.load(dataroot + file) data = np.array(data_nii.dataobj) # Slicer single_frame_volume = self.Slicer(data, 5) # 3d crop crop = Crop3d(single_frame_volume, 512) # Define the output self.pack = np.zeros([512, 3, 512, 500], dtype=np.float32) # Which dimension if axis == 0: for i in range(crop.shape[axis]): img = crop[i, :, :] # get gradient map diffuse_1 = anisotropic_diffusion(img, niter=15, option=2).astype(np.uint8) diffuse_2 = anisotropic_diffusion(img, niter=30, option=2).astype(np.uint8) gradient_1 = self.Sobel(diffuse_1, 3) gradient_2 = self.Sobel(diffuse_2, 3) self.pack[i, 0, :, :] = img self.pack[i, 1, :, :] = gradient_1 self.pack[i, 2, :, :] = gradient_2 print('Axis 0 finished.') elif axis == 1: for i in range(crop.shape[axis]): img = crop[:, i, :] # get gradient map diffuse_1 = anisotropic_diffusion(img, niter=15, option=2).astype(np.uint8) diffuse_2 = anisotropic_diffusion(img, niter=30, option=2).astype(np.uint8) gradient_1 = self.Sobel(diffuse_1, 3) gradient_2 = self.Sobel(diffuse_2, 3) self.pack[i, 0, :, :] = img self.pack[i, 1, :, :] = gradient_1 self.pack[i, 2, :, :] = gradient_2 print('Axis 1 finished.') else: print('Error: Axis unrecognized.')
def Grad_map(self, img, niter, kernel_size): diffuse = anisotropic_diffusion(img, niter=niter, option=2) diffuse = np.uint8(diffuse) sobelx = cv2.Sobel(diffuse, cv2.CV_64F, 1, 0, ksize=kernel_size) sobely = cv2.Sobel(diffuse, cv2.CV_64F, 0, 1, ksize=kernel_size) gradient = np.sqrt(np.square(sobelx) + np.square(sobely)) gradient *= 1.0 / gradient.max() return np.float32(gradient)
def anisomedian_decision(prediction_proba, niter = 5, selem = disk(1), percentile = 75): diffusion = anisotropic_diffusion(prediction_proba, niter=niter) normalization = diffusion / np.linalg.norm(diffusion) med = median(normalization, selem) decision = med > np.percentile(med, 75) return decision
def Kmeans(im): h, w = im.shape kmeans = KMeans(n_clusters=2) diffuse = anisotropic_diffusion(im, niter=5, option=2).astype(np.float32) im_enhance = ContrastEnhance(diffuse) vectorized = im_enhance.reshape((-1, 1)) kmeans.fit(vectorized) y_kmeans = kmeans.predict(vectorized) y = y_kmeans.reshape((h, w)) return y
def filter(xs): """ Method to filter noise out of an image. :param xs: an array corresponding to a noisy image :return: An array corresponding to a cleaner image """ img_filtered = anisotropic_diffusion(xs, gamma=0.1, kappa=40, niter=20, option=1) return prepare_to_plot(img_filtered)
def binarize(vol, vol_seg, verbose): h, slc, w = vol.shape # define the output vol_base_1 = np.zeros(vol.shape, dtype=np.uint8) # otsu vol_base_2 = np.zeros(vol.shape, dtype=np.uint8) # diffuse+otsu vol_opt = np.zeros(vol.shape, dtype=np.uint8) # seg+diffuse+otsu idx = random.randint(0, slc - 1) for i in range(slc): # output 1 im = Int8(vol[:, i, :]) otsu_th_1 = threshold_otsu(im) vol_base_1[:, i, :] = np.uint8(im > otsu_th_1) * 255 # output 2 diffuse = anisotropic_diffusion(im, niter=5, option=2).astype(np.float32) im_enhance = ContrastEnhance(diffuse) otsu_th_2 = threshold_otsu(im_enhance) vol_base_2[:, i, :] = np.uint8(im_enhance > otsu_th_2) * 255 # proposed im_seg = Int8(vol_seg[:, i, :]) diffuse_seg = anisotropic_diffusion(im_seg, niter=5, option=2).astype(np.float32) im_enhance = ContrastEnhance(diffuse_seg) otsu_th_opt = threshold_otsu(im_enhance) vol_opt[:, i, :] = np.uint8(im_enhance > otsu_th_opt) * 255 if verbose == True and i == idx: plt.figure(figsize=(18, 8)) plt.axis('off') plt.title('base1 -- base2 -- proposed', fontsize=15) plt.imshow(np.concatenate( (vol_base_1[:, i, :], vol_base_2[:, i, :], vol_opt[:, i, :]), axis=1), cmap='gray') plt.show() return vol_base_1, vol_base_2, vol_opt
def __init__(self, dataroot, file_x, file_y, im_size): # Load in nii as a 3d matrix data_x_nii = nib.load(dataroot + file_x) data_x = np.array(data_x_nii.dataobj) data_y_nii = nib.load(dataroot + file_y) data_y = np.array(data_y_nii.dataobj) num = data_y.shape[2] self.pack = np.zeros([num, 3, im_size, im_size]).astype(np.float32) t1 = time.time() for i in range(num): data_x_crop = self.Center_Crop(data_x[:, :, i * num_frame], im_size) data_y_crop = self.Center_Crop(data_y[:, :, i], im_size) # get gradient map diffuse_1 = anisotropic_diffusion(data_x_crop, niter=15, option=2).astype(np.uint8) diffuse_2 = anisotropic_diffusion(data_x_crop, niter=30, option=2).astype(np.uint8) gradient_1 = self.Sobel(diffuse_1, 3) gradient_2 = self.Sobel(diffuse_2, 3) # Threshold bg_1 = gradient_1[400:500, 0:100] bg_2 = gradient_2[400:500, 0:100] gradient_1[gradient_1 < bg_1.mean() + 25] = 0 gradient_2[gradient_2 < bg_2.mean() + 25] = 0 self.pack[i, 0, :, :] = data_x_crop self.pack[i, 1, :, :] = gradient_1 self.pack[i, 2, :, :] = gradient_2 t2 = time.time() print('Processing time: ', np.int(t2 - t1), 's')
def smooth_data(image, sel): if (sel == 0): return image if (sel == 1): temp = np.zeros(shape=image.shape) for thickness in range(image.shape[0]): temp[thickness] = gaussian_filter(image[thickness], sigma=1) if (sel == 2): temp = gaussian_filter(image, 1) else: temp = anisotropic_diffusion(image, niter=5, kappa=300) return temp
def ani_dif(img, niter=5, kappa=50, gamma=0.1, voxelspacing=None, option=1): print('Applying Anisotropic Diffusion...') t0 = time.time() if type(img) == np.ndarray: img = list([img]) im_dif = [] for imm in range(len(img)): im_dif.append( anisotropic_diffusion(img[imm], niter, kappa, gamma, voxelspacing, option) * (img[imm] > 0)) print('Applying Anisotropic Diffusion took ', round(time.time() - t0, 2), 'seconds') return im_dif
def segment_lung(img): #function sourced from https://www.kaggle.com/c/data-science-bowl-2017#tutorial """ This segments the Lung Image(Don't get confused with lung nodule segmentation) """ mean = np.mean(img) std = np.std(img) img = img - mean img = img / std middle = img[100:400, 100:400] mean = np.mean(middle) max = np.max(img) min = np.min(img) #remove the underflow bins img[img == max] = mean img[img == min] = mean #apply median filter img = median_filter(img, size=3) #apply anistropic non-linear diffusion filter- This removes noise without blurring the nodule boundary img = anisotropic_diffusion(img) kmeans = KMeans(n_clusters=2).fit( np.reshape(middle, [np.prod(middle.shape), 1])) centers = sorted(kmeans.cluster_centers_.flatten()) threshold = np.mean(centers) thresh_img = np.where(img < threshold, 1.0, 0.0) # threshold the image eroded = morphology.erosion(thresh_img, np.ones([4, 4])) dilation = morphology.dilation(eroded, np.ones([10, 10])) labels = measure.label(dilation) label_vals = np.unique(labels) regions = measure.regionprops(labels) good_labels = [] for prop in regions: B = prop.bbox if B[2] - B[0] < 475 and B[3] - B[1] < 475 and B[0] > 40 and B[2] < 472: good_labels.append(prop.label) mask = np.ndarray([512, 512], dtype=np.int8) mask[:] = 0 # # The mask here is the mask for the lungs--not the nodes # After just the lungs are left, we do another large dilation # in order to fill in and out the lung mask # for N in good_labels: mask = mask + np.where(labels == N, 1, 0) mask = morphology.dilation(mask, np.ones([10, 10])) # one last dilation # mask consists of 1 and 0. Thus by mutliplying with the orginial image, sections with 1 will remain return mask * img
def get_valve(self, M, W2H2, mask): # take window of threshold difference between myocardium and reconstruction thresh = thresholding_fn(M - W2H2, thresh=self.thresh2) valve = thresh * mask valve_aniso = np.empty_like(valve) # anisotropic diffusion to connect segments for j in range(M.shape[2]): valve_aniso[:, :, j] = mp.anisotropic_diffusion(valve[:, :, j], niter=5, kappa=20) valve_aniso[valve_aniso > 0] = 1 return valve_aniso
def remove_valve(WH, S, mask, threshold): M = WH + S # take window of threshold S matrix if len(mask.shape) == 2: mask = np.expand_dims(mask, -1) S_prime = mask * thresholding_fn(S, thresh=threshold) # anisotropic diffusion to connect segments S_aniso = np.empty_like(S_prime) for j in range(S_prime.shape[2]): S_aniso[:, :, j] = mp.anisotropic_diffusion(S_prime[:, :, j], niter=5, kappa=20) # remove from rnmf S_aniso = np.reshape(S_prime, newshape=M.shape) M_prime = M - M * S_aniso return M, M_prime
def __call__(self, image=None): """ Call operator for the VesselTrackHFM class Wrapper around pre-processing and the PDE solver Given an image, produces a distance map and (optionally) a geodesic flow tensor It also returns the post-processed vesselness image (used to compute the speed function for the HFM solver) :param image: (numpy ndarray) : Liver MR scan, expected to be 3-D :return vesselness_image: (numpy ndarray) :return: distance_map: (numpy ndarray) Distance map w.r.t. vessels (in general tubular structures in image) :return: geodesic_flows: (numpy ndarray) Geodesic flow vectors [geodesic_flows.ndim = image.ndim+1] """ # Apply anisotropic diffusion filtering # Option 1 corresponds to exponential function of gradient magnitude as conduction co-eff as shown in # 'Scale-Space and Edge Detection Using Anisotropic Diffusion' Perona and Malik (1990) # Option 3 corresponds to the conduction co-efficient given in 'Robust Anistropic Diffusion' by # Black et al. (1998) # This option seems to fix underflow occurring in certain images image = anisotropic_diffusion(img=image, niter=10, kappa=25, option=3) # Pre-processing of the image to highlight vessels/tubular structures hessian_multiscale, eigenvals_multiscale, vesselness_multiscale = self._multiscale_hessian_eigenanalysis( image) vesselMask = self.create_vessel_mask(vesselness_multiscale) if self.model.lower() == 'isotropic': seeds = self._solve_pde(image=vesselness_multiscale, vesselMask=vesselMask) elif self.model.lower() == 'riemann': seeds = self._solve_pde(image=hessian_multiscale, vesselness=vesselness_multiscale, vesselMask=vesselMask) else: raise RuntimeError('{} is not a valid model'.format(self.model)) if self.get_distance_map > 0: distance_map = self.output['values'] else: distance_map = None return vesselness_multiscale, distance_map, seeds
def upload(): if request.method == 'POST': f = request.files.get('file') f.filename = "Noisy_Image.png" f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename)) img_url = os.path.join(app.config['UPLOADED_PATH'], "Noisy_Image.png") f.filename = img_as_float(io.imread(img_url, as_gray=True)) img_aniso_filtered = anisotropic_diffusion(f.filename, niter=50, kappa=50, gamma=0.2, option=2) cln_img_url = os.path.join(app.config['UPLOADED_PATH'], "Clean_Image.png") plt.imsave(cln_img_url, img_aniso_filtered, cmap='gray') return render_template('index.html')
def pmf(arr, iterations=350, k=.16, g=0.02, option=2, suppress=True): pmf_arr = [] its = [] for i in range(iterations): print(f"running iteration {i}") filtered_arr = anisotropic_diffusion(arr, niter=1, kappa=k, gamma=g, option=option) if suppress: test = prevent_gradient_sharpening(arr, filtered_arr) # print(np.sum(np.abs(test-arr)), np.sum(np.abs(test-filtered_arr)), np.sum(np.abs(filtered_arr-arr))) arr = test else: arr = filtered_arr pmf_arr.append(arr) its.append(i) return pmf_arr, its
def remove_valve(self, WH, S, mask): M = WH + S # take window of threshold S matrix S_prime = mask * thresholding_fn(S, thresh=self.thresh1) # anisotropic diffusion to connect segments S_aniso = np.empty_like(S_prime) for j in range(S_prime.shape[2]): S_aniso[:, :, j] = mp.anisotropic_diffusion(S_prime[:, :, j], niter=5, kappa=20) # remove from rnmf S_aniso = np.reshape(S_prime, newshape=(self.vert, self.horz, self.m)) # M_prime = np.maximum(0, M-S_prime) M_prime = M - M * S_aniso return M, M_prime
def kmeans(self, image): # Etape de prétraitement : application d'un filtre anisotrope image = mfs.anisotropic_diffusion(image, niter=1, kappa=50, gamma=0.1, voxelspacing=None, option=1) vectorized = image.flatten() vectorized = np.float32(vectorized) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) ret, label, center = cv2.kmeans(vectorized, self.segments, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) res = center[label.flatten()] segmented_image = res.reshape((image.shape)) return label.reshape( (image.shape[0], image.shape[1])), segmented_image.astype(np.uint8), center
def expose(self, subspaced_X, y): # Empty model model = np.zeros( (self.grain, self.grain, len(self.classes_))).astype('float_') # Exposing X_locations = self.locations(subspaced_X) unique, counts = np.unique(np.array( [X_locations[:, 0], X_locations[:, 1], y]).T, return_counts=True, axis=0) model[unique[:, 0], unique[:, 1], unique[:, 2]] += counts # Blurring and normalization for layer in range(len(self.classes_)): plane = model[:, :, layer] plane = anisotropic_diffusion(plane, niter=self.a_steps) plane /= np.max(plane) plane = filters.gaussian(plane, sigma=self.focus) plane /= np.max(plane) model[:, :, layer] = plane model /= np.max(model) return model
del Va, Vb # Load the paired x-y pickle file and crop to [r:-r] with open(FR_dir[0], 'rb') as f: pack_xy = pickle.load(f) pack_xy = pack_xy[radius:-radius] # Diffuse and compute gradient t1 = time.time() for i in range(len(pack_xy)): x = np.zeros([3, 1024, 512], dtype=np.float32) gradient = np.zeros([1024, 512], dtype=np.float32) img_sf = V_sf[i, :, :] diffuse = anisotropic_diffusion(img_sf, niter=20, option=2).astype(np.float32) gradient[:, :500] = Sobel(diffuse[:, :500], 3) x[0, :, :] = pack_xy[i][0] x[1, :, :] = gradient x[2, :, :] = img_sf train_pair = train_pair + ((x, pack_xy[i][1]), ) t2 = time.time() print('volume %d. time consumption: %.4f min' % (vol, (t2 - t1) / 60)) #%% #img = train_pair[400][0] #plt.figure(figsize=(12,12)) #plt.subplot(1,3,1),plt.axis('off'),plt.imshow(img[0,:,:],cmap='gray')
def denoise_perframe(fm, method, **kwargs): if method == 'gaussian': return cv2.GaussianBlur(fm, **kwargs) elif method == 'anisotropic': return anisotropic_diffusion(fm, **kwargs)
opt = np.zeros([c,r]) for i in range(r): vector = np.transpose(img[i,:]) opt[:,r-i-1] = vector return opt x_nii = nib.load(dataroot+file_x) x = np.array(x_nii.dataobj) y_nii = nib.load(dataroot+file_y) y = np.array(y_nii.dataobj) # img_x = cw90(x[:,:,1500]) img_y = cw90(y[:,:,289]) img_smooth_1 = anisotropic_diffusion(img_y,niter=30,option=1) img_smooth_2 = anisotropic_diffusion(img_x,niter=12,option=2) img_smooth_3 = anisotropic_diffusion(img_y,niter=30,option=3) plt.figure(figsize=(18,12)) plt.subplot(1,3,1),plt.imshow(img_x) plt.subplot(1,3,2),plt.imshow(img_y) plt.subplot(1,3,3),plt.imshow(img_smooth_2) #%% Column-out n_cl = 300 x = img_x[:,n_cl] y = img_y[:,n_cl] y_smooth = img_smooth_2[:,n_cl]
def anisotropic(self): img_filtered = anisotropic_diffusion(self.processedImage) self.processedImage = img_filtered.astype('uint8')
7000:13000].astype(np.float32) im2 = load('Sigma0_IW1_VH_mst_22Jun2018')[0][7000:13000, 7000:13000].astype(np.float32) im = np.hypot(im1, im2) bd = (im <= 1e-6) | (im > 10) im = np.arcsin(im2 / im) im = np.maximum(1e-6, im) imor = im.copy() fix_pixels(im, bd) u = gaussian_filter(im, 4) u = anisotropic_diffusion(im, 50, 20, 0.25, option=1) #u = im G1 = np.hypot(*np.gradient(im)) G2 = np.hypot(*np.gradient(u)) plt.subplot(2, 2, 1), plt.imshow(imor, cmap='gray') plt.xticks([]), plt.yticks([]) plt.subplot(2, 2, 2), plt.imshow(u, cmap='gray') plt.xticks([]), plt.yticks([]) plt.subplot(2, 2, 3), plt.imshow(G1, cmap='gray') plt.xticks([]), plt.yticks([]) plt.subplot(2, 2, 4), plt.imshow(G2, cmap='gray') plt.xticks([]), plt.yticks([])
import cv2 from skimage.feature import local_binary_pattern import matplotlib.pyplot as plt import numpy as np import os # Utilisation d'un filtre anisotrope import medpy.filter.smoothing as mfs path = './Base de données/wetransfer-063323/' fichiers = os.listdir(path) for fichier in fichiers: image = cv2.imread(path+fichier, -1) # Prétraitement = filtre anisotrope image = mfs.anisotropic_diffusion(image, niter=1, kappa=50, gamma=0.1, voxelspacing=None, option=1) #plt.imshow(image, cmap=plt.get_cmap('gray')) #plt.show() # Paramètres du calcul de LBP radius = 1 n_points = 8 * radius L = local_binary_pattern(image, n_points, radius, method='default') cv2.imwrite("ImagesLBP/R1P8/"+fichier, L.astype("uint16"))
import argparse import sys import warnings import numpy as np import skimage.io import skimage.util from medpy.filter.smoothing import anisotropic_diffusion parser = argparse.ArgumentParser() parser.add_argument('input_file', type=argparse.FileType('r'), default=sys.stdin, help='input file') parser.add_argument('out_file', type=argparse.FileType('w'), default=sys.stdin, help='out file (TIFF)') parser.add_argument('niter', type=int, help='Number of iterations', default=1) parser.add_argument('kappa', type=int, help='Conduction coefficient', default=50) parser.add_argument('gamma', type=float, help='Speed of diffusion', default=0.1) parser.add_argument('eqoption', type=int, choices=[1,2], help='Perona Malik diffusion equation', default=1) args = parser.parse_args() with warnings.catch_warnings(): warnings.simplefilter("ignore") #to ignore FutureWarning as well img_in = skimage.io.imread(args.input_file.name, plugin='tifffile') res = anisotropic_diffusion(img_in, niter=args.niter, kappa=args.kappa, gamma=args.gamma, option=args.eqoption) res[res<-1]=-1 res[res>1]=1 res = skimage.util.img_as_uint(res) #Attention: precision loss skimage.io.imsave(args.out_file.name, res, plugin='tifffile')
if ('sigma' in products): params = products['sigma'] for sn in sigmaNames: print(sn) s = envi.load(sn)[0] if mode == 'zone': s = s[zone[0][0]:zone[1][0], zone[0][1]:zone[1][1]] bad_data = (s < 1e-6) | (s > 10) | (s < 1e-6) | (s > 10) s = np.clip(s, 1e-6, 10) s = np.log10(s) fix_pixels(s, bad_data) s = anisotropic_diffusion(s, params[0], params[1], 0.2, option=1) if mode == 'zone': tnsr_zone[..., product_index] = s product_index += 1 bd_zone |= bad_data elif mode == 'full': tnsr_full[..., product_index] = s product_index += 1 bd_full |= bad_data elif mode == 'both': tnsr_full[..., product_index] = s tnsr_zone[..., product_index] = s[zone[0][0]:zone[1][0], zone[0][1]:zone[1][1]] product_index += 1 bd_full |= bad_data bd_zone |= bad_data[zone[0][0]:zone[1][0], zone[0][1]:zone[1][1]]
dates = os.listdir(s_d) for da in dates: da_d = os.path.join(s_d, da) series = os.listdir(da_d) for se in series: se_d = os.path.join(da_d, se) perspectives = os.listdir(se_d) for pe in perspectives: if "SER1" in pe or "SER2" in pe: #1 is for sagittal view, 2 is for axial view, if you need more, check SER3 and SER4. pe_d = os.path.join(se_d, pe) im = Image.open(os.path.join(pe_d, 'avreage.png')) print(pe_d) img = np.array(im) if d in "R": img = np.fliplr(img) i = anisotropic_diffusion(img, niter=5, kappa=20) image = Image.fromarray( i.astype('uint8')).convert("L") #image=image.filter(ImageFilter.SHARPEN) image = image.filter(ImageFilter.EDGE_ENHANCE) if d in "R": if "SER1" in pe: image.save( 'T:/CleanedMostData/MRI/processedMRI/side/' + p[1:5] + "_R.png" ) #here they change the storage structure if "SER2" in pe: image.save( 'T:/CleanedMostData/MRI/processedMRI/up/' + p[1:5] + "_R.png") if d in "L":
for index in tqdm(range(len(filepaths_imgs))): sc, sp, o, t = utils.readMhd(filepaths_imgs[index]) t_img, t_wld = utils.getImgWorldTransfMats(sp, t) z_max = sc.shape[0] z_max_idx = z_max - (sc.shape[0] % 3) for id_n in range(int(z_max_idx * .6), int(z_max_idx * .9), 3): origins.append(o) input_shapes.append(sc.shape) slide = sc[int(id_n) - 1:int(id_n) + 2, :, :] slide = equalize_hist(slide) slide = anisotropic_diffusion(slide, voxelspacing=sp, kappa=20, gamma=0.01, niter=100, option=2) if sc.shape[1:] != (512, 512): zoom_factors = np.array((512, 512)) / np.array(sc.shape[1:]) slide_a = zoom(slide[0], zoom_factors) slide_b = zoom(slide[1], zoom_factors) slide_c = zoom(slide[2], zoom_factors) slide = np.dstack([slide_a, slide_b, slide_c]) else: slide = np.dstack([slide[0], slide[1], slide[2]]) filename = 'ts-%s-%s.jpg' % (str( filepaths_imgs[index].split('/')[-1].split('.')[0]).zfill(4), str(id_n).zfill(4))