Shot noise corruption to images.

  Args:
    x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
    severity: integer, severity of corruption.

  Returns:
    numpy array, image with uint8 pixels in [0,255]. Added shot noise.
556066
def shot_noise(x, severity=1):
  
  c = [60, 25, 12, 5, 3][severity - 1]
  x = np.array(x) / 255.
  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255
  return around_and_astype(x_clip)
303643
def pseudosample(x):
    
#
    BXs = []
    for k in range(len(x)):
        ind = random.randint(0, len(x) - 1)
        BXs.append(x[ind])
    return BXs
1018592
def sample_pixels(img, options):

    ''''''

    pixels = img.reshape((-1, 3))
    num_pixels = pixels.shape[0]
    num_samples = int(num_pixels*options.sample_fraction)

    idx = np.arange(num_pixels)
    np.random.shuffle(idx)

    return pixels[idx[:num_samples]]
1160069
def estimateFromImages(imgs1, imgs2=None, mn_mx=None, nbins=100):
    '''
    
    '''
    if imgs2 is None:
        imgs2 = [None] * len(imgs1)
    else:
        assert len(imgs1) == len(imgs2)

    y_vals = np.empty((len(imgs1), nbins))
    w_vals = np.zeros((len(imgs1), nbins))

    if mn_mx is None:
        print('estimating min and max image value')
        mn = 1e6
        mx = -1e6
        # get min and max image value checking all first images:
        for n, i1 in enumerate(imgs1):
            print('%s/%s' % (n + 1, len(imgs1)))
            i1 = imread(i1)
            mmn, mmx = _getMinMax(i1)
            mn = min(mn, mmn)
            mx = mx = max(mx, mmx)
        print('--> min(%s), max(%s)' % (mn, mx))
    else:
        mn, mx = mn_mx

    x = None
    print('get noise level function')
    for n, (i1, i2) in enumerate(zip(imgs1, imgs2)):
        print('%s/%s' % (n + 1, len(imgs1)))

        i1 = imread(i1)
        if i2 is not None:
            i2 = imread(i2)

        x, y, weights, _ = calcNLF(i1, i2, mn_mx_nbins=(mn, mx, nbins), x=x)
        y_vals[n] = y
        w_vals[n] = weights

    # filter empty places:
    filledPos = np.sum(w_vals, axis=0) != 0
    w_vals = w_vals[:, filledPos]
    y_vals = y_vals[:, filledPos]
    x = x[filledPos]

    y_avg = np.average(np.nan_to_num(y_vals),
                       weights=w_vals,
                       axis=0)
    w_vals = np.sum(w_vals, axis=0)
    w_vals /= w_vals.sum()

    fitParams, fn, i = _evaluate(x, y_avg, w_vals)
    return x, fn, y_avg, y_vals, w_vals, fitParams, i
445090
def vignettingFromRandomSteps(imgs, bg, inPlane_scale_factor=None,
                              debugFolder=None, **kwargs):
    '''
    
    '''
    # TODO: inPlane_scale_factor
    if debugFolder:
        debugFolder = PathStr(debugFolder)

    s = ObjectVignettingSeparation(imgs[0], bg,  **kwargs)
    for img in imgs[1:]:
        fit = s.addImg(img)

        if debugFolder and fit is not False:
            imwrite(debugFolder.join('fit_%s.tiff' % len(s.fits)), fit)

    if debugFolder:
        imwrite(debugFolder.join('init.tiff'), s.flatField)

    smoothed_ff, mask, flatField, obj = s.separate()

    if debugFolder:
        imwrite(debugFolder.join('object.tiff'), obj)
        imwrite(debugFolder.join('flatfield.tiff'), flatField, dtype=float)
        imwrite(debugFolder.join('flatfield_smoothed.tiff'), smoothed_ff,
                dtype=float)

    return smoothed_ff, mask
1075946
def array_to_img(x, scale=True):
    
    from PIL import Image
    if x.ndim != 3:
        raise Exception('Unsupported shape : ', str(x.shape), '. Need (channels, width, height)')
    if scale:
        x += max(-np.min(x), 0)
        x /= np.max(x)
        x *= 255
    if x.shape[0] == 3:
        # RGB
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.astype('uint8'), 'RGB')
    elif x.shape[0] == 1:
        # grayscale
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.reshape(x.shape[1], x.shape[2]), 'L')
    else:
        raise Exception('Unsupported channel number: ', x.shape[0])
