def strict_local_maximum(prob_map): prob_gau = np.zeros(prob_map.shape) sn.gaussian_filter(prob_map, 2, output=prob_gau, mode='mirror') prob_fil = np.zeros(prob_map.shape) sn.rank_filter(prob_gau, -2, output=prob_fil, footprint=np.ones([3, 3])) temp = np.logical_and(prob_gau > prob_fil, prob_map > HIGH_PROB) * 1. idx = np.where(temp > 0) return idx
def nms(img, radius, threshold): circle = skimage.morphology.disk(radius) filtered = ndimage.rank_filter(img, rank=-1, footprint=circle) mask = img == filtered result = np.where(filtered > threshold, filtered, 0) result = np.where(mask,255,0) return result
def denoise(img): tmp = ndimage.minimum_filter(img, 3) tmp = wiener(tmp, 2) tmp = ndimage.maximum_filter(tmp, 2) tmp = ndimage.rank_filter(tmp, 2, 2) tmp = ndimage.gaussian_filter(tmp, 0.5) return tmp
def harris(im, sigma, thresh=None, radius=None): """ Harris corner detector Parameters ---------- im: numpy.ndarray Image to be processed sigma: float Standard deviation of smoothing Gaussian thresh: float (optional) radius: float (optional) Radius of region considered in non-maximal suppression Returns ------- cim: numpy.ndarray Binary image marking corners r: numpy.ndarray Row coordinates of corner points. Returned only if none of `thresh` and `radius` are None. c: numpy.ndarray Column coordinates of corner points. Returned only if none of `thresh` and `radius` are None. """ if im.ndim == 3: im = rgb2gray(im) dx = np.tile([[-1, 0, 1]], [3, 1]) dy = dx.T Ix = convolve2d(im, dx, 'same') Iy = convolve2d(im, dy, 'same') f_wid = np.round(3 * np.floor(sigma)) G = norm.pdf(np.arange(-f_wid, f_wid + 1), loc=0, scale=sigma).reshape(-1, 1) G = G.T * G G /= G.sum() Ix2 = convolve2d(Ix**2, G, 'same') Iy2 = convolve2d(Iy**2, G, 'same') Ixy = convolve2d(Ix * Iy, G, 'same') cim = (Ix2 * Iy2 - Ixy**2) / (Ix2 + Iy2 + 1e-12) if thresh is None or radius is None: return cim else: size = int(2 * radius + 1) mx = rank_filter(cim, -1, size=size) cim = (cim == mx) & (cim > thresh) r, c = cim.nonzero() return cim, r, c
def denoise_log(img, log=0.25): tmp = exposure.adjust_log(img, log) tmp = ndimage.minimum_filter(tmp, 3) tmp = ndimage.maximum_filter(tmp, 5) tmp = ndimage.uniform_filter(tmp, 3) tmp = wiener(tmp, 2) tmp = ndimage.median_filter(tmp, 3) tmp = ndimage.rank_filter(tmp, 1, 2) tmp = uf.convert_to_img(tmp) return tmp
def npa(log_results, InputImage): multi_npa = ndimage.rank_filter(log_results, rank=-1, size=3) depth = multi_npa.shape[0] result = np.zeros(InputImage.shape) for i in range(multi_npa.shape[1]): for j in range(multi_npa.shape[2]): maxi = -30 for d in range(depth): if (log_results[d][i][j] > maxi): maxi = log_results[d][i][j] result[i][j] = maxi return result
def applyFilter(Rx, filterInfo): import scipy.ndimage as sn # contains the filters if ('gauss' in filterInfo[0]): try: Nf = float(filterInfo[1]) except: print( ' Failed to obtain <sigma> for the Gaussian filter. Exiting.') sys.exit(1) else: try: Nf = int(filterInfo[1]) except: print(' Failed to obtain <size> for the filters. Exiting.') sys.exit(1) if ('median' in filterInfo[0]): print(' Median {0}x{0} filter applied. '.format(Nf)) Rf = sn.median_filter(Rx, size=Nf) elif ('perc' in filterInfo[0]): print(' Percentile 60 {0}x{0} filter applied. '.format(Nf)) Rf = sn.percentile_filter(Rx, 60, size=Nf) elif ('rank' in filterInfo[0]): print(' Rank 5 {0}x{0} filter applied. '.format(Nf)) Rf = sn.rank_filter(Rx, 5, size=Nf) elif ('gauss' in filterInfo[0]): print(' Gaussian sigma={} filter applied. '.format(Nf)) Rf = sn.gaussian_filter(Rx, sigma=Nf) elif ('local' in filterInfo[0]): print(' Local mean {0}x{0} filter applied. '.format(Nf)) Rf = sn.uniform_filter(Rx, size=Nf) elif ('max' in filterInfo[0]): print('Max {0}x{0} filter applied. '.format(Nf)) Rf = sn.maximum_filter(Rx, size=Nf) else: print(' No filter applied. ') Rf = Rx return Rf
def eval(self, source_data): return ndimage.rank_filter(source_data, *self.args, **self.kwargs)
def filter(original_images, transformation): """ :param original_images: :param transformation: :return: """ nb_images, img_rows, img_cols, nb_channels = original_images.shape transformed_images = [] if (transformation == TRANSFORMATION.filter_sobel): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = filters.sobel(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_median): for img in original_images: img_trans = ndimage.median_filter(img, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_minimum): for img in original_images: img_trans = ndimage.minimum_filter(img, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_maximum): for img in original_images: img_trans = ndimage.maximum_filter(img, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_gaussian): for img in original_images: img_trans = ndimage.gaussian_filter(img, sigma=1) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_rank): for img in original_images: img_trans = ndimage.rank_filter(img, rank=15, size=3) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_entropy): for img in original_images: radius = 2 if (nb_channels == 3): radius = 1 img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) """ requires values in range [-1., 1.] """ img = (img - 0.5) * 2. """ skimage-entropy function returns values in float64, however opencv only supports float32. """ img_trans = np.float32( filters.rank.entropy(img, disk(radius=radius))) """ rescale back into range [0., 1.] """ img_trans = (img_trans / 2.) + 0.5 if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_roberts): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = roberts(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_scharr): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = scharr(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_prewitt): for img in original_images: if (nb_channels == 3): img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = img.reshape(img_rows, img_cols) img_trans = prewitt(img) if (nb_channels == 3): img_trans = cv2.cvtColor(img_trans, cv2.COLOR_GRAY2RGB) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_meijering): for img in original_images: if nb_channels == 1: img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) img_trans = meijering(img, sigmas=[0.01]) if nb_channels == 1: img_trans = img_trans[:, :, 1] transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_sato): for img in original_images: img_trans = sato(img) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_frangi): for img in original_images: img_trans = frangi(img) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_hessian): for img in original_images: img_trans = hessian(img) transformed_images.append(img_trans) elif (transformation == TRANSFORMATION.filter_skeletonize): for img in original_images: img = invert(img) img = img.reshape((img_rows, img_cols)) img = skeletonize(img) transformed_images.append(img) elif (transformation == TRANSFORMATION.filter_thin): for img in original_images: img = img.reshape(img_rows, img_cols) img = thin(img, max_iter=100) transformed_images.append(img) else: raise ValueError('{} is not supported.'.format(transformation)) transformed_images = np.stack(transformed_images, axis=0) if (nb_channels == 1): # reshape a 3d to a 4d transformed_images = transformed_images.reshape( (nb_images, img_rows, img_cols, nb_channels)) return transformed_images
def extract_features(image_number, slice_number): # extracts features for [image_number]_[slice_number]_t1.tif and [image_number]_[slice_number]_t2.tif # Input: # image_number - Which subject (scalar) # slice_number - Which slice (scalar) # Output: # X - N x k dataset, where N is the number of pixels and k is the total number of features # features - k x 1 cell array describing each of the k features base_dir = '../data/dataset_brains/' t1 = plt.imread(base_dir + str(image_number) + '_' + str(slice_number) + '_t1.tif') t2 = plt.imread(base_dir + str(image_number) + '_' + str(slice_number) + '_t2.tif') fig = plt.figure(figsize=(10, 10)) ax1 = fig.add_subplot(181) ax1.imshow(t1) ax2 = fig.add_subplot(182) ax2.imshow(t2) n = t1.shape[0] features = () #display image t1f = t1.flatten().T.astype(float) t1f = t1f.reshape(-1, 1) t2f = t2.flatten().T.astype(float) t2f = t2f.reshape(-1, 1) X = np.concatenate((t1f, t2f), axis=1) features += ('T1 intensity', ) features += ('T2 intensity', ) #------------------------------------------------------------------# # TODO: Extract more features and add them to X. # Don't forget to provide (short) descriptions for the features #add blurred images to features t1b = ndimage.gaussian_filter(t1, sigma=2) #blurred t1 t2b = ndimage.gaussian_filter(t2, sigma=2) #blurred t2 #display altered images ax3 = fig.add_subplot(183) ax3.imshow(t1b) ax4 = fig.add_subplot(184) ax4.imshow(t2b) t1b = t1b.flatten().T.astype(float) t1b = t1b.reshape(-1, 1) t2b = t2b.flatten().T.astype(float) t2b = t2b.reshape(-1, 1) X = np.concatenate((X, t1b), axis=1) X = np.concatenate((X, t2b), axis=1) features += ('T1 blurred intensity', ) features += ('T2 blurred intensity', ) #minimum filter t1min = ndimage.minimum_filter(t1, size=5) t2min = ndimage.minimum_filter(t2, size=5) ax5 = fig.add_subplot(185) ax5.imshow(t1min) ax6 = fig.add_subplot(186) ax6.imshow(t2min) t1min = t1min.flatten().T.astype(float) t1min = t1min.reshape(-1, 1) t2min = t2min.flatten().T.astype(float) t2min = t2min.reshape(-1, 1) X = np.concatenate((X, t1min), axis=1) X = np.concatenate((X, t2min), axis=1) features += ('T1 minimum intensity', ) features += ('T2 minimum intensity', ) #maximum filter t1max = ndimage.maximum_filter(t1, size=5) t2max = ndimage.maximum_filter(t2, size=5) ax7 = fig.add_subplot(187) ax7.imshow(t1max) ax8 = fig.add_subplot(188) ax8.imshow(t2max) t1max = t1max.flatten().T.astype(float) t1max = t1max.reshape(-1, 1) t2max = t2max.flatten().T.astype(float) t2max = t2max.reshape(-1, 1) X = np.concatenate((X, t1max), axis=1) X = np.concatenate((X, t2max), axis=1) features += ('T1 maximum intensity', ) features += ('T2 maximum intensity', ) #gaussian gradient magnitude t1_ggm = ndimage.gaussian_gradient_magnitude(t1, sigma=2) t2_ggm = ndimage.gaussian_gradient_magnitude(t2, sigma=2) fig1 = plt.figure(figsize=(10, 10)) ax9 = fig1.add_subplot(181) ax9.imshow(t1_ggm) ax10 = fig1.add_subplot(182) ax10.imshow(t2_ggm) t1_ggm = t1_ggm.flatten().T.astype(float) t1_ggm = t1_ggm.reshape(-1, 1) t2_ggm = t2_ggm.flatten().T.astype(float) t2_ggm = t2_ggm.reshape(-1, 1) X = np.concatenate((X, t1_ggm), axis=1) X = np.concatenate((X, t2_ggm), axis=1) features += ('T1 gaussian gradient magnitude intensity', ) features += ('T2 gaussian gradient magnitude intensity', ) #gaussian la place (second derivative) t1_glp = ndimage.gaussian_laplace(t1, sigma=1) t2_glp = ndimage.gaussian_laplace(t2, sigma=1) ax11 = fig1.add_subplot(183) ax11.imshow(t1_glp) ax12 = fig1.add_subplot(184) ax12.imshow(t2_glp) t1_glp = t1_glp.flatten().T.astype(float) t1_glp = t1_glp.reshape(-1, 1) t2_glp = t2_glp.flatten().T.astype(float) t2_glp = t2_glp.reshape(-1, 1) X = np.concatenate((X, t1_glp), axis=1) X = np.concatenate((X, t2_glp), axis=1) features += ('T1 gaussian la place intensity', ) features += ('T2 gaussian la place intensity', ) #median filter (smoothning filter) t1_median = ndimage.median_filter(t1, size=5) t2_median = ndimage.median_filter(t2, size=5) ax13 = fig1.add_subplot(185) ax13.imshow(t1_median) ax14 = fig1.add_subplot(186) ax14.imshow(t2_median) t1_median = t1_median.flatten().T.astype(float) t1_median = t1_median.reshape(-1, 1) t2_median = t2_median.flatten().T.astype(float) t2_median = t2_median.reshape(-1, 1) X = np.concatenate((X, t1_median), axis=1) X = np.concatenate((X, t2_median), axis=1) features += ('T1 median intensity', ) features += ('T2 median intensity', ) #sobel filter (edge detection, derivative filter, horizontal/vertical lines, some smoothning) t1_sobel = ndimage.sobel(t1) t2_sobel = ndimage.sobel(t2) ax15 = fig1.add_subplot(187) ax15.imshow(t1_sobel) ax16 = fig1.add_subplot(188) ax16.imshow(t2_sobel) t1_sobel = t1_sobel.flatten().T.astype(float) t1_sobel = t1_sobel.reshape(-1, 1) t2_sobel = t2_sobel.flatten().T.astype(float) t2_sobel = t2_sobel.reshape(-1, 1) X = np.concatenate((X, t1_sobel), axis=1) X = np.concatenate((X, t2_sobel), axis=1) features += ('T1 sobel intensity', ) features += ('T2 sobel intensity', ) # rank filter (smoothning filter) t1_rank = ndimage.rank_filter(t1, rank=30, size=10) t2_rank = ndimage.rank_filter(t2, rank=30, size=10) fig2 = plt.figure(figsize=(10, 10)) ax17 = fig2.add_subplot(181) ax17.imshow(t1_rank) ax18 = fig2.add_subplot(182) ax18.imshow(t2_rank) t1_rank = t1_rank.flatten().T.astype(float) t1_rank = t1_rank.reshape(-1, 1) t2_rank = t2_rank.flatten().T.astype(float) t2_rank = t2_rank.reshape(-1, 1) X = np.concatenate((X, t1_sobel), axis=1) X = np.concatenate((X, t2_sobel), axis=1) features += ('T1 rank intensity', ) features += ('T2 rank intensity', ) # prewitt filter (edge detection, derivative filter, horizontal/vertical lines, some smoothning) # looks like sobel filter but has different kernel, only horizonal or vertical lines t1_prewitt = ndimage.prewitt(t1) t2_prewitt = ndimage.prewitt(t2) ax19 = fig2.add_subplot(183) ax19.imshow(t1_prewitt) ax20 = fig2.add_subplot(184) ax20.imshow(t2_prewitt) t1_prewitt = t1_prewitt.flatten().T.astype(float) t1_prewitt = t1_prewitt.reshape(-1, 1) t2_prewitt = t2_prewitt.flatten().T.astype(float) t2_prewitt = t2_prewitt.reshape(-1, 1) X = np.concatenate((X, t1_prewitt), axis=1) X = np.concatenate((X, t2_prewitt), axis=1) features += ('T1 prewitt intensity', ) features += ('T2 prewitt intensity', ) #------------------------------------------------------------------# return X, features
from scipy import ndimage, misc import matplotlib.pyplot as plt fig = plt.figure() plt.gray() # show the filtered result in grayscale ax1 = fig.add_subplot(121) # left side ax2 = fig.add_subplot(122) # right side ascent = misc.ascent() result = ndimage.rank_filter(ascent, rank=42, size=20) ax1.imshow(ascent) ax2.imshow(result) plt.show()
#=input=======================================================================# Rdict = readNumpyZTile(filename) R = Rdict['R'] Rdims = np.array(np.shape(R)) ROrig = Rdict['GlobOrig'] print(' Rdims = {} '.format(Rdims)) print(' ROrig = {} '.format(ROrig)) #=filtering===================================================================# if (sigma is not None): print(' Applying the gaussian filter with σ=' + str(sigma) + '.') R = sn.gaussian_filter(R, sigma) elif maxi: print(' Applying the maximum filter.') R = sn.maximum_filter(R, size=fsize) elif medi: print(' Applying the median filter.') R = sn.median_filter(R, size=fsize) elif mini: print(' Applying the minumum filter.') R = sn.minimum_filter(R, size=fsize) elif (rank is not None): print(' Applying the rank filter. Selecting values at rank ' + str(rank) + '/' + str(np.prod(fsize)) + ' from the filter window.') R = sn.rank_filter(R, rank, size=fsize) else: print(' No filter specified. Nothing to do here.') sys.exit() #=output======================================================================# Rdict['R'] = np.round(R, decimals=1) saveTileAsNumpyZ(fileout, Rdict)
def applyFilter(input, filter, title): cleaned = input - filter plotImage(filter, title) plotImage(cleaned, "cleaned = input - " + title) return cleaned x = "2.png" y = "2_output.png" input = spms.imread(x) output = spms.imread(y) #input, output = 1.0*input, 1.0*output input = input / divisionFactor output = output / divisionFactor height, width = input.shape plotImage(input, "input: distorted image") plotImage(output, "output : cleaned image") #maxFilterCleaned = applyFilter(input, ndimage.maximum_filter(input, size=5, mode='nearest'), "maxFilter") #cleaned = applyFilter(input, ndimage.percentile_filter(input, percentile=98, size=5), "percentile_filter") cleaned = applyFilter(input, ndimage.rank_filter(input, rank=-1, size=3), "percentile_filter") #cleaned = applyFilter(cleaned, ndimage.gaussian_filter(cleaned, 2), "gaussian_filter") plt.show()
def rankFiltro(img, width, height): filtrada = ndimage.rank_filter(img, rank=42, size=20) redimensionaImg = misc.imresize(filtrada, (height, width)) return redimensionaImg
plt.show() tmrt_maxf = ndimage.maximum_filter(tmrt, size=3, mode='constant', cval=0) print(np.percentile(tmrt_maxf, 97)) fig = plt.figure(figsize=(14, 7)) ax1 = plt.subplot(2, 2, 1) im1 = ax1.imshow(tmrt, clim=[50, 60]) plt.colorbar(im1) ax2 = plt.subplot(2, 2, 2) im2 = ax2.imshow(tmrt_maxf, clim=[50, 60]) plt.colorbar(im2) plt.tight_layout() plt.show() tmrt_rank = ndimage.rank_filter(tmrt, rank=-1, size=3, mode='constant', cval=0) fig = plt.figure(figsize=(14, 7)) ax1 = plt.subplot(2, 2, 1) im1 = ax1.imshow(tmrt, clim=[50, 60]) plt.colorbar(im1) ax2 = plt.subplot(2, 2, 2) im2 = ax2.imshow(tmrt_rank, clim=[50, 60]) plt.colorbar(im2) plt.tight_layout() plt.show() tmrt_ggm = ndimage.gaussian_gradient_magnitude(tmrt, sigma=10) fig = plt.figure(figsize=(14, 7)) ax1 = plt.subplot(2, 2, 1)
sy_A = sy[0:3, 0:3, :] sob_A = np.hypot(sx_A, sy_A) plt.imshow(sob_A) plt.show() sob = np.hypot(sx, sy) plt.imshow(sob) plt.show() # Some transformation... B = scim.uniform_filter(A) plt.imshow(B) plt.show() # Some transformation... B = scim.rank_filter(A, 5, 10) plt.imshow(B) plt.show() # Some transformation... B = scim.fourier.fourier_uniform(A, [10, 15, 20]) plt.imshow(B) plt.show() # Convolution, let's see if I understand it... # Yes I do understand it now # But not completely ONE = np.ones((98, 98)) ZERO = np.zeros((98, 98)) C = np.stack([ZERO, EYE, ZERO], axis=2)