def rb_closing(bin, size): return filters.uniform_filter( filters.uniform_filter(bin, size, np.float) > 1e-7, size, mode='constant', cval=1, origin=-1) == 1
def plane_sweep_ncc(im_l,im_r,start,steps,wid): """ Find disparity image using normalized cross-corelation """ m,n = im_l.shape # arrays to hold different sums mean_l = zeros((m,n)) mean_r = zeros((m,n)) s = zeros((m,n)) s_l = zeros((m,n)) s_r = zeros((m,n)) # array to hold depth planes dmaps = zeros((m,n,steps)) # compute mean of patch filters.uniform_filter(im_l,wid,mean_l) filters.uniform_filter(im_r,wid,mean_r) # normalized images norm_l = im_l - mean_l norm_r = im_r - mean_r # try different disparities for displ in range(steps): # move left image to the right, compute sums filters.uniform_filter(roll(norm_l,-displ-start)*norm_r,wid,s) # sum nominator filters.uniform_filter(roll(norm_l,-displ-start)*roll(norm_l,-displ-start),wid,s_l) filters.uniform_filter(norm_r*norm_r,wid,s_r) # sum denominator # store ncc scores dmaps[:,:,displ] = s/sqrt(s_l*s_r) # pick best depth for each pixel return argmax(dmaps,axis=2)
def compute_colseps_conv(binary, scale=1.0, csminheight=10, maxcolseps=3): """Find column separators by convolution and thresholding. csminheight: minimum column height (units=scale) maxcolseps: maximum # whitespace column separators """ h, w = binary.shape # find vertical whitespace by thresholding assert np.array_equal(binary, 1.0 * binary) smoothed = filters.gaussian_filter(binary, sigma=(scale, scale * 0.5)) smoothed = filters.uniform_filter(smoothed, size=(5.0 * scale, 1)) thresh = smoothed < np.amax(smoothed) * 0.1 DSAVE("1thresh", thresh) # find column edges by filtering grad = filters.gaussian_filter(binary, (scale, scale * 0.5), order=(0, 1)) grad = filters.uniform_filter(grad, (10.0 * scale, 1)) # grad = abs(grad) # use this for finding both edges grad = (grad > 0.5 * np.amax(grad)) DSAVE("2grad", grad) # combine edges and whitespace seps = np.minimum( thresh, filters.maximum_filter(grad, (int(scale), int(5 * scale)))) seps = filters.maximum_filter(seps, (int(2 * scale), 1)) DSAVE("3seps", seps) # select only the biggest column separators seps = morph.select_regions(seps, sl.dim0, min=csminheight * scale, nbest=maxcolseps) DSAVE("4seps", seps) return seps
def compute_colseps_conv(binary: np.array, scale: float = 1.0, minheight: int = 10, maxcolseps: int = 2) -> np.array: """Find column separators by convolution and thresholding. Args: binary (numpy.array): scale (float): minheight (int): maxcolseps (int): Returns: Separators """ logger.debug('Finding column separators') # find vertical whitespace by thresholding smoothed = gaussian_filter(1.0 * binary, (scale, scale * 0.5)) smoothed = uniform_filter(smoothed, (5.0 * scale, 1)) thresh = (smoothed < np.amax(smoothed) * 0.1) # find column edges by filtering grad = gaussian_filter(1.0 * binary, (scale, scale * 0.5), order=(0, 1)) grad = uniform_filter(grad, (10.0 * scale, 1)) grad = (grad > 0.5 * np.amax(grad)) # combine edges and whitespace seps = np.minimum(thresh, maximum_filter(grad, (int(scale), int(5 * scale)))) seps = maximum_filter(seps, (int(2 * scale), 1)) # select only the biggest column separators seps = morph.select_regions(seps, sl.dim0, min=minheight * scale, nbest=maxcolseps) return seps
def E_lee_filter(band, window, var_noise = 0.25,damp = 1, numL = 1): # band: SAR data to be despeckled (already reshaped into image dimensions) # window: descpeckling filter window (tuple) # default noise variance = 0.25 # assumes noise mean = 0 mean_window = uniform_filter(band, window) mean_sqr_window = uniform_filter(band**2, window) var_window = mean_sqr_window - mean_window**2 SD_window = np.sqrt(var_window); C_U = 1/(np.sqrt(numL)*var_noise) C_max = np.sqrt(1+2/numL) C_L = SD_window/mean_window K = np.exp(-damp*(C_L - C_U)/(C_L - C_max)) if (C_L.all() <= C_U.all()): band_filtered = mean_window elif (C_L.all()>C_U.all() and C_L < C_max): band_filtered = mean_window*K + (1-K)*band else: band_filtered = band; return band_filtered
def smooth_my_data(mydata, grid_space, edge_value): """ Smooth data using scipy's uniform_filter Args: mydata (ndarray): Data to be smoothed grid_space (int) : Smoothing factor (nb of grid points) edge_value (float) : Value to put a field edges Returns: numpy.ndarray : Smoothed data array """ print("+ Smooth Data") size_grid = grid_space*2 + 1 # account for struct size in uniform_filter # WARNING: rpnpy get its fields from librmn fst functions # these fields are most of the times Fortran real*4 array # (dtype=np.float32) # while the default numpy array is C double # (dtype=np.float64) mydata_smooth = np.zeros(mydata.shape, dtype=mydata.dtype, order='FORTRAN') spyfilt.uniform_filter(mydata, output=mydata_smooth, size=size_grid, mode='constant') mydata[:,:] = edge_value (ni, nj) = mydata.shape mydata[grid_space:ni-grid_space, grid_space:nj-grid_space] = \ mydata_smooth[grid_space:ni-grid_space, grid_space:nj-grid_space] del mydata_smooth return mydata
def shi_tomasi_tracking_points(dx, dy, window_size=(3, 3), num=300, border=2): dxdy = dx * dy matrices = np.array([[dx * dx, dxdy], [dxdy, dy * dy]]) sum_matrices = np.zeros_like(matrices) uniform_filter(input=matrices, output=sum_matrices, size=(1, 1, *window_size)) sum_matrices *= 4 corner_vals = np.zeros_like(dx) tracking_points = list() response = list() for i in range(border, matrices.shape[2] - border): for j in range(border, matrices.shape[3] - border): trace = sum_matrices[0, 0, i, j] + sum_matrices[1, 1, i, j] det = sum_matrices[0, 0, i, j] * sum_matrices[ 1, 1, i, j] - sum_matrices[0, 1, i, j] * sum_matrices[1, 0, i, j] if trace**2 / 4 - det > 0: ev1 = trace / 2 + sqrt(trace**2 / 4 - det) ev2 = trace / 2 - sqrt(trace**2 / 4 - det) corner_vals[i, j] = min(ev1, ev2) tracking_points.append([i, j]) response.append(corner_vals[i, j]) order = np.argsort(-np.array(response)) tracking_points = np.array(tracking_points)[order[0:num]] return np.array(tracking_points)
def plane_sweep_ncc(im_l, im_r, start, steps, wid): '''Find disparity image using normalized cross-correlation.''' m, n = im_l.shape # Must match im_r.shape. mean_l = numpy.zeros(im_l.shape) mean_r = numpy.zeros(im_l.shape) s = numpy.zeros(im_l.shape) s_l = numpy.zeros(im_l.shape) s_r = numpy.zeros(im_l.shape) dmaps = numpy.zeros((m, n, steps)) filters.uniform_filter(im_l, wid, mean_l) filters.uniform_filter(im_r, wid, mean_r) norm_l = im_l - mean_l norm_r = im_r - mean_r for disp in range(steps): filters.uniform_filter( numpy.roll(norm_l, -disp - start) * norm_r, wid, s) filters.uniform_filter( numpy.roll(norm_l, -disp - start) * numpy.roll(norm_l, -disp - start), wid, s_l) filters.uniform_filter(norm_r * norm_r, wid, s_r) dmaps[:, :, disp] = s / numpy.sqrt(s_l * s_r) return numpy.argmax(dmaps, axis=2)
def getStats(map, w_thresh = .3, rem_weight = False): # rms is calculated on a map smoothed with a 1-arcmin box car # only take points where weight > threshold # remove the weight first # This is for pure c maps, not loaded into a map object # if rem_weight: # not_zero = np.nonzero(map.Map.weight_map) # map.Map.real_map_T = (map.Map.real_map_T[not_zero] / # map.Map.weight_map[not_zero]) # smooth_w = filters.uniform_filter(map.Map.weight_map, size = 4) # smooth_T = filters.uniform_filter(map.Map.real_map_T, size = 4) # if len(np.shape(map.Map.weight_map)) > 2: # # for polarized maps # good = np.where(map.Map.weight_map[:,:, 0, 0] > w_thresh) # else: # good = np.where(map.Map.weight_map > w_thresh) # med_w = np.median(map.Map.weight_map[good]) # tot_w = np.sum(map.Map.weight_map[good]) # rms = np.sqrt(np.sum(smooth_T[good]**2)) # This is for sptpol-style map objects if map.weighted_map: map.removeWeight() smooth_w = filters.uniform_filter(map.weight, size = 4) smooth_T = filters.uniform_filter(map.map, size = 4) good = np.where(map.weight > w_thresh) med_w = np.median(map.weight[good]) tot_w = np.sum(map.weight[good]) rms = np.sqrt(np.sum(smooth_T[good]**2)) return {map.from_filename: {'rms': rms, 'med_w': med_w, 'tot_w': tot_w}}
def _get_sums(GT, P, fltr, valid=None, norm=False, **kwargs): if fltr == Filter.UNIFORM: GT_sum = uniform_filter(GT, size=kwargs['ws']) P_sum = uniform_filter(P, size=kwargs['ws']) elif fltr == Filter.GAUSSIAN: GT_sum = gaussian_filter(GT, sigma=kwargs['s'], truncate=kwargs['t']) P_sum = gaussian_filter(P, sigma=kwargs['s'], truncate=kwargs['t']) if norm: N = kwargs['n'] x, y = np.mgrid[-N // 2 + 1:N // 2 + 1, -N // 2 + 1:N // 2 + 1] g = np.exp(-((x**2 + y**2) / (2.0 * kwargs['s']**2))) den = g.sum() if den != 0: GT_sum /= den P_sum /= den if valid is not None: GT_sum = GT_sum[valid:-valid, valid:-valid] P_sum = P_sum[valid:-valid, valid:-valid] GT_sum_sq = GT_sum * GT_sum P_sum_sq = P_sum * P_sum GT_P_sum_mul = GT_sum * P_sum return GT_sum_sq, P_sum_sq, GT_P_sum_mul
def _uqi_single(GT, P, ws): N = ws**2 window = np.ones((ws, ws)) GT_sq = GT * GT P_sq = P * P GT_P = GT * P GT_sum = uniform_filter(GT, ws) P_sum = uniform_filter(P, ws) GT_sq_sum = uniform_filter(GT_sq, ws) P_sq_sum = uniform_filter(P_sq, ws) GT_P_sum = uniform_filter(GT_P, ws) GT_P_sum_mul = GT_sum * P_sum GT_P_sum_sq_sum_mul = GT_sum * GT_sum + P_sum * P_sum numerator = 4 * (N * GT_P_sum - GT_P_sum_mul) * GT_P_sum_mul denominator1 = N * (GT_sq_sum + P_sq_sum) - GT_P_sum_sq_sum_mul denominator = denominator1 * GT_P_sum_sq_sum_mul q_map = np.ones(denominator.shape) index = np.logical_and((denominator1 == 0), (GT_P_sum_sq_sum_mul != 0)) q_map[index] = 2 * GT_P_sum_mul[index] / GT_P_sum_sq_sum_mul[index] index = (denominator != 0) q_map[index] = numerator[index] / denominator[index] s = int(np.round(ws / 2)) return np.mean(q_map[s:-s, s:-s])
def image_std(image, radius): """ Calculates the standard deviation of an image, using a moving window of specified radius. Arguments: ----------- image: np.array 2D array containing the pixel intensities of a single-band image radius: int radius defining the moving window used to calculate the standard deviation. For example, radius = 1 will produce a 3x3 moving window. Returns: ----------- win_std: np.array 2D array containing the standard deviation of the image """ # convert to float image = image.astype(float) # first pad the image image_padded = np.pad(image, radius, 'reflect') # window size win_rows, win_cols = radius * 2 + 1, radius * 2 + 1 # calculate std win_mean = uniform_filter(image_padded, (win_rows, win_cols)) win_sqr_mean = uniform_filter(image_padded**2, (win_rows, win_cols)) win_var = win_sqr_mean - win_mean**2 win_std = np.sqrt(win_var) # remove padding win_std = win_std[radius:-radius, radius:-radius] return win_std
def smooth_my_data(mydata, grid_space, edge_value): """ Smooth data using scipy's uniform_filter Args: mydata (ndarray): Data to be smoothed grid_space (int) : Smoothing factor (nb of grid points) edge_value (float) : Value to put a field edges Returns: numpy.ndarray : Smoothed data array """ print("+ Smooth Data") size_grid = grid_space * 2 + 1 # account for struct size in uniform_filter # WARNING: rpnpy get its fields from librmn fst functions # these fields are most of the times Fortran real*4 array # (dtype=np.float32) # while the default numpy array is C double # (dtype=np.float64) mydata_smooth = np.zeros(mydata.shape, dtype=mydata.dtype, order='FORTRAN') spyfilt.uniform_filter(mydata, output=mydata_smooth, size=size_grid, mode='constant') mydata[:, :] = edge_value (ni, nj) = mydata.shape mydata[grid_space:ni-grid_space, grid_space:nj-grid_space] = \ mydata_smooth[grid_space:ni-grid_space, grid_space:nj-grid_space] del mydata_smooth return mydata
def lee_filter2(img, window=(3, 3)): """ Apply a Lee filter to a numpy array. Does not modify original. Code is based on: https://stackoverflow.com/questions/39785970/speckle-lee-filter-in-python PCI implementation is found at http://www.pcigeomatics.com/geomatica-help/references/pciFunction_r/python/P_fle.html *Parameters* img : numpy array Array to which filter is applied window : int Size of filter *Returns* array filtered array """ img_mean = uniform_filter(img, window) img_sqr = np.square(img) img_sqr_mean = uniform_filter(img_sqr, window) img_variance = img_sqr_mean - img_mean**2 overall_variance = variance(img) img_weights = img_variance / (img_variance + overall_variance) img_output = img_mean + img_weights * (img - img_mean) return img_output
def moving_window_sd(data, window, return_mean=False, return_variance=False): """ This is Ben's implementation Calculate a moving window standard deviation (and mean) """ t1 = data.copy() t2 = np.square(t1) uniform_filter(t1, window, output=t1) uniform_filter(t2, window, output=t2) if return_mean: m = t1.copy() np.square(t1, out=t1) np.subtract(t2, t1, out=t2) t2[t2 < 0] = 0 del t1 if not return_variance: np.sqrt(t2, out=t2) if return_mean: return t2, m else: return t2
def compute_colseps_conv(binary, scale=1.0, args=None): """Find column separators by convoluation and thresholding.""" h, w = binary.shape # find vertical whitespace by thresholding smoothed = filters.gaussian_filter(1.0 * binary, (scale, scale * 0.5)) smoothed = filters.uniform_filter(smoothed, (5.0 * scale, 1)) thresh = (smoothed < amax(smoothed) * 0.1) DSAVE("1thresh", thresh, args=args) # find column edges by filtering grad = filters.gaussian_filter(1.0 * binary, (scale, scale * 0.5), order=(0, 1)) grad = filters.uniform_filter(grad, (10.0 * scale, 1)) # grad = abs(grad) # use this for finding both edges grad = (grad > 0.5 * amax(grad)) DSAVE("2grad", grad, args=args) # combine edges and whitespace seps = minimum(thresh, filters.maximum_filter(grad, (int(scale), int(5 * scale)))) seps = filters.maximum_filter(seps, (int(2 * scale), 1)) DSAVE("3seps", seps, args=args) # select only the biggest column separators seps = select_regions(seps, dim0, min=args.csminheight * scale, nbest=args.maxcolseps) DSAVE("4seps", seps, args=args) return seps
def varfilt(a, size): a = np.float32(a) sum = uniform_filter(a, (size, size, 1)) mean = sum expdev = (a - mean)**2 sum = uniform_filter(expdev, (size, size, 1)) return sum
def neuropil_subtraction(mov, lx): """ subtract low-pass filtered version of binned movie low-pass filtered version ~ neuropil subtract to help ignore neuropil Parameters ---------------- mov : 3D array binned movie, size [nbins x Ly x Lx] lx : int size of filter Returns ---------------- mov : 3D array binned movie with "neuropil" subtracted, size [nbins x Ly x Lx] """ if len(mov.shape) < 3: mov = mov[np.newaxis, :, :] nbinned, Ly, Lx = mov.shape c1 = uniform_filter(np.ones((Ly, Lx)), size=[lx, lx], mode='constant') for j in range(nbinned): mov[j] -= uniform_filter(mov[j], size=[lx, lx], mode='constant') / c1 return mov
def std2d(X, window_size): """ Get 2D standard deviation of 2D array efficiently. Examples --------- >>> std2d = kkpy.util.std2d(arr2d, 3) Parameters ---------- X : 2D Array Array containing the data. window_size : float or 1D array Window size. If array of two elements, window sizes of x and y will be window_size[0] and window_size[1], respectively. Returns --------- std2d : 2D Array Return 2D standard deviation. Notes --------- This code is from https://nickc1.github.io/python,/matlab/2016/05/17/Standard-Deviation-(Filters)-in-Matlab-and-Python.html, written by Nick Cortale. Modified by Kwonil Kim in November 2020: add docstring, modify function name """ from scipy.ndimage.filters import uniform_filter r, c = X.shape X += np.random.rand(r, c) * 1e-6 c1 = uniform_filter(X, window_size, mode='reflect') c2 = uniform_filter(X * X, window_size, mode='reflect') return np.sqrt(c2 - c1 * c1)
def compute_colseps_conv(binary, scale=1.0, minheight_whiteseps=10, max_whiteseps=3): """Find column separators by convolution and thresholding. """ h, w = binary.shape # find vertical whitespace by thresholding smoothed = gaussian_filter(1.0 * binary, (scale, scale * 0.5)) smoothed = uniform_filter(smoothed, (5.0 * scale, 1)) thresh = (smoothed < np.amax(smoothed) * 0.1) # find column edges by filtering grad = gaussian_filter(1.0 * binary, (scale, scale * 0.5), order=(0, 1)) grad = uniform_filter(grad, (10.0 * scale, 1)) # grad = abs(grad) # use this for finding both edges grad = (grad > 0.5 * np.amax(grad)) # combine edges and whitespace seps = np.minimum(thresh, maximum_filter(grad, (int(scale), int(5 * scale)))) seps = maximum_filter(seps, (int(2 * scale), 1)) # select only the biggest column separators seps = morph.select_regions(seps, sl.dim0, min=minheight_whiteseps * scale, nbest=max_whiteseps) return seps
def compute_colseps_conv(binary, scale=1.0, minheight=10, maxcolseps=2): """Find column separators by convolution and thresholding. Args: binary (numpy.array): scale (float): minheight (int): maxcolseps (int): Returns: Separators """ h, w = binary.shape # find vertical whitespace by thresholding smoothed = gaussian_filter(1.0*binary, (scale, scale*0.5)) smoothed = uniform_filter(smoothed, (5.0*scale, 1)) thresh = (smoothed < np.amax(smoothed)*0.1) # find column edges by filtering grad = gaussian_filter(1.0*binary, (scale, scale*0.5), order=(0, 1)) grad = uniform_filter(grad, (10.0*scale, 1)) grad = (grad > 0.5*np.amax(grad)) # combine edges and whitespace seps = np.minimum(thresh, maximum_filter(grad, (int(scale), int(5*scale)))) seps = maximum_filter(seps, (int(2*scale), 1)) # select only the biggest column separators seps = morph.select_regions(seps, sl.dim0, min=minheight*scale, nbest=maxcolseps+1) return seps
def plane_sweep_ncc(im_l,im_r,start,steps,wid): "正規化相互機関を用いて視差画像を求める""" m,n=im_l.shape #差の和を格納する配列 mean_l = np.zeros((m,n)) mean_r = np.zeros((m,n)) s = np.zeros((m,n)) s_l = np.zeros((m,n)) s_r = np.zeros((m,n)) #奥行き平面を格納する配列 dmaps = np.zeros((m,n,steps)) #パッチの平均を計算する filters.uniform_filter(im_l,wid,mean_l) filters.uniform_filter(im_r,wid,mean_r) #画像を正規化する norm_l = im_l - mean_l norm_r = im_r - mean_r #視差を順番に試していく for displ in range(steps): #左の画像を右にずらして和を計算する filters.uniform_filter(np.roll(norm_l,-displ-start)* norm_r,wid,s) #分子の和 filters.uniform_filter(np.roll(norm_l,-displ-start)* np.roll(norm_l,-displ-start),wid,s_l) filters.uniform_filter(norm_r*norm_r,wid,s_r) #分母の和 #相互相関の値を保存する dmaps[:,:,displ] = s/np.sqrt(s_l*s_r) #各ピクセルで最良の奥行きを選ぶ return np.argmax(dmaps,axis=2)
def window_stdev(arr, radius, epsilon=1e-7): c1 = uniform_filter(arr, radius * 2 + 1, mode='constant', origin=-radius) c2 = uniform_filter(arr * arr, radius * 2 + 1, mode='constant', origin=-radius) return ((c2 - c1 * c1)**.5) + epsilon
def get_limp_doppler_img(cplx_img, filter_size, limp_ratio=2): aline_num = cplx_img.shape[1] oct_img = abs(cplx_img) limp_filter = zeros(aline_num) limp_filter[0:aline_num/2+1] = linspace(0, 1, aline_num/2+1) limp_img_pos = abs(fft.ifft(fft.fft(cplx_img, axis=1) \ * limp_filter, axis=1)) limp_filter = flipud(limp_filter) limp_img_neg = abs(fft.ifft(fft.fft(cplx_img, axis=1) \ * limp_filter, axis=1)) if filter_size > 1: from scipy.ndimage.filters import uniform_filter doppler_img_pos = uniform_filter(limp_img_pos) \ / uniform_filter(oct_img) doppler_img_neg = uniform_filter(limp_img_neg) \ / uniform_filter(oct_img) else: doppler_img_pos = limp_img_pos / oct_img doppler_img_neg = limp_img_neg / oct_img ## set pos/neg ratio threshold mask_pos = doppler_img_pos > doppler_img_neg \ * (limp_ratio - doppler_img_neg*(limp_ratio - 1)) mask_neg = doppler_img_neg > doppler_img_pos \ * (limp_ratio - doppler_img_pos*(limp_ratio - 1)) doppler_img = doppler_img_pos * mask_pos - doppler_img_neg * mask_neg doppler_img *= pi * ((sqrt(2) - 1) * abs(doppler_img) + 1) doppler_img[doppler_img > pi] = pi doppler_img[doppler_img < -pi] = -pi return doppler_img
def smooth_boxcar(self, filtwidth, verbose=True): """ Does a boxcar smooth of the spectrum. The default is to do inverse variance weighting, using the variance spectrum if it exists. The other default is not to write out an output file. This can be changed by setting the outfile parameter. """ """ Set the weighting """ if self.var is not None: if verbose: print('Weighting by the inverse variance') wht = 1.0 / self.var else: if verbose: print('Uniform weighting') wht = 0.0 * self.y + 1.0 """ Smooth the spectrum and variance spectrum """ yin = wht * self.y smowht = filters.uniform_filter(wht, filtwidth) ysmooth = filters.uniform_filter(yin, filtwidth) ysmooth /= smowht if self.var is not None: varsmooth = 1.0 / (filtwidth * smowht) else: varsmooth = None return ysmooth, varsmooth
def lee_filter(img, size, mode='reflect'): """ lee滤波算法 Reference: Lee, J. S.: Speckle suppression and analysis for SAR images, Opt. Eng., 25, 636–643, 1986. @param img: 输入的影像 numpy数组 @param size: 滤波窗口大小 @param mode: 滤波边缘处理方式 详见:https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.ndimage.uniform_filter.html @return 返回滤波后的影像 """ img_mean = uniform_filter(img, (size, size), mode=mode) img_sqr_mean = uniform_filter(img ** 2, (size, size)) img_variance = img_sqr_mean - img_mean ** 2 overall_variance = variance(img) np.seterr(divide='ignore', invalid='ignore') img_weights = img_variance ** 2 / \ (img_variance ** 2 + overall_variance ** 2) img_output = img_mean + img_weights * (img - img_mean) return img_output.astype(np.int)
def plane_sweep_ncc(im_l, im_r, start, steps, wid): '''Find disparity image using normalized cross-correlation.''' m, n = im_l.shape # Must match im_r.shape. mean_l = numpy.zeros(im_l.shape) mean_r = numpy.zeros(im_l.shape) s = numpy.zeros(im_l.shape) s_l = numpy.zeros(im_l.shape) s_r = numpy.zeros(im_l.shape) dmaps = numpy.zeros((m, n, steps)) filters.uniform_filter(im_l, wid, mean_l) filters.uniform_filter(im_r, wid, mean_r) norm_l = im_l - mean_l norm_r = im_r - mean_r for disp in range(steps): filters.uniform_filter(numpy.roll(norm_l, -disp - start) * norm_r, wid, s) filters.uniform_filter(numpy.roll(norm_l, -disp - start) * numpy.roll(norm_l, -disp - start), wid, s_l) filters.uniform_filter(norm_r * norm_r, wid, s_r) dmaps[:, :, disp] = s / numpy.sqrt(s_l * s_r) return numpy.argmax(dmaps, axis=2)
def window_stdev(arr, radius): ''' standard deviation on sliding windows Code extract from http://stackoverflow.com/questions/18419871/improving-code-efficiency-standard-deviation-on-sliding-windows ''' c1 = uniform_filter(arr, radius * 2, mode='constant', origin=-radius) c2 = uniform_filter(arr * arr, radius * 2, mode='constant', origin=-radius) std = ((c2 - c1 * c1)**.5)[:-radius * 2 + 1, :-radius * 2 + 1] # adjust result to get it on the same grid as input arr grid_x, grid_y = np.meshgrid(range(np.shape(arr)[1]), range(np.shape(arr)[0])) egrid_x, egrid_y = np.meshgrid( np.linspace(0.5 + radius / 2, np.shape(arr)[1] + 0.5 - radius - 1, np.shape(arr)[1] - radius - 1), np.linspace(0.5 + radius / 2, np.shape(arr)[0] + 0.5 - radius - 1, np.shape(arr)[0] - radius - 1)) epoints = np.array( [np.ndarray.flatten(egrid_x), np.ndarray.flatten(egrid_y)]).transpose() evalues = np.ndarray.flatten(std) return griddata(epoints, evalues, (grid_x, grid_y), method='cubic')
def window_stdev(img, window, img_mean=None, img_sqr_mean=None): """ Calculate standard deviation filter for an image *Parameters* img : numpy array Array to which filter is applied window : int Size of filter img_mean : array, optional Mean of image calculated using an equally sized window. If not provided, it is computed. img_sqr_mean : array, optional Mean of square of image calculated using an equally sized window. If not provided, it is computed. The function is based on code from: http://nickc1.github.io/python,/matlab/2016/05/17/Standard-Deviation-(Filters)-in-Matlab-and-Python.html """ if img_mean is None: img_mean = uniform_filter(img, window) if img_sqr_mean is None: img_sqr_mean = uniform_filter(img**2, window) std = np.sqrt(img_sqr_mean - img_mean**2) return (std)
def lee_filter(x, size): img_mean = uniform_filter(x, (size, size)) img_sq_mean = uniform_filter(x**2, (size, size)) img_var = img_sq_mean - img_mean**2 overall_var = variance(x) img_weights = img_var / (img_var + overall_var) return img_mean + img_weights * (x - img_mean)
def lee_filter(img, size): img_mean = uniform_filter(img, (size, size)) img_sqr_mean = uniform_filter(img**2, (size, size)) img_variance = img_sqr_mean - img_mean**2 overall_variance = variance(img) img_weights = img_variance / (img_variance + overall_variance) img_output = img_mean + img_weights * (img - img_mean) return img_output
def lee_filter(band, window, var_noise=0.25): mean_window = uniform_filter(band, window) mean_sqr_window = uniform_filter(band**2, window) var_window = mean_sqr_window - mean_window**2 weights = var_window / (var_window + var_noise) band_filtered = mean_window + weights * (band - mean_window) return band_filtered
def filter_complex_image(image, size, mode='constant'): """Boxcar average of complex image. Created by splitting into real and imaginary components, boxcaring, and recombining. Assumes complex number are of the form (r + i)""" real = np.real(image) imag = np.imag(image) out = uniform_filter( real, size, mode=mode) + 1j * uniform_filter(imag, size, mode=mode) return out
def window_stdev(self, arr, radius): diameter = int(round(radius * 2)) radius = int(round(radius)) c1 = uniform_filter(arr, diameter, mode='constant', origin=-radius) c2 = uniform_filter(arr * arr, diameter, mode='constant', origin=-radius) c_std = ((c2 - c1 * c1) ** .5)[:-diameter + 1, :-diameter + 1] # symmetric padding to match Matlab stdfilt: return np.pad(c_std, radius, 'symmetric')
def neuropil_subtraction(mov,lx): if len(mov.shape)<3: mov = mov[np.newaxis, :, :] nframes, Ly, Lx = mov.shape c1 = uniform_filter(np.ones((Ly,Lx)), size=[lx, lx], mode = 'constant') for j in range(nframes): mov[j] -= uniform_filter(mov[j], size=[lx, lx], mode = 'constant') / c1 return mov
def get_kasai_doppler_img(cplx_img, filter_size): doppler_img = cplx_img[:, 1:] * conjugate(cplx_img[:, 0:-1]) if filter_size > 1 : from scipy.ndimage.filters import uniform_filter doppler_img = uniform_filter(doppler_img.real, filter_size) + \ 1j * uniform_filter(doppler_img.imag, filter_size) doppler_img = angle(doppler_img) return doppler_img
def lee_filter(self, img): img_mean = uniform_filter(img, (self.intensity, self.intensity)) img_sqr_mean = uniform_filter(img**2, (self.intensity, self.intensity)) img_variance = img_sqr_mean - img_mean**2 overall_variance = variance(img) img_weights = img_variance / (img_variance + overall_variance) img_output = img_mean + img_weights * (img - img_mean) return img_output
def neuropil_subtraction(mov: np.ndarray, filter_size: int) -> None: """Returns movie subtracted by a low-pass filtered version of itself to help ignore neuropil.""" nbinned, Ly, Lx = mov.shape c1 = uniform_filter(np.ones((Ly, Lx)), size=filter_size, mode='constant') movt = np.zeros_like(mov) for frame, framet in zip(mov, movt): framet[:] = frame - (uniform_filter(frame, size=filter_size, mode='constant') / c1) return movt
def get_stddev(data, size): """ Old: do not use because it does not work out at boundaries and masked values! """ mean_squared = np.square(uniform_filter(data, size=size, mode='reflect')) squared_mean = uniform_filter(np.square(data), size=size, mode='reflect') std = np.sqrt(squared_mean - mean_squared) return std
def window_stdev(arr, radius): c1 = uniform_filter(arr, radius*2, mode='constant', #origin=-radius ) c2 = uniform_filter(arr*arr, radius*2, mode='constant', #origin=-radius ) r = ((c2 - c1*c1)**.5) #[:-radius*2+1] return r
def smooth(array, box, phase=False): """ Imitates IDL's smooth function. Can also (correctly) smooth interferometric phases with the phase=True keyword. """ if np.iscomplexobj(array): return filters.uniform_filter(array.real, box) + 1j * filters.uniform_filter(array.imag, box) elif phase is True: return np.angle(smooth(np.exp(1j * array), box)) else: return filters.uniform_filter(array.real, box)
def get_intensity_variance_omag(amplitude_img, filter_size, intensity_thresh): cc_img = 2*amplitude_img[:, 0:-1] * amplitude_img[:, 1:] from scipy.ndimage.filters import uniform_filter cc_img = uniform_filter(cc_img, filter_size) amplitude_img = amplitude_img**2 ac_img = amplitude_img[:, 0:-1] + amplitude_img[:, 1:] ac_img = uniform_filter(ac_img, filter_size) omag_img = 1-cc_img/ac_img omag_img *= (ac_img > intensity_thresh**2) return omag_img
def get_cplx_diff_omag(cplx_img, filter_size, intensity_thresh): diff_img = abs(diff(cplx_img, axis=1)) mean_img = abs(cplx_img[:, 1:] + cplx_img[:, 0:-1])/2 from scipy.ndimage.filters import uniform_filter diff_img = uniform_filter(diff_img, filter_size) mean_img = uniform_filter(mean_img, filter_size) omag_img = diff_img / mean_img omag_img *= (mean_img > intensity_thresh) return omag_img
def get_phase_variance_omag(cplx_img, filter_size, intensity_thresh): conj_img = cplx_img[:, 1:] * cplx_img[:, 0:-1] from scipy.ndimage.filters import uniform_filter conj_img = uniform_filter(conj_img.real, filter_size) + \ 1j * uniform_filter(conj_img.imag, filter_size) cc_img = abs(conj_img) * 2 amplitude_img = abs(cplx_img)**2 ac_img = amplitude_img[:, 0:-1] + amplitude_img[:, 1:] ac_img = uniform_filter(ac_img, filter_size) omag_img = 1-cc_img/ac_img omag_img *= (ac_img > intensity_thresh**2) return omag_img
def filter(self, array, *args, **kwargs): meta = kwargs['meta'] pol = meta['CH_pol'] idx_hh = pol.index('HH') idx_vv = pol.index('VV') idx_xx = pol.index('XX') Srr = (array[idx_hh, ...] - array[idx_vv, ...] + 1j * 2.0 * array[idx_xx, ...]) / 2.0 Sll = (array[idx_vv, ...] - array[idx_hh, ...] + 1j * 2.0 * array[idx_xx, ...]) / 2.0 a1 = Srr * np.conj(Sll) a1 = filters.uniform_filter(a1.real, self.win) + 1j * filters.uniform_filter(a1.imag, self.win) return np.angle(a1) / 4
def filter(self, array, *args, **kwargs): win = self.win if array.ndim == 3: win = [1] + self.win if array.ndim == 4: win = [1, 1] + self.win array[np.isnan(array)] = 0.0 if np.iscomplexobj(array): return filters.uniform_filter(array.real, win) + 1j * filters.uniform_filter(array.imag, win) else: tmp = np.exp(1j * array) tmp = filters.uniform_filter(tmp.real, win) + 1j * filters.uniform_filter(tmp.imag, win) return np.angle(tmp)
def showDef2(cost): from scipy.ndimage.filters import uniform_filter #vmin=cost.min() #vmax=cost.max() pl=pylab vy=(cost[0]) vx=(cost[1]) hy=(cost[2]) hx=(cost[3]) vyn=uniform_filter(vy,[2,1],mode="constant") vxn=uniform_filter(vx,[2,1],mode="constant") hyn=uniform_filter(hy,[1,2],mode="constant") hxn=uniform_filter(hx,[1,2],mode="constant") qvy=(cost[4]) qvx=(cost[5]) qhy=(cost[6]) qhx=(cost[7]) qvyn=uniform_filter(qvy,[2,1],mode="constant") qvxn=uniform_filter(qvx,[2,1],mode="constant") qhyn=uniform_filter(qhy,[1,2],mode="constant") qhxn=uniform_filter(qhx,[1,2],mode="constant") vmin=(vyn+hyn+vxn+hxn+qvyn+qhyn+qvxn+qhxn).min() vmax=(vyn+hyn+vxn+hxn+qvyn+qhyn+qvxn+qhxn).max() pl.imshow(vyn+hyn+vxn+hxn,interpolation="nearest")#,vmin=vmin,vmax=vmax) pl.xlabel("Def (min %.5f,max %.5f)"%(vmin,vmax)) return vyn+hyn+vxn+hxn+qvyn+qhyn+qvxn+qhxn
def smoothen(loglines, down_sample, key=None, num_samples=100, **kwargs): num_samples /= down_sample if key is not None: values = uniform_filter([getattr(x, key) for x in loglines], num_samples) for idx, v in itertools.izip(xrange(len(loglines)), values): try: loglines[idx] = loglines[idx]._replace(**{key : v}) except: l = loglines[idx] setattr(l, key, v) return loglines else: values = uniform_filter(loglines, num_samples) return values
def plane_sweep_ssd(im_l, im_r, start, steps, wid): '''Find disparity image using sum of squared differences.''' m, n = im_l.shape # Must match im_r.shape. s = numpy.zeros(im_l.shape) dmaps = numpy.zeros((m, n, steps)) for disp in range(steps): filters.uniform_filter((numpy.roll(im_l, -disp - start) - im_r) ** 2, wid, s) dmaps[:, :, disp] = s return numpy.argmin(dmaps, axis=2)
def normals_numpy(depth, rect=((0,0),(640,480)), win=7, mat=None): assert depth.dtype == np.float32 from scipy.ndimage.filters import uniform_filter (l,t),(r,b) = rect v,u = np.mgrid[t:b,l:r] depth = depth[v,u] depth[depth==0] = -1e8 # 2047 depth = calibkinect.recip_depth_openni(depth) depth = uniform_filter(depth, win) global duniform duniform = depth dx = (np.roll(depth,-1,1) - np.roll(depth,1,1))/2 dy = (np.roll(depth,-1,0) - np.roll(depth,1,0))/2 #dx,dy = np.array(depth),np.array(depth) #speedup.gradient(depth.ctypes.data, dx.ctypes.data, # dy.ctypes.data, depth.shape[0], depth.shape[1]) X,Y,Z,W = -dx, -dy, 0*dy+1, -(-dx*u + -dy*v + depth).astype(np.float32) mat = calibkinect.projection().astype('f').transpose() mat = np.ascontiguousarray(mat) x = X*mat[0,0] + Y*mat[0,1] + Z*mat[0,2] + W*mat[0,3] y = X*mat[1,0] + Y*mat[1,1] + Z*mat[1,2] + W*mat[1,3] z = X*mat[2,0] + Y*mat[2,1] + Z*mat[2,2] + W*mat[2,3] w = np.sqrt(x*x + y*y + z*z) w[z<0] *= -1 weights = z*0+1 weights[depth<-1000] = 0 weights[(z/w)<.1] = 0 #return x/w, y/w, z/w return np.dstack((x/w,y/w,z/w)), weights
def smooth_cfa(cfa,footprint=8,stereo=False): """ Smooth a RAW (bayer-patterned) image with a uniform filter. Parameters ---------- cfa : ndarray bayer-patterned image footprint : int size of uniform filter kernel (must be multiple of 2) stereo : boolean whether image is a side-by-side stereo image, in which case smoothing will be performed independently on each side Returns ------- smoothed image : ndarray """ (h,w) = cfa.shape if footprint > 0: smoothed = np.zeros_like(cfa) if stereo: xs,fw = [0,w/2], w/2 else: xs,fw = [0], w for x in xs: for dy in [0,1]: for dx in [0,1]: smoothed[dy::2,x+dx:x+dx+fw:2] = uniform_filter(cfa[dy::2,x+dx:x+dx+fw:2],size=footprint/2,mode='nearest') return smoothed else: return cfa
def compute_gradmaps(binary, scale, gauss=False): """ Use gradient filtering to find baselines Args: binary (numpy.array): scale (float): gauss (bool): Use gaussian instead of uniform filtering Returns: (bottom, top, boxmap) """ # use gradient filtering to find baselines logger.debug('Computing gradient maps') boxmap = compute_boxmap(binary, scale) cleaned = boxmap*binary if gauss: grad = gaussian_filter(1.0*cleaned, (0.3*scale, 6*scale), order=(1, 0)) else: grad = gaussian_filter(1.0*cleaned, (max(4, 0.3*scale), scale), order=(1, 0)) grad = uniform_filter(grad, (1, 6*scale)) bottom = norm_max((grad < 0)*(-grad)) top = norm_max((grad > 0)*grad) return bottom, top, boxmap
def smooth_color(image,footprint=8,stereo=False): """ Smooth a multi-channel image with a uniform filter. Applies same filter to all channels. Parameters ---------- image : ndarray color image footprint : int size of uniform filter kernel stereo : boolean whether image is a side-by-side stereo image, in which case smoothing will be performed independently on each side Returns ------- smoothed image : ndarray """ (h,w,nc) = image.shape if footprint > 0: smoothed = np.zeros_like(image) if stereo: xs,fw = [0,w/2], w/2 else: xs,fw = [0], w for x in xs: for c in range(nc): smoothed[:,x:fw,c] = uniform_filter(image[:,x:fw,c],size=footprint,mode='nearest') return smoothed else: return image
def magiceye_solver(x): """ Solves the autostereogram image represented by the ndarray, x """ shape = x.shape if len(shape) >= 3: m, n, c = shape color_image = True else: m, n, c = shape[0], shape[1], 1 color_image = False solution = np.zeros((m, c * n), dtype=float) for i in range(c): if color_image: color = x[:, :, i] else: color = x if color.std() == 0.0: continue shifted = shift_pic(color) filt_1 = filters.prewitt(shifted) filt_2 = filters.uniform_filter(filt_1, size=(5, 5)) if ski_filter: filt_2 = post_process(filt_2) m, n = filt_2.shape solution[:m, i * n:i * n + n] = filt_2 return solution[:, :c * n]
def filter(self, array, *args, **kwargs): array = np.exp(1j * array) win = (7, 7) coh = filters.uniform_filter( np.abs(filters.uniform_filter(array.real, win) + 1j * filters.uniform_filter(array.imag, win)), win) bp = Blocxy(array, (self.bs, self.bs), (self.bs // 2, self.bs // 2)) bc = Blocxy(coh, (self.bs, self.bs), (self.bs // 2, self.bs // 2)) for block, cblock in zip(bp.getiterblocks(), bc.getiterblocks()): block = np.fft.fft2(block) block *= abs(block) ** (1.0 - np.mean(cblock[self.bs // 4:self.bs // 4 * 3, self.bs // 4:self.bs // 4 * 3])) block = np.fft.ifft2(block) bp.setiterblocks(block) output = bp.getresult() output = np.angle(output) return output
def bandpass(image, lshort, llong, threshold=None): """Convolve with a Gaussian to remove short-wavelength noise, and subtract out long-wavelength variations, retaining features of intermediate scale. Parmeters --------- image : ndarray lshort : small-scale cutoff (noise) llong : large-scale cutoff threshold : float or integer By default, 1 for integer images and 1/256. for float images. Returns ------- ndarray, the bandpassed image """ if threshold is None: if np.issubdtype(image.dtype, np.integer): threshold = 1 else: threshold = 1/256. if not 2*lshort < llong: raise ValueError("The smoothing length scale must be more" + "than twice the noise length scale.") settings = dict(mode='nearest', cval=0) boxcar = uniform_filter(image, 2*llong+1, **settings) gaussian = ifftn(fourier_gaussian(fftn(image), lshort)) result = gaussian - boxcar return np.where(result > threshold, result.real, 0)
def likelihood_velocity(positions, velocities, img_now, img_before): ratio_now = uniform_filter(img_now.astype(np.float), size=5) ratio_before = uniform_filter(img_before.astype(np.float), size=5) weights = np.zeros(len(positions)) for i in xrange(len(positions)): try: if np.min(positions[i] >= 0) and np.min(positions[i] - velocities[i]) >= 0: weights[i] = ratio_now[positions[i, 0], positions[i, 1]] * ratio_before[positions[i, 0] - velocities[i, 0], positions[i, 1] - velocities[i, 1]] except IndexError: pass if np.sum(weights) == 0: weights = np.ones_like(weights) / len(positions) else: weights = weights / np.sum(weights) return weights
def getlist(tempa): # datamax = filters.uniform_filter(tempa[Threadid+1].data, vecinos) vecinos = 10 datamax = filters.uniform_filter(tempa, vecinos) difftop = datamax > 55000 diff = difftop # diffbot = datamax < 5000 # diff = difftop | diffbot mask = np.where(diff, 0, 1) return mask.min()
def calc(self,pv,indxob): pvspec = rfft2(pv) psispec = self.model.invert(pvspec=pvspec) pvavspec = (psispec[1]-psispec[0])/self.model.H pvav = irfft2(pvavspec) if self.filter_width > 0: if self.use_gaussian_filter: pvav = gaussian_filter(pvav, self.filter_width, mode='wrap') else: pvav = uniform_filter(pvav, size=self.filter_width, mode='wrap') return self.scalefact*pvav.ravel()[indxob]
def showDefNodes(cost): from scipy.ndimage.filters import uniform_filter #vmin=cost.min() #vmax=cost.max() pl=pylab if cost[0].shape[0]>cost[0].shape[1]: ny=3;nx=2 pl.figure(figsize=(5,10)) else: ny=2;nx=3 pl.figure(figsize=(10,5)) #pl.figure(figsize=(4,12)) vy=(cost[0]) vx=(cost[1]) hy=(cost[2]) hx=(cost[3]) vyn=uniform_filter(vy,[2,1],mode="constant") vxn=uniform_filter(vx,[2,1],mode="constant") hyn=uniform_filter(hy,[1,2],mode="constant") hxn=uniform_filter(hx,[1,2],mode="constant") vmin=(vyn+hyn+vxn+hxn).min()/2.0 vmax=(vyn+hyn+vxn+hxn).max()/2.0 pl.subplot(ny,nx,1) pl.imshow(vyn+hyn,interpolation="nearest")#,vmin=vmin,vmax=vmax) pl.xlabel("lin Y (%.5f,%.5f)"%((vyn+hyn).min(),(vyn+hyn).max())) pl.subplot(ny,nx,2) pl.imshow(vxn+hxn,interpolation="nearest")#,vmin=vmin,vmax=vmax) pl.xlabel("lin X (%.5f,%.5f)"%((vxn+hxn).min(),(vxn+hxn).max())) pl.subplot(ny,nx,3) pl.imshow(vyn+hyn+vxn+hxn,interpolation="nearest")#,vmin=vmin*2,vmax=vmax*2) pl.xlabel("lin All (%.5f,%.5f)"%((vxn+hxn+vyn+hyn).min(),(vxn+hxn+vyn+hyn).max())) vy=(cost[4]) vx=(cost[5]) hy=(cost[6]) hx=(cost[7]) vyn=uniform_filter(vy,[2,1],mode="constant") vxn=uniform_filter(vx,[2,1],mode="constant") hyn=uniform_filter(hy,[1,2],mode="constant") hxn=uniform_filter(hx,[1,2],mode="constant") vmin=(vyn+hyn+vxn+hxn).min() vmax=(vyn+hyn+vxn+hxn).max() pl.subplot(ny,nx,4) pl.imshow(vyn+hyn,interpolation="nearest")#,vmin=vmin,vmax=vmax) pl.xlabel("quad Y (%.5f,%.5f)"%((vyn+hyn).min(),(vyn+hyn).max())) pl.subplot(ny,nx,5) pl.imshow(vxn+hxn,interpolation="nearest")#,vmin=vmin,vmax=vmax) pl.xlabel("quad X (%.5f,%.5f)"%((vxn+hxn).min(),(vxn+hxn).max())) pl.subplot(ny,nx,6) pl.imshow(vyn+hyn+vxn+hxn,interpolation="nearest")#,vmin=vmin,vmax=vmax) pl.xlabel("quad All (%.5f,%.5f)"%((vxn+hxn+vyn+hyn).min(),(vxn+hxn+vyn+hyn).max()))