http://scikit-image.org/docs/dev/api/skimage.restoration.html?highlight=denoise
198204
def updateframe(t, raw, wavelen, cam, ax, fg):
    showcb = False

    ttxt = f'Cam {cam.name}: '

    if raw.ndim == 3:
        frame = raw[t, ...]
    elif raw.ndim == 2:
        frame = raw
    elif raw.ndim == 1:  # GeoData
        frame = raw.reshape((sqrt(raw.size), -1))
    else:
        raise ValueError('ndim==3 or 2')
# %% filtering (optional) # FIXME provide noise estimate
    
    if 'wiener' in cam.cp:
        # psf = ones((cam.wiener, cam.wiener)) / cam.wiener**2
        frame = wiener(frame, cam.cp['wiener'])

    if 'medfilt2d' in cam.cp:
        frame = medfilt2d(frame.astype(float), cam.cp['medfilt2d'])

    if 'denoise_bilateral' in cam.cp:
        frame = skres.denoise_bilateral(((frame - cam.clim[0]) / (cam.clim[1] - cam.clim[0])).clip(0., 1.),
                                        sigma_color=0.05, sigma_spatial=15, multichannel=False)
    if 'denoise_tv_chambolle' in cam.cp:
        frame = skres.denoise_tv_chambolle(((frame - cam.clim[0]) / (cam.clim[1] - cam.clim[0])).clip(0., 1.),
                                           )
# %% plotting raw uint16 data
    if False:
        v = vis.HistEqStretch(frame)
        NORM = ImageNormalize(stretch=v)

    NORM = None
    #  NORM = LogNorm()
    # NORM = ImageNormalize(stretch=vis.LogStretch())

    hi = ax.imshow(frame,
                   origin='lower', interpolation='none',
                   # aspect='equal',
                   # extent=(0,C.superx,0,C.supery),
                   vmin=cam.clim[0], vmax=cam.clim[1],
                   cmap='gray', norm=NORM)

    # autoscale(False) for case where we put plots on top of image
    # yet still reduces blank space between subplots
    ax.autoscale(False)

    if showcb:  # showing the colorbar makes the plotting go 5-10x more slowly
        hc = fg.colorbar(hi, ax=ax)  # not cax!
        hc.set_label(f'{raw.dtype} data numbers')

    dtframe = datetime.utcfromtimestamp(cam.tKeo[t])

    if cam.name == 'asi':
        dtstr = datetime.strftime(dtframe, '%H:%M:%S')
        if int(wavelen[t]) == 428:
            tcolor = 'blue'
        elif int(wavelen[t]) == 557:
            tcolor = 'limegreen'
        elif int(wavelen[t]) == 630:
            tcolor = 'red'
        else:
            tcolor = 'limegreen'
        ttxt += f'{dtstr} $\lambda$ {wavelen[t]:.1f}'
    else:
        dtstr = datetime.strftime(dtframe, '%H:%M:%S.%f')[:-3]  # millisecond
        tcolor = 'limegreen'
        ttxt += f'{dtstr}'

    ax.set_title(ttxt, color=tcolor)

    ax.set_axis_off()  # no ticks

    if False:
        ax.set_xlabel('x-pixel')
        if cam.name == 0:
            ax.set_ylabel('y-pixel')
# %% plotting 1D cut line
    try:
        ax.plot(cam.cutcol[cam.Lcind], cam.cutrow[cam.Lcind],
                marker='.', linestyle='none', color='blue', markersize=1, alpha=0.5)
        # plot magnetic zenith
        ax.scatter(x=cam.cutcol[cam.angleMagzenind],
                   y=cam.cutrow[cam.angleMagzenind],
                   marker='o', facecolors='none', color='red', s=500, linewidth=2, alpha=0.5)
    except AttributeError:  # asi
        pass
# %% plot cleanup
    ax.grid(False)  # in case Seaborn is used
    return dtframe
162923
public static <T extends ImageGray<T>> DenoiseWavelet<T> sure(Class<T> imageType )
	{
		if( imageType == GrayF32.class ) {
			return (DenoiseWavelet<T>)new DenoiseSureShrink_F32();
		} else {
			throw new IllegalArgumentException("Unsupported image type "+imageType);
		}
	}
1322147
def iterstraight(self, raw):
        

        # length of row, in bytes
        rb = self.row_bytes
        a = array('B')
        # The previous (reconstructed) scanline.  None indicates first
        # line of image.
        recon = None
        for some in raw:
            a.extend(some)
            while len(a) >= rb + 1:
                filter_type = a[0]
                scanline = a[1:rb+1]
                del a[:rb+1]
                recon = self.undo_filter(filter_type, scanline, recon)
                yield recon
        if len(a) != 0:
            # :file:format We get here with a file format error:
            # when the available bytes (after decompressing) do not
            # pack into exact rows.
            raise FormatError(
              'Wrong size for decompressed IDAT chunk.')
        assert len(a) == 0
