Stretch linearly the contrast of the current image.

        Use *cutoffs* for left and right trimming.
430601
def stretch_linear(self, cutoffs=(0.005, 0.005)):
        
        logger.debug("Perform a linear contrast stretch.")

        logger.debug("Calculate the histogram quantiles: ")
        logger.debug("Left and right quantiles: " +
                     str(cutoffs[0]) + " " + str(cutoffs[1]))

        cutoff_type = np.float64
        # numpy percentile (which quantile calls) returns 64-bit floats
        # unless the value is a higher order float
        if np.issubdtype(self.data.dtype, np.floating) and \
                np.dtype(self.data.dtype).itemsize > 8:
            cutoff_type = self.data.dtype
        left, right = dask.delayed(self._compute_quantile, nout=2)(self.data.data, self.data.dims, cutoffs)
        left_data = da.from_delayed(left,
                                    shape=(self.data.sizes['bands'],),
                                    dtype=cutoff_type)
        left = xr.DataArray(left_data, dims=('bands',),
                            coords={'bands': self.data['bands']})
        right_data = da.from_delayed(right,
                                     shape=(self.data.sizes['bands'],),
                                     dtype=cutoff_type)
        right = xr.DataArray(right_data, dims=('bands',),
                             coords={'bands': self.data['bands']})

        self.crude_stretch(left, right)
95024
def _linear_selection(self, non_empty_slices, num_slices):
        """"""

        num_non_empty = len(non_empty_slices)

        # # trying to skip 5% slices at the tails (bottom clipping at 0)
        # skip_count = max(0, np.around(num_non_empty * 0.05).astype('int16'))
        # # only when possible
        # if skip_count > 0 and (num_non_empty - 2 * skip_count > num_slices):
        #     non_empty_slices = non_empty_slices[skip_count: -skip_count]
        #     num_non_empty = len(non_empty_slices)

        sampled_indices = np.linspace(0, num_non_empty, num=min(num_non_empty, num_slices),
                                      endpoint=False)
        slices_in_dim = non_empty_slices[np.around(sampled_indices).astype('int64')]

        return slices_in_dim
665773
def trim_rounded(src, trim, radius)
      trim_cc = Cairo::Context.new(Cairo::ImageSurface.new(@width - 2.0 * trim, @height - 2.0 * trim))
      trim_cc.rounded_rectangle(0, 0, trim_cc.target.width, trim_cc.target.height, radius, radius)
      trim_cc.set_source(src, -1 * trim, -1 * trim)
      trim_cc.clip
      trim_cc.paint
      return trim_cc.target
    end
595206
def crop(im, r, c, sz_h, sz_w):
    '''
    
    '''
    return im[r:r+sz_h, c:c+sz_w]
937143
protected Planar<GrayF32> preprocess(Planar<GrayF32> image) {
		super.preprocess(image);

		// image net is BGR color order
		imageBgr.bands[0] = imageRgb.bands[2];
		imageBgr.bands[1] = imageRgb.bands[1];
		imageBgr.bands[2] = imageRgb.bands[0];

		// image needs to be between 0 and 1
		GPixelMath.divide(imageBgr,255,imageBgr);

		// Normalize the image's statistics
		for (int band = 0; band < 3; band++) {
			DataManipulationOps.normalize(imageBgr.getBand(band),mean[band],stdev[band]);
		}

		return imageBgr;
	}
905691
def fixpix(data, mask, kind='linear'):
    """"""
    if data.shape != mask.shape:
        raise ValueError

    if not numpy.any(mask):
        return data

    x = numpy.arange(0, data.shape[0])
    for row, mrow in zip(data, mask):
        if numpy.any(mrow):  # Interpolate if there's some pixel missing
            valid = (mrow == numpy.False_)
            invalid = (mrow == numpy.True_)
            itp = interp1d(x[valid], row[valid], kind=kind, copy=False)
            row[invalid] = itp(x[invalid]).astype(row.dtype)
    return data
1337126
def stretch_cv(x,sr,sc,interpolation=cv2.INTER_AREA):
    
    if sr==0 and sc==0: return x
    r,c,*_ = x.shape
    x = cv2.resize(x, None, fx=sr+1, fy=sc+1, interpolation=interpolation)
    nr,nc,*_ = x.shape
    cr = (nr-r)//2; cc = (nc-c)//2
    return x[cr:r+cr, cc:c+cc]
561803
def crop_3dimage(img, beg_coords, end_coords):
    """"""

    cropped_img = img[
                  beg_coords[0]:end_coords[0],
                  beg_coords[1]:end_coords[1],
                  beg_coords[2]:end_coords[2]
                  ]

    return cropped_img
