When part of the region is outside the image G and E need to be recomputed
196589
protected int computeGandE_border(KltFeature feature, float cx, float cy) {

		computeSubImageBounds(feature, cx, cy);

		ImageMiscOps.fill(currDesc, Float.NaN);
		currDesc.subimage(dstX0, dstY0, dstX1, dstY1, subimage);
		interpInput.setImage(image);
		interpInput.region(srcX0, srcY0, subimage);

		int total = 0;

		Gxx = 0; Gyy = 0; Gxy = 0;
		Ex = 0; Ey = 0;

		for( int i = 0; i < lengthFeature; i++ ) {
			float template = feature.desc.data[i];
			float current = currDesc.data[i];

			// if the description was outside of the image here skip it
			if( Float.isNaN(template) || Float.isNaN(current))
				continue;

			// count total number of points inbounds
			total++;

			float dX = feature.derivX.data[i];
			float dY = feature.derivY.data[i];

			// compute the difference between the previous and the current image
			float d = template - current;

			Ex += d * dX;
			Ey += d * dY;

			Gxx += dX * dX;
			Gyy += dY * dY;
			Gxy += dX * dY;
		}

		return total;
	}
785699
def tenengrad(img, ksize=3):
    '''''''
    Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
    Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
    FM = Gx*Gx + Gy*Gy
    mn = cv2.mean(FM)[0]
    if np.isnan(mn):
        return np.nanmean(FM)
    return mn
867981
def crop_to_seg_extents(img, seg, padding):
    """"""

    beg_coords, end_coords = crop_coords(seg, padding)

    img = crop_3dimage(img, beg_coords, end_coords)
    seg = crop_3dimage(seg, beg_coords, end_coords)

    return img, seg
469609
def post_process(self):
        
        self.image.putdata(self.pixels)
        self.image = self.image.transpose(Image.ROTATE_90)
724656
protected void computeHistogramBorder(T image, RectangleRotate_F32 region) {
		for( int i = 0; i < samplePts.size(); i++ ) {
			Point2D_F32 p = samplePts.get(i);

			squareToImageSample(p.x, p.y, region);

			// make sure its inside the image
			if( !BoofMiscOps.checkInside(image, imageX, imageY)) {
				sampleHistIndex[ i ] = -1;
			} else {
				// use the slower interpolation which can handle the border
				interpolate.get(imageX, imageY, value);

				int indexHistogram = computeHistogramBin(value);

				sampleHistIndex[ i ] = indexHistogram;
				histogram[indexHistogram] += weights[i];
			}
		}
	}
785307
private RegionData findUsableRegion(int width, int height) {
        final int imageWidth = image.getWidth();
        final int imageHeight = image.getHeight();
        for (int y = 0; y < imageHeight - height; y++) {
            for (int x = 0; x < imageWidth - width; x++) {
                final RegionData data = new RegionData(x, y, width, height);
                if (!intersectsOtherTexture(data)) {
                    return data;
                }
            }
        }
        return null;
    }
247165
def ReduceOpacity(im, opacity):
    
    assert opacity >= 0 and opacity <= 1
    if isalpha(im):
        im = im.copy()
    else:
        im = im.convert('RGBA')

    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)
    return im
195475
private void createAreas(final BufferedImage IMAGE) {
        final double ORIGIN_CORRECTION;
        final double ANGLE_STEP;

        switch (getOrientation()) {
            case NORTH:
                ORIGIN_CORRECTION = 135;
                break;
            case EAST:
                ORIGIN_CORRECTION = 135;
                break;
            case SOUTH:
                ORIGIN_CORRECTION = 135;
                break;
            case WEST:
                ORIGIN_CORRECTION = 225;
                break;
            default:
                ORIGIN_CORRECTION = 135;
                break;
        }

        if (bImage != null) {
            if (!isLogScale()) {
                ANGLE_STEP = Math.toDegrees(getModel().getAngleRange()) / (getMaxValue() - getMinValue());
            } else {
                ANGLE_STEP = Math.toDegrees(getModel().getAngleRange()) / UTIL.logOfBase(BASE, getMaxValue() - getMinValue());
            }

            if (bImage != null && !getAreas().isEmpty()) {
                final double OUTER_RADIUS = bImage.getWidth() * 0.44f;
                final double RADIUS;
                if (isSectionsVisible()) {
                    RADIUS = isExpandedSectionsEnabled() ? OUTER_RADIUS - bImage.getWidth() * 0.12f : OUTER_RADIUS - bImage.getWidth() * 0.04f;
                } else {
                    RADIUS = OUTER_RADIUS;
                }
                final double FREE_AREA = bImage.getWidth() / 2.0 - RADIUS;
                final Rectangle2D AREA_FRAME = new Rectangle2D.Double(bImage.getMinX() + FREE_AREA, bImage.getMinY() + FREE_AREA, 2 * RADIUS, 2 * RADIUS);

                for (Section area : getAreas()) {
                    if (!isLogScale()) {
                        area.setFilledArea(new Arc2D.Double(AREA_FRAME, ORIGIN_CORRECTION - (area.getStart() * ANGLE_STEP) + (getMinValue() * ANGLE_STEP), -(area.getStop() - area.getStart()) * ANGLE_STEP, Arc2D.PIE));
                    } else {
                        area.setFilledArea(new Arc2D.Double(AREA_FRAME, ORIGIN_CORRECTION - (UTIL.logOfBase(BASE, area.getStart()) * ANGLE_STEP) + (UTIL.logOfBase(BASE, getMinValue()) * ANGLE_STEP), -UTIL.logOfBase(BASE, area.getStop() - area.getStart()) * ANGLE_STEP, Arc2D.PIE));
                    }
                }
            }
            // Draw the areas
            if (isAreasVisible() && IMAGE != null) {
                final Graphics2D G2 = IMAGE.createGraphics();
                G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                switch (getOrientation()) {
                    case EAST:
                        break;
                    case SOUTH:
                        break;
                    case WEST:
                        G2.translate(CENTER.getX() / 2.2, 0);
                        break;
                    case NORTH:

                    default:
                        G2.translate(0, CENTER.getY() / 2.2);
                        break;
                }

                for (Section area : getAreas()) {
                    G2.setColor(isTransparentAreasEnabled() ? area.getTransparentColor() : area.getColor());
                    G2.fill(area.getFilledArea());
                }
                G2.dispose();
            }
        }
    }