1307178
def _denoise(seeds, x, dico, sup_bound, n_atoms, verbose=False, indep=True,
             stop_crit=None, selection_rule=None, pad=0,
             memory=Memory(None)):
    
    approx = []
    for seed in seeds:
        if verbose > 0:
            print("Run seed %d" % seed)
        if indep:
            approx.append(_single_mp_run(x, dico, sup_bound, n_atoms,
                                         verbose=verbose, pad=pad,
                                         random_state=seed,
                                         memory=memory)[0])
        else:
            approx.append(_single_multichannel_mp_run(x, dico, sup_bound,
                                                      selection_rule,
                                                      stop_crit,
                                                      n_atoms, verbose=verbose,
                                                      pad=pad,
                                                      random_state=seed,
                                                      memory=memory)[0])
    return approx
9017
def noisepickle(d, data, u, v, w, chunk=200):
    

    if d['savenoise']:
        noisefile = getnoisefile(d)

        if os.path.exists(noisefile):
            logger.warn('noisefile %s already exists' % noisefile)
        else:
            nints = len(data)
            chunk = min(chunk, nints)  # ensure at least one measurement
            results = []

            rr = range(0, nints, chunk)
            if len(rr) == 1: rr.append(1)   # hack. need to make sure it iterates for nints=1 case
            for i in range(len(rr)-1):
                imid = (rr[i]+rr[i+1])/2
                noiseperbl = estimate_noiseperbl(data[rr[i]:rr[i+1]])
                imstd = sample_image(d, data, u, v, w, imid, verbose=0).std()
                zerofrac = float(len(n.where(data[rr[i]:rr[i+1]] == 0j)[0]))/data[rr[i]:rr[i+1]].size
                results.append( (d['segment'], noiseperbl, zerofrac, imstd) )

            with open(noisefile, 'a') as pkl:
                pickle.dump(results, pkl)
            logger.info('Wrote %d noise measurement%s to %s.' % (len(results), 's'[:len(results)-1], noisefile))
165763
def _coarsenImage(image, f):
    '''
    
    '''
    from skimage.morphology import square
    from skimage.filters import rank
    from skimage.transform._warps import rescale
    selem = square(f)
    arri = rank.mean(image, selem=selem)
    return rescale(arri, 1 / f, order=0)
1331915
def _replace_bm(self):
        """"""
        self._block_matcher = cv2.StereoSGBM(minDisparity=self._min_disparity,
                        numDisparities=self._num_disp,
                        SADWindowSize=self._sad_window_size,
                        uniquenessRatio=self._uniqueness,
                        speckleWindowSize=self._speckle_window_size,
                        speckleRange=self._speckle_range,
                        disp12MaxDiff=self._max_disparity,
                        P1=self._P1,
                        P2=self._P2,
                        fullDP=self._full_dp)
79571
def plotnoise(noisepkl, mergepkl, plot_width=950, plot_height=400):
    

    d = pickle.load(open(mergepkl))
    ndist, imstd, flagfrac = plotnoisedist(noisepkl, plot_width=plot_width/2, plot_height=plot_height)
    fluxscale = calcfluxscale(d, imstd, flagfrac)
    logger.info('Median image noise is {0:.3} Jy.'.format(fluxscale*imstd))
    ncum, imnoise = plotnoisecum(noisepkl, fluxscale=fluxscale, plot_width=plot_width/2, plot_height=plot_height)

    hndle = show(Row(ndist, ncum, width=plot_width, height=plot_height))
    return imnoise
930878
def _clean_background(data):
    
    allowed_keys = set(["variant", "cnv_reference"])
    val = tz.get_in(["algorithm", "background"], data)
    errors = []
    if val:
        out = {}
        # old style specification, single string for variant
        if isinstance(val, six.string_types):
            out["variant"] = _file_to_abs(val, [os.getcwd()])
        elif isinstance(val, dict):
            for k, v in val.items():
                if k in allowed_keys:
                    if isinstance(v, six.string_types):
                        out[k] = _file_to_abs(v, [os.getcwd()])
                    else:
                        assert isinstance(v, dict)
                        for ik, iv in v.items():
                            v[ik] = _file_to_abs(iv, [os.getcwd()])
                        out[k] = v
                else:
                    errors.append("Unexpected key: %s" % k)
        else:
            errors.append("Unexpected input: %s" % val)
        if errors:
            raise ValueError("Problematic algorithm background specification for %s:\n %s" %
                             (data["description"], "\n".join(errors)))
        out["cnv_reference"] = structural.standardize_cnv_reference({"config": data,
                                                                     "description": data["description"]})
        data["algorithm"]["background"] = out
    return data
