Python add gaussian noise

25 Python code examples are found related to " add gaussian noise". 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.
Example 1
Source File: utils.py    From DMENet with GNU Affero General Public License v3.0 9 votes vote down vote up
def add_gaussian_noise(image):
    image = image.astype(np.float32)
    shape = image.shape[:2]

    mean = 0
    var = random.uniform(0,0.1)
    sigma = var ** 0.5
    gamma = 0.25
    alpha = 0.75
    beta = 1 - alpha

    gaussian = np.random.normal(loc=mean, scale = sigma, size = (shape[0], shape[1], 1)).astype(np.float32)
    gaussian = np.concatenate((gaussian, gaussian, gaussian), axis = 2)
    #gaussian_img = image * 0.75 + 0.25 * gaussian + 0.25
    gaussian_img = cv2.addWeighted(image, alpha, beta * gaussian, beta, gamma)

    return gaussian_img

    # noise_sigma = 0.01
    # h = image.shape[0]
    # w = image.shape[1]
    # noise = np.random.randn(h, w) * noise_sigma

    # noisy_image = np.zeros(image.shape, np.float64)
    # if len(image.shape) == 2:
    #     noisy_image = image + noise
    # else:
    #     noisy_image[:,:,0] = image[:,:,0] + noise
    #     noisy_image[:,:,1] = image[:,:,1] + noise
    #     noisy_image[:,:,2] = image[:,:,2] + noise

    # """
    # print('min,max = ', np.min(noisy_image), np.max(noisy_image))
    # print('type = ', type(noisy_image[0][0][0]))
    # """

    # return noisy_image 
Example 2
Source File: utils.py    From taskonomy with MIT License 6 votes vote down vote up
def add_gaussian_noise_layer( input_layer, std, scope ):
    with tf.variable_scope( scope ) as sc:
        noise = tf.random_normal( shape=input_layer.get_shape(), mean=0.0, stddev=std, 
                    dtype=tf.float32 )
        print('\t\t{scope}'.format( scope=scope ), noise.get_shape() ) 
        return input_layer + noise 
Example 3
Source File: utils.py    From multilabel-image-classification-tensorflow with MIT License 5 votes vote down vote up
def AddGaussianNoise(t, sigma, name=None):
  """Add i.i.d. Gaussian noise (0, sigma^2) to every entry of t.

  Args:
    t: the input tensor.
    sigma: the stddev of the Gaussian noise.
    name: optional name.
  Returns:
    the noisy tensor.
  """

  with tf.name_scope(values=[t, sigma], name=name,
                     default_name="add_gaussian_noise") as name:
    noisy_t = t + tf.random_normal(tf.shape(t), stddev=sigma)
  return noisy_t 
Example 4
Source File: ColorAugmentersMethods.py    From impy with Apache License 2.0 5 votes vote down vote up
def addGaussianNoise(self, frame = None, coefficient = None):
		"""
		Add gaussian noise to a tensor.
		Args:
			frame: A tensor that contains an image.
			coefficient: A float that contains the amount of noise to add
										to a frame.
		Returns:
			An altered frame that has gaussian noise.
		"""
		pass 
Example 5
Source File: pre_processing.py    From pytorch-unet-segmentation with MIT License 5 votes vote down vote up
def add_gaussian_noise(image, mean=0, std=1):
    """
    Args:
        image : numpy array of image
        mean : pixel mean of image
        standard deviation : pixel standard deviation of image
    Return :
        image : numpy array of image with gaussian noise added
    """
    gaus_noise = np.random.normal(mean, std, image.shape)
    image = image.astype("int16")
    noise_img = image + gaus_noise
    image = ceil_floor_image(image)
    return noise_img 
Example 6
Source File: calcMeanValue.py    From TensorflowLite-UNet with MIT License 5 votes vote down vote up
def addGaussianNoise(src):
    row,col,ch= src.shape
    mean = 0
    var = 0.1
    sigma = 15
    gauss = np.random.normal(mean,sigma,(row,col,ch))
    gauss = gauss.reshape(row,col,ch)
    noisy = src + gauss
    return noisy