440195
def rgb2gray(img):
    """"""
    T = np.linalg.inv(np.array([
        [1.0,  0.956,  0.621],
        [1.0, -0.272, -0.647],
        [1.0, -1.106,  1.703],
    ]))
    r_c, g_c, b_c = T[0]
    r, g, b = np.rollaxis(as_float_image(img), axis=-1)
    return r_c * r + g_c * g + b_c * b
1078742
function RoundImage(i, r, iw, ih, s) {
  var cv, c, r1 = parseFloat(r), l = max(iw, ih);
  cv = NewCanvas(iw, ih);
  if(!cv)
    return null;
  if(r.indexOf('%') > 0)
    r1 = l * r1 / 100;
  else
    r1 = r1 * s;
  c = cv.getContext('2d');
  c.globalCompositeOperation = 'source-over';
  c.fillStyle = '#fff';
  if(r1 >= l/2) {
    r1 = min(iw,ih) / 2;
    c.beginPath();
    c.moveTo(iw/2,ih/2);
    c.arc(iw/2,ih/2,r1,0,2*Math.PI,false);
    c.fill();
    c.closePath();
  } else {
    r1 = min(iw/2,ih/2,r1);
    RRect(c, 0, 0, iw, ih, r1, true);
    c.fill();
  }
  c.globalCompositeOperation = 'source-in';
  c.drawImage(i, 0, 0, iw, ih);
  return cv;
}
497168
function imagetransfer($src_im, $dst_im) {
        if (is_resource($dst_im)) imagedestroy($dst_im);
        $dst_im = & $src_im;
        return $dst_im;
    }
793873
def fixpix2(data, mask, iterations=3, out=None):
    
    out = out if out is not None else data.copy()

    # A binary mask, regions are ones
    binry = mask != 0

    # Label regions in the binary mask
    lblarr, labl = ndimage.label(binry)

    # Structure for dilation is 8-way
    stct = ndimage.generate_binary_structure(2, 2)
    # Pixels in the background
    back = lblarr == 0
    # For each object
    for idx in range(1, labl + 1):
        # Pixels of the object
        segm = lblarr == idx
        # Pixels of the object or the background
        # dilation will only touch these pixels
        dilmask = numpy.logical_or(back, segm)
        # Dilation 3 times
        more = ndimage.binary_dilation(segm, stct,
                                       iterations=iterations,
                                       mask=dilmask)
        # Border pixels
        # Pixels in the border around the object are
        # more and (not segm)
        border = numpy.logical_and(more, numpy.logical_not(segm))
        # Pixels in the border
        xi, yi = border.nonzero()
        # Bilinear leastsq calculator
        calc = FitOne(xi, yi, out[xi, yi])
        # Pixels in the region
        xi, yi = segm.nonzero()
        # Value is obtained from the fit
        out[segm] = calc(xi, yi)

    return out
832068
public static void horizontal(Kernel1D_S32 kernel, InterleavedU16 src, InterleavedI16 dst ) {
		InputSanityCheck.checkSameShapeB(src, dst);

		boolean processed = BOverrideConvolveImageNormalized.invokeNativeHorizontal(kernel,src,dst);
		
		if( !processed ) {
			if( kernel.width >= src.width ) {
				ConvolveNormalizedNaive_IL.horizontal(kernel, src, dst);
			} else {
				ConvolveImageNoBorder.horizontal(kernel, src, dst, kernel.computeSum());
				ConvolveNormalized_JustBorder_IL.horizontal(kernel, src, dst);
			}
		}
	}