94354
def distort(self, img, rotX=0, rotY=0, quad=None):
        '''
        

        '''
        self.img = imread(img)
        # fit old image to self.quad:
        corr = self.correct(self.img)

        s = self.img.shape
        if quad is None:
            wquad = (self.quad - self.quad.mean(axis=0)).astype(float)

            win_width = s[1]
            win_height = s[0]
            # project quad:
            for n, q in enumerate(wquad):
                p = Point3D(q[0], q[1], 0).rotateX(-rotX).rotateY(-rotY)
                p = p.project(win_width, win_height, s[1], s[1])
                wquad[n] = (p.x, p.y)
            wquad = sortCorners(wquad)
            # scale result so that longest side of quad and wquad are equal
            w = wquad[:, 0].max() - wquad[:, 0].min()
            h = wquad[:, 1].max() - wquad[:, 1].min()
            scale = min(s[1] / w, s[0] / h)
            # scale:
            wquad = (wquad * scale).astype(int)
        else:
            wquad = sortCorners(quad)
        wquad -= wquad.min(axis=0)

        lx = corr.shape[1]
        ly = corr.shape[0]

        objP = np.array([
            [0, 0],
            [lx, 0],
            [lx, ly],
            [0, ly],
        ], dtype=np.float32)

        homography = cv2.getPerspectiveTransform(
            wquad.astype(np.float32), objP)
        # distort corr:
        w = wquad[:, 0].max() - wquad[:, 0].min()
        h = wquad[:, 1].max() - wquad[:, 1].min()
        #(int(w),int(h))
        dist = cv2.warpPerspective(corr, homography, (int(w), int(h)),
                                   flags=cv2.INTER_CUBIC | cv2.WARP_INVERSE_MAP)

        # move middle of dist to middle of the old quad:
        bg = np.zeros(shape=s)
        rmn = (bg.shape[0] / 2, bg.shape[1] / 2)

        ss = dist.shape
        mn = (ss[0] / 2, ss[1] / 2)  # wquad.mean(axis=0)
        ref = (int(rmn[0] - mn[0]), int(rmn[1] - mn[1]))

        bg[ref[0]:ss[0] + ref[0], ref[1]:ss[1] + ref[1]] = dist

        # finally move quad into right position:
        self.quad = wquad
        self.quad += (ref[1], ref[0])
        self.img = bg
        self._homography = None
        self._poseFromQuad()

        if self.opts['do_correctIntensity']:
            tf = self.tiltFactor()
            if self.img.ndim == 3:
                for col in range(self.img.shape[2]):
                    self.img[..., col] *= tf
            else:
                #                 tf = np.tile(tf, (1,1,self.img.shape[2]))
                self.img = self.img * tf

        return self.img
341717
def crop! params
      decode_all_scanlines

      x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width]
      raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 }

      # adjust crop sizes if they greater than image sizes
      h = self.height-y if (y+h) > self.height
      w = self.width-x if (x+w) > self.width
      raise ArgumentError, "negative params not allowed (p2)" if [x,y,h,w].any?{ |x| x < 0 }

      # delete excess scanlines at tail
      scanlines[(y+h)..-1] = [] if (y+h) < scanlines.size

      # delete excess scanlines at head
      scanlines[0,y] = [] if y > 0

      # crop remaining scanlines
      scanlines.each{ |l| l.crop!(x,w) }

      # modify header
      hdr.height, hdr.width = h, w

      # return self
      self
    end
21306
def shift_to_coords(self, pix, fill_value=np.nan):
        """"""

        pix_offset = self.get_offsets(pix)
        dpix = np.zeros(len(self.shape) - 1)
        for i in range(len(self.shape) - 1):
            x = self.rebin * (pix[i] - pix_offset[i + 1]
                              ) + (self.rebin - 1.0) / 2.
            dpix[i] = x - self._pix_ref[i]

        pos = [pix_offset[i] + self.shape[i] // 2
               for i in range(self.data.ndim)]
        s0, s1 = utils.overlap_slices(self.shape_out, self.shape, pos)

        k = np.zeros(self.data.shape)
        for i in range(k.shape[0]):
            k[i] = shift(self._data_spline[i], dpix, cval=np.nan,
                         order=2, prefilter=False)

        for i in range(1, len(self.shape)):
            k = utils.sum_bins(k, i, self.rebin)

        k0 = np.ones(self.shape_out) * fill_value

        if k[s1].size == 0 or k0[s0].size == 0:
            return k0
        k0[s0] = k[s1]
        return k0
879903
function(options) {
        var params = [],
            opts = options || {},
            transform = 'contrast';

        if (opts.sharpen) {
            params.push('sharpen=' + opts.sharpen);
        }

        if (params.length) {
            transform += ':' + params.join(',');
        }

        return this.append(transform);
    }
651151
function (x, y, tickLength, tickWidth, horiz, renderer) {
		return renderer.crispLine([
				M,
				x,
				y,
				L,
				x + (horiz ? 0 : -tickLength),
				y + (horiz ? tickLength : 0)
			], tickWidth);
	}
341422
def rounded(self, image, geometry, options):
        
        r = options['rounded']
        if not r:
            return image
        return self._rounded(image, int(r))
456765
def blur(self, image, geometry, options):
        
        if options.get('blur'):
            return self._blur(image, int(options.get('blur')))
        return image
226500
private void blur(BufferedImage image) {
		float[] matrix = GAUSSIAN_BLUR_KERNELS[blurKernelSize - 1];
		Kernel gaussianBlur1 = new Kernel(matrix.length, 1, matrix);
		Kernel gaussianBlur2 = new Kernel(1, matrix.length, matrix);
		RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
		ConvolveOp gaussianOp1 = new ConvolveOp(gaussianBlur1, ConvolveOp.EDGE_NO_OP, hints);
		ConvolveOp gaussianOp2 = new ConvolveOp(gaussianBlur2, ConvolveOp.EDGE_NO_OP, hints);
		BufferedImage scratchImage = EffectUtil.getScratchImage();
		for (int i = 0; i < blurPasses; i++) {
			gaussianOp1.filter(image, scratchImage);
			gaussianOp2.filter(scratchImage, image);
		}
	}
935170
function (offset, bounds) {
		if (!bounds) { return offset; }

		var viewBounds = this.getPixelBounds(),
		    newBounds = new L.Bounds(viewBounds.min.add(offset), viewBounds.max.add(offset));

		return offset.add(this._getBoundsOffset(newBounds, bounds));
	}