# Salt & Pepper noise function 
Example 7
Source File: image_processing.py    From train-mtcnn-head with MIT License 5 votes vote down vote up
def addGaussianNoise(image,percetage): 
    G_Noiseimg = image.copy()
    w = image.shape[1]
    h = image.shape[0]
    G_NoiseNum=int(percetage*image.shape[0]*image.shape[1]) 
    for i in range(G_NoiseNum): 
        temp_x = np.random.randint(0,h) 
        temp_y = np.random.randint(0,w) 
        G_Noiseimg[temp_x][temp_y][np.random.randint(3)] = np.random.randn(1)[0] 
    return G_Noiseimg
#dimming 
Example 8
Source File: utils.py    From ECO-pytorch with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def AddGaussianNoise(t, sigma, name=None):
  """Add i.i.d. Gaussian noise (0, sigma^2) to every entry of t.

  Args:
    t: the input tensor.
    sigma: the stddev of the Gaussian noise.
    name: optional name.
  Returns:
    the noisy tensor.
  """

  with tf.op_scope([t, sigma], name, "add_gaussian_noise") as name:
    noisy_t = t + tf.random_normal(tf.shape(t), stddev=sigma)
  return noisy_t 
Example 9
Source File: augmentation.py    From DLTK with Apache License 2.0 5 votes vote down vote up
def add_gaussian_noise(image, sigma=0.05):
    """
    Add Gaussian noise to an image

    Args:
        image (np.ndarray): image to add noise to
        sigma (float): stddev of the Gaussian distribution to generate noise
            from

    Returns:
        np.ndarray: same as image but with added offset to each channel
    """

    image += np.random.normal(0, sigma, image.shape)
    return image 
Example 10
Source File: AntBulletEnv.py    From FitML with MIT License 5 votes vote down vote up
def add_gaussian_noise(mu,noiseSigma,largeNoise=False):
    #print ( gauss(mu, noiseSigma) )
    if np.random.rand(1) < MUTATION_PROB:
        return gauss(mu, noiseSigma)
    else:
        return mu+0.0

#add_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float]) 
Example 11
Source File: op_utils.py    From KATE with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_gaussian_noise(X, corruption_ratio, range_=[0, 1]):
    X_noisy = X + corruption_ratio * np.random.normal(loc=0.0, scale=1.0, size=X.shape)
    X_noisy = np.clip(X_noisy, range_[0], range_[1])

    return X_noisy 
Example 12
Source File: utils.py    From machine-learning-diff-private-federated-learning with Apache License 2.0 5 votes vote down vote up
def AddGaussianNoise(t, sigma, noise_rate, name=None):
  """Add i.i.d. Gaussian noise (0, sigma^2) to every entry of t.
  Args:
    t: the input tensor.
    sigma: the stddev of the Gaussian noise.
    name: optional name.
  Returns:
    the noisy tensor.
  """

  with tf.name_scope(values=[t, sigma], name=name,
                     default_name="add_gaussian_noise") as name:
    noisy_t = t + tf.scalar_mul(noise_rate, tf.random_normal(tf.shape(t), stddev=sigma))
  return noisy_t 
Example 13
Source File: chart.py    From talk-generator with MIT License 5 votes vote down vote up
def add_gaussian_noise_to_multidim_points(max_noise_ratio, datapoints):
    return [
        _add_gaussian_noise_to_multidim_point(max_noise_ratio, point)
        for point in datapoints
    ] 