1020877
private void scaleToOutputResolution(Image image) {

        float factor = m_sharedContext.getDotsPerPixel();
        if (factor != 1.0f) {
            image.scaleAbsolute(image.getPlainWidth() * factor, image.getPlainHeight() * factor);
        }
    }
482363
function convertToFalseColorImage (element, colormap) {
  const enabledElement = getEnabledElement(element);


  return convertImageToFalseColorImage(enabledElement.image, colormap);
}
890443
function recolorImageWithCanvasContext(context, img, colorFunc) {
  if (!defined(context)) {
    throw new DeveloperError("No context for image recoloring.");
  }

  // Copy the image contents to the canvas
  context.clearRect(0, 0, context.canvas.width, context.canvas.height);
  context.drawImage(img, 0, 0);
  var image = context.getImageData(
    0,
    0,
    context.canvas.width,
    context.canvas.height
  );
  image = ImageryProviderHooks.recolorImage(image, colorFunc);
  return image;
}
1020755
def correctGrid(self, img, grid):
        '''
        
        '''

        self.img = imread(img)
        h = self.homography  # TODO: cleanup only needed to get newBorder attr.

        if self.opts['do_correctIntensity']:
            self.img = self.img / self._getTiltFactor(self.img.shape)

        s0, s1 = grid.shape[:2]
        n0, n1 = s0 - 1, s1 - 1

        snew = self._newBorders
        b = self.opts['border']

        sx, sy = (snew[0] - 2 * b) // n0, (snew[1] - 2 * b) // n1

        out = np.empty(snew[::-1], dtype=self.img.dtype)

        def warp(ix, iy, objP, outcut):
            shape = outcut.shape[::-1]
            quad = grid[ix:ix + 2,
                        iy:iy + 2].reshape(4, 2)[np.array([0, 2, 3, 1])]
            hcell = cv2.getPerspectiveTransform(
                quad.astype(np.float32), objP)
            cv2.warpPerspective(self.img, hcell, shape, outcut,
                                flags=cv2.INTER_LANCZOS4,
                                **self.opts['cv2_opts'])
            return quad

        objP = np.array([[0, 0],
                         [sx, 0],
                         [sx, sy],
                         [0, sy]], dtype=np.float32)
        # INNER CELLS
        for ix in range(1, n0 - 1):
            for iy in range(1, n1 - 1):
                sub = out[iy * sy + b: (iy + 1) * sy + b,
                          ix * sx + b: (ix + 1) * sx + b]
#                 warp(ix, iy, objP, sub)

                shape = sub.shape[::-1]
                quad = grid[ix:ix + 2,
                            iy:iy + 2].reshape(4, 2)[np.array([0, 2, 3, 1])]
#                 print(quad, objP)

                hcell = cv2.getPerspectiveTransform(
                    quad.astype(np.float32), objP)
                cv2.warpPerspective(self.img, hcell, shape, sub,
                                    flags=cv2.INTER_LANCZOS4,
                                    **self.opts['cv2_opts'])

#         return out
        # TOP CELLS
        objP[:, 1] += b
        for ix in range(1, n0 - 1):
            warp(ix, 0, objP, out[: sy + b,
                                  ix * sx + b: (ix + 1) * sx + b])
        # BOTTOM CELLS
        objP[:, 1] -= b
        for ix in range(1, n0 - 1):
            iy = (n1 - 1)
            y = iy * sy + b
            x = ix * sx + b
            warp(ix, iy, objP, out[y: y + sy + b, x: x + sx])
        # LEFT CELLS
        objP[:, 0] += b
        for iy in range(1, n1 - 1):
            y = iy * sy + b
            warp(0, iy, objP, out[y: y + sy, : sx + b])
        # RIGHT CELLS
        objP[:, 0] -= b
        ix = (n0 - 1)
        x = ix * sx + b
        for iy in range(1, n1 - 1):
            y = iy * sy + b
            warp(ix, iy, objP, out[y: y + sy, x: x + sx + b])
        # BOTTOM RIGHT CORNER
        warp(n0 - 1, n1 - 1, objP, out[-sy - b - 1:, x: x + sx + b])
#         #TOP LEFT CORNER
        objP += (b, b)
        warp(0, 0, objP, out[0: sy + b, 0: sx + b])
        # TOP RIGHT CORNER
        objP[:, 0] -= b
#         x = (n0-1)*sx+b
        warp(n0 - 1, 0, objP, out[: sy + b, x: x + sx + b])
#         #BOTTOM LEFT CORNER
        objP += (b, -b)
        warp(0, n1 - 1, objP, out[-sy - b - 1:, : sx + b])
        return out