Python skimage.filters.gaussian() Examples
The following are 30
code examples of skimage.filters.gaussian().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
skimage.filters
, or try the search function
.
Example #1
Source File: msct_register.py From spinalcordtoolbox with MIT License | 6 votes |
def circular_filter_1d(signal, window_size, kernel='gaussian'): """ This function filters circularly the signal inputted with a median filter of inputted size, in this context circularly means that the signal is wrapped around and then filtered inputs : - signal : 1D numpy array - window_size : size of the kernel, an int outputs : - signal_smoothed : 1D numpy array, same size as signal""" signal_extended = np.concatenate((signal, signal, signal)) # replicate signal at both ends if kernel == 'gaussian': signal_extended_smooth = ndimage.gaussian_filter(signal_extended, window_size) # gaussian elif kernel == 'median': signal_extended_smooth = medfilt(signal_extended, window_size) # median filtering else: raise Exception("Unknow type of kernel") signal_smoothed = signal_extended_smooth[len(signal):2*len(signal)] # truncate back the signal return signal_smoothed
Example #2
Source File: corruptions.py From robustness with Apache License 2.0 | 6 votes |
def glass_blur(x, severity=1): # sigma, max_delta, iterations c = [(0.7, 1, 2), (0.9, 2, 1), (1, 2, 3), (1.1, 3, 2), (1.5, 4, 2)][severity - 1] x = np.uint8(gaussian(np.array(x) / 255., sigma=c[0], multichannel=True) * 255) # locally shuffle pixels for i in range(c[2]): for h in range(224 - c[1], c[1], -1): for w in range(224 - c[1], c[1], -1): dx, dy = np.random.randint(-c[1], c[1], size=(2,)) h_prime, w_prime = h + dy, w + dx # swap x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w] return np.clip(gaussian(x / 255., sigma=c[0], multichannel=True), 0, 1) * 255
Example #3
Source File: MinutiaeNet_utils.py From MinutiaeNet with MIT License | 6 votes |
def smooth_dir_map(dir_map,sigma=2.0,mask = None): cos2Theta = np.cos(dir_map * 2) sin2Theta = np.sin(dir_map * 2) if mask is not None: assert (dir_map.shape[0] == mask.shape[0]) assert (dir_map.shape[1] == mask.shape[1]) cos2Theta[mask == 0] = 0 sin2Theta[mask == 0] = 0 cos2Theta = gaussian(cos2Theta, sigma, multichannel=False, mode='reflect') sin2Theta = gaussian(sin2Theta, sigma, multichannel=False, mode='reflect') dir_map = np.arctan2(sin2Theta,cos2Theta)*0.5 return dir_map
Example #4
Source File: enhancer_gan.py From ImageEnhancer with MIT License | 6 votes |
def _corrupt(self, source): """ corrupt the input with specific corruption method :param source: original data set :return: corrupted data set, if noise type is not defined, the original data set will return """ if self.corrupt_type is None: return source noised = np.zeros((np.shape(source)[0],) + self.shape['in']) for i, raw in enumerate(source): if self.corrupt_type == 'GSN': noised[i] = random_noise(raw, 'gaussian', var=self.corrupt_ratio) elif self.corrupt_type == 'MSN': noised[i] = random_noise(raw, 'pepper', amount=self.corrupt_ratio) elif self.corrupt_type == 'SPN': noised[i] = random_noise(raw, 's&p', amount=self.corrupt_ratio) elif self.corrupt_type == 'GSB': noised[i] = gaussian(raw, sigma=self.corrupt_ratio, multichannel=True) elif self.corrupt_type == 'GRY': noised[i] = gray2rgb(rgb2gray(raw)) elif self.corrupt_type == 'BLK': rad = int(self.corrupt_ratio) row = random.randint(rad, self.shape['in'][0] - rad - 1) col = random.randint(rad, self.shape['in'][1] - rad - 1) noised[i] = np.copy(raw) noised[i][circle(row, col, self.corrupt_ratio)] = 0 elif self.corrupt_type == 'ZIP': noised[i] = rescale(raw, 0.5, mode='constant') return noised
Example #5
Source File: make_cifar_c.py From robustness with Apache License 2.0 | 6 votes |
def glass_blur(x, severity=1): # sigma, max_delta, iterations c = [(0.05,1,1), (0.25,1,1), (0.4,1,1), (0.25,1,2), (0.4,1,2)][severity - 1] x = np.uint8(gaussian(np.array(x) / 255., sigma=c[0], multichannel=True) * 255) # locally shuffle pixels for i in range(c[2]): for h in range(32 - c[1], c[1], -1): for w in range(32 - c[1], c[1], -1): dx, dy = np.random.randint(-c[1], c[1], size=(2,)) h_prime, w_prime = h + dy, w + dx # swap x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w] return np.clip(gaussian(x / 255., sigma=c[0], multichannel=True), 0, 1) * 255
Example #6
Source File: make_tinyimagenet_c.py From robustness with Apache License 2.0 | 6 votes |
def glass_blur(x, severity=1): # sigma, max_delta, iterations c = [(0.1,1,1), (0.5,1,1), (0.6,1,2), (0.7,2,1), (0.9,2,2)][severity - 1] x = np.uint8(gaussian(np.array(x) / 255., sigma=c[0], multichannel=True) * 255) # locally shuffle pixels for i in range(c[2]): for h in range(64 - c[1], c[1], -1): for w in range(64 - c[1], c[1], -1): dx, dy = np.random.randint(-c[1], c[1], size=(2,)) h_prime, w_prime = h + dy, w + dx # swap x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w] return np.clip(gaussian(x / 255., sigma=c[0], multichannel=True), 0, 1) * 255
Example #7
Source File: makeup.py From face-makeup.PyTorch with MIT License | 6 votes |
def sharpen(img): img = img * 1.0 gauss_out = gaussian(img, sigma=5, multichannel=True) alpha = 1.5 img_out = (img - gauss_out) * alpha + img img_out = img_out / 255.0 mask_1 = img_out < 0 mask_2 = img_out > 1 img_out = img_out * (1 - mask_1) img_out = img_out * (1 - mask_2) + mask_2 img_out = np.clip(img_out, 0, 1) img_out = img_out * 255 return np.array(img_out, dtype=np.uint8)
Example #8
Source File: make_imagenet_64_c.py From robustness with Apache License 2.0 | 6 votes |
def glass_blur(x, severity=1): # sigma, max_delta, iterations c = [(0.1,1,1), (0.5,1,1), (0.6,1,2), (0.7,2,1), (0.9,2,2)][severity - 1] x = np.uint8(gaussian(np.array(x) / 255., sigma=c[0], multichannel=True) * 255) # locally shuffle pixels for i in range(c[2]): for h in range(64 - c[1], c[1], -1): for w in range(64 - c[1], c[1], -1): dx, dy = np.random.randint(-c[1], c[1], size=(2,)) h_prime, w_prime = h + dy, w + dx # swap x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w] return np.clip(gaussian(x / 255., sigma=c[0], multichannel=True), 0, 1) * 255
Example #9
Source File: common.py From ggcnn with BSD 3-Clause "New" or "Revised" License | 6 votes |
def post_process_output(q_img, cos_img, sin_img, width_img): """ Post-process the raw output of the GG-CNN, convert to numpy arrays, apply filtering. :param q_img: Q output of GG-CNN (as torch Tensors) :param cos_img: cos output of GG-CNN :param sin_img: sin output of GG-CNN :param width_img: Width output of GG-CNN :return: Filtered Q output, Filtered Angle output, Filtered Width output """ q_img = q_img.cpu().numpy().squeeze() ang_img = (torch.atan2(sin_img, cos_img) / 2.0).cpu().numpy().squeeze() width_img = width_img.cpu().numpy().squeeze() * 150.0 q_img = gaussian(q_img, 2.0, preserve_range=True) ang_img = gaussian(ang_img, 2.0, preserve_range=True) width_img = gaussian(width_img, 1.0, preserve_range=True) return q_img, ang_img, width_img
Example #10
Source File: corruptions.py From imagecorruptions with Apache License 2.0 | 6 votes |
def glass_blur(x, severity=1): # sigma, max_delta, iterations c = [(0.7, 1, 2), (0.9, 2, 1), (1, 2, 3), (1.1, 3, 2), (1.5, 4, 2)][ severity - 1] x = np.uint8( gaussian(np.array(x) / 255., sigma=c[0], multichannel=True) * 255) x_shape = np.array(x).shape # locally shuffle pixels for i in range(c[2]): for h in range(x_shape[0] - c[1], c[1], -1): for w in range(x_shape[1] - c[1], c[1], -1): dx, dy = np.random.randint(-c[1], c[1], size=(2,)) h_prime, w_prime = h + dy, w + dx # swap x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w] return np.clip(gaussian(x / 255., sigma=c[0], multichannel=True), 0, 1) * 255
Example #11
Source File: dataset.py From PoseNFS with MIT License | 6 votes |
def print_info(self): logger.info('need the grountruth mask information == {}'.format(self.use_mask)) if self.augment: logger.info( "augmentation is used for training" ) logger.info("setting: scale=1±{},rotation=0±{},flip(p=0.5)={},random_occlusion={}" .format(self.aug_scale,self.aug_rotation,self.flip,self.random_occlusion)) if self.random_occlusion: logger.info("occlusion block: probability = {},size = {},block_nums= {}" .format(self.occlusion_prob,self.occlusion_size,self.occlusion_nums)) else: logger.info('augmentation is not used ') logger.info("dataset:{} , total samples: {}".format(self.mode,len(self.data))) logger.info('Initial:Standard deviation of gaussian kernel for different keypoints heatmaps is:\n==> {}' .format(self.sigmas))
Example #12
Source File: crappifiers.py From PSSR with BSD 3-Clause "New" or "Revised" License | 6 votes |
def new_crap_AG_SP(x, scale=4, upsample=False): xn = np.array(x) xorig_max = xn.max() xn = xn.astype(np.float32) xn /= float(np.iinfo(np.uint8).max) lvar = filters.gaussian(xn, sigma=5) + 1e-10 xn = random_noise(xn, mode='localvar', local_vars=lvar*0.5) xn = random_noise(xn, mode='salt', amount=0.005) xn = random_noise(xn, mode='pepper', amount=0.005) new_max = xn.max() x = xn if new_max > 0: xn /= new_max xn *= xorig_max multichannel = len(x.shape) > 2 xn = rescale(xn, scale=1/scale, order=1, multichannel=multichannel) return PIL.Image.fromarray(xn.astype(np.uint8))
Example #13
Source File: image_tfs.py From tanda with MIT License | 6 votes |
def TF_elastic_deform(img, alpha=1.0, sigma=1.0): """Elastic deformation of images as described in Simard 2003""" assert len(img.shape) == 3 h, w, nc = img.shape if nc != 1: raise NotImplementedError("Multi-channel not implemented.") # Generate uniformly random displacement vectors, then convolve with gaussian kernel # and finally multiply by a magnitude coefficient alpha dx = alpha * gaussian_filter( (np.random.random((h, w)) * 2 - 1), sigma, mode="constant", cval=0 ) dy = alpha * gaussian_filter( (np.random.random((h, w)) * 2 - 1), sigma, mode="constant", cval=0 ) # Map image to the deformation mesh x, y = np.meshgrid(np.arange(h), np.arange(w), indexing='ij') indices = np.reshape(x+dx, (-1, 1)), np.reshape(y+dy, (-1, 1)) return map_coordinates(img.reshape((h,w)), indices, order=1).reshape(h,w,nc)
Example #14
Source File: locate_tissue.py From tissueloc with MIT License | 6 votes |
def thresh_slide(gray, thresh_val, sigma=13): """ Threshold gray image to binary image Parameters ---------- gray : np.array 2D gray image. thresh_val: float Thresholding value. smooth_sigma: int Gaussian smoothing sigma. Returns ------- bw_img: np.array Binary image """ # Smooth smooth = filters.gaussian(gray, sigma=sigma) smooth /= np.amax(smooth) # Threshold bw_img = smooth < thresh_val return bw_img
Example #15
Source File: composition.py From pytorch_connectomics with MIT License | 6 votes |
def smooth_edge(self, data): smoothed_label = data['label'].copy() for z in range(smoothed_label.shape[0]): temp = smoothed_label[z].copy() for idx in np.unique(temp): if idx != 0: binary = (temp==idx).astype(np.uint8) for _ in range(2): binary = dilation(binary) binary = gaussian(binary, sigma=2, preserve_range=True) binary = dilation(binary) binary = (binary > 0.8).astype(np.uint8) temp[np.where(temp==idx)]=0 temp[np.where(binary==1)]=idx smoothed_label[z] = temp data['label'] = smoothed_label return data
Example #16
Source File: utils.py From PSSR with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _my_noise(x, gauss_sigma:uniform=0.01, pscale:uniform=10): xn = x.numpy() xorig_max = xn.max() xn = random_noise(xn, mode='salt', amount=0.005) xn = random_noise(xn, mode='pepper', amount=0.005) lvar = filters.gaussian(x, sigma=5) + 1e-10 xn = random_noise(xn, mode='localvar', local_vars=lvar*0.5) #xn = np.random.poisson(xn*pscale)/pscale #xn += np.random.normal(0, gauss_sigma*xn.std(), size=x.shape) x = x.new(xn) new_max = xn.max() if new_max > 0: xn /= new_max xn *= xorig_max return x
Example #17
Source File: crappifiers.py From PSSR with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fluo_SP_AG_D_sameas_preprint_rescale(x, scale=4, upsample=False): xn = np.array(x) xorig_max = xn.max() xn = xn.astype(np.float32) xn /= float(np.iinfo(np.uint8).max) xn = random_noise(xn, mode='salt', amount=0.005) xn = random_noise(xn, mode='pepper', amount=0.005) lvar = filters.gaussian(xn, sigma=5) + 1e-10 xn = random_noise(xn, mode='localvar', local_vars=lvar*0.5) new_max = xn.max() x = xn if new_max > 0: xn /= new_max xn *= xorig_max multichannel = len(x.shape) > 2 x_down = rescale(x, scale=1/scale, order=1, multichannel=multichannel) return PIL.Image.fromarray(x_down.astype(np.uint8))
Example #18
Source File: crappifiers.py From PSSR with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fluo_SP_AG_D_sameas_preprint(x, scale=4, upsample=False): xn = np.array(x) xorig_max = xn.max() xn = xn.astype(np.float32) xn /= float(np.iinfo(np.uint8).max) xn = random_noise(xn, mode='salt', amount=0.005) xn = random_noise(xn, mode='pepper', amount=0.005) lvar = filters.gaussian(xn, sigma=5) + 1e-10 xn = random_noise(xn, mode='localvar', local_vars=lvar*0.5) new_max = xn.max() x = xn if new_max > 0: xn /= new_max xn *= xorig_max x_down = npzoom(x, 1/scale, order=1) return PIL.Image.fromarray(x_down.astype(np.uint8))
Example #19
Source File: crappifiers.py From PSSR with BSD 3-Clause "New" or "Revised" License | 6 votes |
def fluo_AG_D(x, scale=4, upsample=False): xn = np.array(x) xorig_max = xn.max() xn = xn.astype(np.float32) xn /= float(np.iinfo(np.uint8).max) lvar = filters.gaussian(xn, sigma=5) + 1e-10 xn = random_noise(xn, mode='localvar', local_vars=lvar*0.5) new_max = xn.max() x = xn if new_max > 0: xn /= new_max xn *= xorig_max x_down = npzoom(x, 1/scale, order=1) #x_up = npzoom(x_down, scale, order=1) return PIL.Image.fromarray(x_down.astype(np.uint8))
Example #20
Source File: crappifiers.py From PSSR with BSD 3-Clause "New" or "Revised" License | 6 votes |
def new_crap(x, scale=4, upsample=False): xn = np.array(x) xorig_max = xn.max() xn = xn.astype(np.float32) xn /= float(np.iinfo(np.uint8).max) xn = random_noise(xn, mode='salt', amount=0.005) xn = random_noise(xn, mode='pepper', amount=0.005) lvar = filters.gaussian(xn, sigma=5) + 1e-10 xn = random_noise(xn, mode='localvar', local_vars=lvar*0.5) new_max = xn.max() x = xn if new_max > 0: xn /= new_max xn *= xorig_max multichannel = len(x.shape) > 2 x = rescale(x, scale=1/scale, order=1, multichannel=multichannel) return PIL.Image.fromarray(x.astype(np.uint8))
Example #21
Source File: makeup.py From face-parsing.PyTorch with MIT License | 6 votes |
def sharpen(img): img = img * 1.0 gauss_out = gaussian(img, sigma=5, multichannel=True) alpha = 1.5 img_out = (img - gauss_out) * alpha + img img_out = img_out / 255.0 mask_1 = img_out < 0 mask_2 = img_out > 1 img_out = img_out * (1 - mask_1) img_out = img_out * (1 - mask_2) + mask_2 img_out = np.clip(img_out, 0, 1) img_out = img_out * 255 return np.array(img_out, dtype=np.uint8)
Example #22
Source File: test_white_tophat.py From starfish with MIT License | 5 votes |
def simple_spot_3d(): big_spot = np.zeros((100, 100, 100), dtype=np.uint16) big_spot[20, 20, 20] = 10000 big_spot = gaussian(big_spot, sigma=(4, 4, 4), preserve_range=True).astype(np.uint16) small_spot = np.zeros((100, 100, 100), dtype=np.uint16) small_spot[80, 80, 80] = 10000 small_spot = gaussian(small_spot, sigma=(1, 1, 1), preserve_range=True).astype(np.uint16) return big_spot + small_spot
Example #23
Source File: transforms.py From KagglePlanetPytorch with MIT License | 5 votes |
def blur(sigma=0.1): def call(x): x = gaussian(x, sigma=sigma, preserve_range=True, multichannel=True) return x return call
Example #24
Source File: transforms.py From KagglePlanetPytorch with MIT License | 5 votes |
def random_blur(sigma=lambda: np.random.random_sample()*1): def call(x): x = gaussian(x, sigma=sigma(), preserve_range=True, multichannel=True) return x return call
Example #25
Source File: visualizer.py From dlcv_for_beginners with BSD 3-Clause "New" or "Revised" License | 5 votes |
def draw_density_estimation(self, axis, title, samples, cmap): axis.clear() axis.set_xlabel(title) density_estimation = numpy.zeros((self.l_kde, self.l_kde)) for x, y in samples: if 0 < x < 1 and 0 < y < 1: density_estimation[int((1-y) / self.resolution)][int(x / self.resolution)] += 1 density_estimation = filters.gaussian(density_estimation, self.bw_kde_) axis.imshow(density_estimation, cmap=cmap) axis.xaxis.set_major_locator(pyplot.NullLocator()) axis.yaxis.set_major_locator(pyplot.NullLocator())
Example #26
Source File: MinutiaeNet_utils.py From MinutiaeNet with MIT License | 5 votes |
def gaussian2d(shape=(5,5),sigma=0.5): """ 2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma]) """ m,n = [(ss-1.)/2. for ss in shape] y,x = np.ogrid[-m:m+1,-n:n+1] h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) ) h[ h < np.finfo(h.dtype).eps*h.max() ] = 0 sumh = h.sum() if sumh != 0: h /= sumh return h
Example #27
Source File: cellularity_detection_thresholding.py From HistomicsTK with Apache License 2.0 | 5 votes |
def find_potentially_cellular_regions(self): """Find regions that are potentially cellular.""" mask_out = self.labeled != self.cdt.GTcodes.loc[ "not_specified", "GT_code"] # deconvolvve to ge hematoxylin channel (cellular areas) # hematoxylin channel return shows MINIMA so we invert self.tissue_htx, _, _ = color_deconvolution_routine( self.tissue_rgb, mask_out=mask_out, **self.cdt.stain_unmixing_routine_params) self.tissue_htx = 255 - self.tissue_htx[..., 0] # get cellular regions by threshold HTX stain channel self.maybe_cellular, _ = get_tissue_mask( self.tissue_htx.copy(), deconvolve_first=False, n_thresholding_steps=1, sigma=self.cdt.cellular_step1_sigma, min_size=self.cdt.cellular_step1_min_size) # Second, low-pass filter to dilate and smooth a bit self.maybe_cellular = gaussian( 0 + (self.maybe_cellular > 0), sigma=self.cdt.cellular_step2_sigma, output=None, mode='nearest', preserve_range=True) # find connected components self.maybe_cellular, _ = ndimage.label(self.maybe_cellular) # restrict cellular regions to not-otherwise-specified self.maybe_cellular[mask_out] = 0 # assign to mask self.labeled[self.maybe_cellular > 0] = self.cdt.GTcodes.loc[ 'maybe_cellular', 'GT_code'] # =========================================================================
Example #28
Source File: MinutiaeNet_utils.py From MinutiaeNet with MIT License | 5 votes |
def get_quality_map_ori_dict(img, dict, spacing, dir_map = None, block_size = 16): if img.dtype=='uint8': img = img.astype(np.float) img = FastEnhanceTexture(img) h, w = img.shape blkH, blkW = dir_map.shape quality_map = np.zeros((blkH,blkW),dtype=np.float) fre_map = np.zeros((blkH,blkW),dtype=np.float) ori_num = len(dict) #dir_map = math.pi/2 - dir_map dir_ind = dir_map*ori_num/math.pi dir_ind = dir_ind.astype(np.int) dir_ind = dir_ind%ori_num patch_size = np.sqrt(dict[0].shape[1]) patch_size = patch_size.astype(np.int) pad_size = (patch_size-block_size)//2 img = np.lib.pad(img, (pad_size, pad_size), 'symmetric') for i in range(0,blkH): for j in range(0,blkW): ind = dir_ind[i,j] patch = img[i*block_size:i*block_size+patch_size,j*block_size:j*block_size+patch_size] patch = patch.reshape(patch_size*patch_size,) patch = patch - np.mean(patch) patch = patch / (np.linalg.norm(patch)+0.0001) patch[patch>0.05] = 0.05 patch[patch<-0.05] = -0.05 simi = np.dot(dict[ind], patch) similar_ind = np.argmax(abs(simi)) quality_map[i,j] = np.max(abs(simi)) fre_map[i,j] = 1./spacing[ind][similar_ind] quality_map = gaussian(quality_map,sigma=2) return quality_map, fre_map
Example #29
Source File: MinutiaeNet_utils.py From MinutiaeNet with MIT License | 5 votes |
def gausslabel(length=180, stride=2): gaussian_pdf = signal.gaussian(length+1, 3) label = np.reshape(np.arange(stride/2, length, stride), [1,1,-1,1]) y = np.reshape(np.arange(stride/2, length, stride), [1,1,1,-1]) delta = np.array(np.abs(label - y), dtype=int) delta = np.minimum(delta, length-delta)+length/2 return gaussian_pdf[delta]
Example #30
Source File: gaussian_low_pass.py From starfish with MIT License | 5 votes |
def _low_pass( image: xr.DataArray, sigma: Union[Number, Tuple[Number]], ) -> xr.DataArray: """ Apply a Gaussian blur operation over a multi-dimensional image. Parameters ---------- image : xr.DataArray 2-d or 3-d image data sigma : Union[Number, Tuple[Number]] Standard deviation of the Gaussian kernel that will be applied. If a float, an isotropic kernel will be assumed, otherwise the dimensions of the kernel give (z, y, x) rescale : bool If true scales data by max value, if false clips max values to one (default False) Returns ------- xr.DataArray : Blurred data in same shape as input image """ filtered = gaussian( image, sigma=sigma, output=None, cval=0, multichannel=False, preserve_range=True, truncate=4.0 ) return filtered