Example 14
Source File: images_data_augmenter_seqaware.py    From RecurrentGaze with MIT License 5 votes vote down vote up
def add_gaussian_noise(images: list, var: list, random_var: float=None, gauss_noise: list=None):
    """
    Add gaussian noise to input images. If random_var and gauss_noise are given, use them to compute the final images.
    Otherwise, compute random_var and gauss_noise.
    :param images: list of images
    :param var: variance range from which the variance value is uniformly sampled if random_var is None.
    :param random_var: optional value specifying the variance multiplier.
    :param gauss_noise: optional value specifying the additive gaussian noise per image.
    :return: transformed image, random_var value, gauss_noise_out list
    """
    if random_var is None:
        random_var = np.random.uniform(var[0], var[1])
    mean = 0
    new_images = []
    gauss_noise_out = []
    for i,image in enumerate(images):
        row, col, c = image.shape
        if gauss_noise is None or \
                (gauss_noise is not None and row*col*c !=
                 gauss_noise[i].shape[0]*gauss_noise[i].shape[1] * gauss_noise[i].shape[2]):
            gauss = np.random.normal(mean, random_var * 127.5, (row, col, c))
        else:
            gauss = gauss_noise[i]
        gauss_noise_out.append(gauss)
        gauss = gauss.reshape(row, col, c)
        image1 = np.clip(image + gauss, 0., 255.)
        new_images.append(image1)
    return new_images, random_var, gauss_noise_out 
Example 15
Source File: data_convertors.py    From DualResidualNetworks with MIT License 5 votes vote down vote up
def AddGaussianNoise(patchs, var):
    # A randomly generated seed. Use it for an easy performance comparison.
    m_seed_cpu = 8526081014239199321
    m_seed_gpu = 8223752412272754
    torch.cuda.manual_seed(m_seed_gpu)
    torch.manual_seed(m_seed_cpu)
    
    c, h, w = patchs.size()
    noise_pad = torch.FloatTensor(c, h, w).normal_(0, var)
    noise_pad = torch.div(noise_pad, 255.0)
    patchs+= noise_pad    
    return patchs 
Example 16
Source File: seq_preprocess.py    From sanet_relocal_demo with GNU General Public License v3.0 4 votes vote down vote up
def add_gaussian_noise(seq, rot_noise_deg=10.0, loc_displace_factor=0.1):
    """
    Add gaussian noise for the pose of keyframes
    :param seq: keyframe sequences, dim: (M, 3, 4), M is the number of keyframes
    :param rot_noise_deg: noise in rotation (unit: deg)
    :param loc_displace_factor: displacement factor in translation, the unit 1 is the avg. baseline among all cameras.
    :return: noise sequences with dim (M, 3, 4), displacement std.
    """
    n_frames = seq.shape[0]

    avg_frame_dist = 0
    R, t = cam_opt.Rt(seq[0])
    pre_frame_center = cam_opt.camera_center_from_Tcw(R, t)
    for frame_idx in range(1, n_frames):
        R, t = cam_opt.Rt(seq[frame_idx])
        frame_center = cam_opt.camera_center_from_Tcw(R, t)
        dist = np.linalg.norm(frame_center - pre_frame_center)
        avg_frame_dist += dist
    avg_frame_dist /= n_frames

    # Set the translation noise
    loc_disp_noise_sigma = loc_displace_factor * avg_frame_dist     # std. for random displacement
    disp_noise = np.random.normal(0, loc_disp_noise_sigma, size=(n_frames, 3))

    # Set the rotation noise
    rot_noise_factor = np.deg2rad(rot_noise_deg)
    rot_noise = np.random.normal(0, rot_noise_factor, size=n_frames)

    new_seq = seq.copy()
    for frame_idx in range(1, n_frames):
        T = seq[frame_idx]
        R, t = cam_opt.Rt(T)

        # Add random noise to translation
        C = cam_opt.camera_center_from_Tcw(R, t)
        rand_C = C + disp_noise[frame_idx]

        # Add random noise to rotation
        temp_T = np.eye(4)
        temp_T[:3, :3] = R
        angle, axis, _ = trans.rotation_from_matrix(temp_T)
        new_angle = angle + rot_noise[frame_idx]
        new_axis = axis + np.random.normal(0, 0.1, size=3)
        new_R = trans.rotation_matrix(new_angle, new_axis)[:3, :3]

        new_t = cam_opt.translation_from_center(new_R, rand_C)
        new_seq[frame_idx][:3, :3] = new_R[:3, :3]
        new_seq[frame_idx][:3, 3] = new_t

    return new_seq, loc_disp_noise_sigma