603637
def deinterlace(self, raw):
        
        # Values per row (of the target image)
        vpr = self.width * self.planes

        # Make a result array, and make it big enough.  Interleaving
        # writes to the output array randomly (well, not quite), so the
        # entire output array must be in memory.
        if self.bitdepth > 8:
            a = newHarray(vpr * self.height)
        else:
            a = newBarray(vpr * self.height)
        source_offset = 0
        filt = Filter(self.bitdepth * self.planes)
        for xstart, ystart, xstep, ystep in _adam7:
            if xstart >= self.width:
                continue
            # The previous (reconstructed) scanline.  None at the
            # beginning of a pass to indicate that there is no previous
            # line.
            filt.prev = None
            # Pixels per row (reduced pass image)
            ppr = int(math.ceil((self.width-xstart)/float(xstep)))
            # Row size in bytes for this pass.
            row_size = int(math.ceil(self.psize * ppr))
            for y in range(ystart, self.height, ystep):
                filter_type = raw[source_offset]
                scanline = raw[source_offset + 1:source_offset + row_size + 1]
                source_offset += (row_size + 1)
                if filter_type not in (0, 1, 2, 3, 4):
                    raise FormatError('Invalid PNG Filter Type.'
                '  See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .')
                filt.undo_filter(filter_type, scanline)
                # Convert so that there is one element per pixel value
                flat = self.serialtoflat(scanline, ppr)
                end_offset = (y + 1) * vpr
                if xstep == 1:
                    # Last pass (0, 1, 1, 2))
                    assert xstart == 0
                    offset = y * vpr
                    a[offset:end_offset] = flat
                else:
                    offset = y * vpr + xstart * self.planes
                    for i in range(self.planes):
                        a[offset + i:end_offset:self.planes * xstep] = \
                            flat[i::self.planes]
        return a
76752
def restore(self):
        
        clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2)

        if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)):
            self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(conv.pad_array(self.model))*np.fft.rfft2(clean_beam)))
            self.restored = self.restored[self.dirty_data_shape[0]/2:-self.dirty_data_shape[0]/2,
                            self.dirty_data_shape[1]/2:-self.dirty_data_shape[1]/2]
        else:
            self.restored = np.fft.fftshift(np.fft.irfft2(np.fft.rfft2(self.model)*np.fft.rfft2(clean_beam)))
        self.restored += self.residual
        self.restored = self.restored.astype(np.float32)

        return beam_params
284085
def quantize_without_scipy(self, image):
        "
        w, h = image.size
        px = np.asarray(image).copy()
        memo = {}
        for j in range(w):
            for i in range(h):
                key = (px[i, j, 0], px[i, j, 1], px[i, j, 2])
                try:
                    val = memo[key]
                except KeyError:
                    val = self.convert(*key)
                    memo[key] = val
                px[i, j, 0], px[i, j, 1], px[i, j, 2] = val
        return Image.fromarray(px).convert("RGB").quantize(palette=self.palette_image())
1193991
def _fix_diffusion_images(bvals, bvecs, nifti, nifti_file):
    
    # if all zero continue of if the last bvec is not all zero continue
    if numpy.count_nonzero(bvecs) == 0 or not numpy.count_nonzero(bvals[-1]) == 0:
        # nothing needs to be done here
        return nifti, bvals, bvecs
    # remove last elements from bvals and bvecs
    bvals = bvals[:-1]
    bvecs = bvecs[:-1]

    # remove last elements from the nifti
    new_nifti = nibabel.Nifti1Image(nifti.get_data()[:, :, :, :-1], nifti.affine)
    new_nifti.to_filename(nifti_file)

    return new_nifti, bvals, bvecs
981820
def denoise(self,bitthresh=0.5):
        
        for i in range(self.width):
            tot = 0
            for letter in ACGT:
                if self.logP:
                    Pij = pow(2.0, self.logP[i][letter])
                else:
                    Pij = pow(2.0, self.ll[i][letter]) * self.background[letter]
                if Pij > 0.01:
                    bit = Pij * self.ll[i][letter]
                    tot = tot + bit
            if tot < bitthresh:  #Zero Column
                for letter in ACGT:
                    self.ll[i][letter] = 0.0
        self.compute_from_ll(self.ll)
225411
def remove_priors(self):
        """"""

        for src in self.roi.sources:

            for par in self.like[src.name].funcs["Spectrum"].params.values():
                par.removePrior()
1138454
def distortImage(self, image):
        '''
        
        '''
        image = imread(image)
        (imgHeight, imgWidth) = image.shape[:2]
        mapx, mapy = self.getDistortRectifyMap(imgWidth, imgHeight)
        return cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
                         borderValue=(0, 0, 0))
1067324
def smooth_gaussian(image, sigma=1):
    
    return scipy.ndimage.filters.gaussian_filter(image, sigma=sigma, mode="nearest")