260715
def visual(title, X, name):
    
    assert len(X.shape) == 4
    X = X.transpose((0, 2, 3, 1))
    X = np.clip((X - np.min(X))*(255.0/(np.max(X) - np.min(X))), 0, 255).astype(np.uint8)
    n = np.ceil(np.sqrt(X.shape[0]))
    buff = np.zeros((int(n*X.shape[1]), int(n*X.shape[2]), int(X.shape[3])), dtype=np.uint8)
    for i, img in enumerate(X):
        fill_buf(buff, i, img, X.shape[1:3])
    buff = buff[:, :, ::-1]
    plt.imshow(buff)
    plt.title(title)
    plt.savefig(name)
81226
def remove_interference_line(img):
    
    pixdata = img.load()
    w,h = img.size
    for y in range(1,h-1):
        for x in range(1,w-1):
            count = 0
            if pixdata[x,y-1] > 245:
                count = count + 1
            if pixdata[x,y+1] > 245:
                count = count + 1
            if pixdata[x-1,y] > 245:
                count = count + 1
            if pixdata[x+1,y] > 245:
                count = count + 1
            if count > 2:
                pixdata[x,y] = 255
    return img
553068
def corruptDenseVector(vector, noiseLevel):
  
  size = len(vector)
  for i in range(size):
    rnd = random.random()
    if rnd < noiseLevel:
      if vector[i] == 1:
        vector[i] = 0
      else:
        vector[i] = 1
729559
def threshold(image, block_size=DEFAULT_BLOCKSIZE, mask=None):
    
    if mask is None:
        mask = np.zeros(image.shape[:2], dtype=np.uint8)
        mask[:] = 255

    if len(image.shape) > 2 and image.shape[2] == 4:
        image = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
    res = _calc_block_mean_variance(image, mask, block_size)
    res = image.astype(np.float32) - res.astype(np.float32) + 255
    _, res = cv2.threshold(res, 215, 255, cv2.THRESH_BINARY)
    return res
1149667
def distorted_inputs():
  
  if not FLAGS.data_dir:
    raise ValueError('Please supply a data_dir')
  data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin')
  images, labels = cifar10_input.distorted_inputs(data_dir=data_dir,
                                                  batch_size=FLAGS.batch_size)
  if FLAGS.use_fp16:
    images = tf.cast(images, tf.float16)
    labels = tf.cast(labels, tf.float16)
  return images, labels
812745
def _make_bright_pixel_mask(intensity_mean, mask_factor=5.0):
        
        mask = np.zeros((intensity_mean.data.shape), bool)
        nebins = len(intensity_mean.data)
        sum_intensity = intensity_mean.data.sum(0)
        mean_intensity = sum_intensity.mean()
        for i in range(nebins):
            mask[i, 0:] = sum_intensity > (mask_factor * mean_intensity)
        return HpxMap(mask, intensity_mean.hpx)
593624
def zero_pixels(self):
        
        zero_px = np.where(np.sum(self.raw_data, axis=2) == 0)
        zero_px = np.c_[zero_px[0], zero_px[1]]
        return zero_px
244679
def finite_pixels(self):
        
        finite_px = np.where(np.isfinite(self.data))
        finite_px = np.c_[finite_px[0], finite_px[1]]
        return finite_px
902513
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    if self.ord != np.inf:
      raise NotImplementedError(self.ord)
    eta = tf.random_uniform(tf.shape(x), -self.eps, self.eps,
                            dtype=self.tf_dtype)
    adv_x = x + eta
    if self.clip_min is not None or self.clip_max is not None:
      assert self.clip_min is not None and self.clip_max is not None
      adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

    return adv_x
820747
public static float noise1(float x) {
        int bx0, bx1;
        float rx0, rx1, sx, t, u, v;

        if (start) {
            start = false;
            init();
        }

        t = x + N;
        bx0 = ((int)t) & BM;
        bx1 = (bx0+1) & BM;
        rx0 = t - (int)t;
        rx1 = rx0 - 1.0f;

        sx = sCurve(rx0);

        u = rx0 * g1[p[bx0]];
        v = rx1 * g1[p[bx1]];
        return 2.3f*lerp(sx, u, v);
    }
663270
def _correctArtefacts(self, image, threshold):
        '''
        
        '''
        image = np.nan_to_num(image)
        medianThreshold(image, threshold, copy=False)
        return image