Helper function to calculate location of image pixel in (l,m) coords.
    Assumes peak pixel, but input can be provided in pixel units.
    minmax defines whether to look for image maximum or minimum.
351397
def calc_lm(d, im=[], pix=(), minmax='max'):
    

    if len(pix) == 0:  # default is to get pixel from image
        if minmax == 'max':
            peakl, peakm = n.where(im == im.max())
        elif minmax == 'min':
            peakl, peakm = n.where(im == im.min())
        peakl = peakl[0]; peakm = peakm[0]
    elif len(pix) == 2:   # can also specify
        peakl, peakm = pix

    if len(im):
        npixx, npixy = im.shape
    else:
        npixx = d['npixx']
        npixy = d['npixy']

    l1 = (npixx/2. - peakl)/(npixx*d['uvres'])
    m1 = (npixy/2. - peakm)/(npixy*d['uvres'])

    return l1, m1
790645
def _findObject(self, img):
        '''
        
        '''
        from imgProcessor.imgSignal import signalMinimum
        # img is scaled already
        i = img > signalMinimum(img)  # img.max()/2.5
        # filter noise, single-time-effects etc. from mask:
        i = minimum_filter(i, 4)
        return boundingBox(i)
430886
private void computePixelFeatures() {
		for (int y = 0; y < derivX.height; y++) {
			int pixelIndex = y*derivX.width;
			int endIndex = pixelIndex+derivX.width;
			for (; pixelIndex < endIndex; pixelIndex++ ) {
				float dx = derivX.data[pixelIndex];
				float dy = derivY.data[pixelIndex];

				// angle from 0 to pi radians
				orientation.data[pixelIndex] = UtilAngle.atanSafe(dy,dx) + GrlConstants.F_PId2;
				// gradient magnitude
				magnitude.data[pixelIndex] = Math.sqrt(dx*dx + dy*dy);
			}
		}
	}
1101207
function fillFinders(matrix) {
    var N = matrix.length;
    for (var i = -3; i <= 3; i++) {
        for (var j = -3; j <= 3; j++) {
            var max = Math.max(i, j);
            var min = Math.min(i, j);
            var pixel = (max == 2 && min >= -2) || (min == -2 && max <= 2) ? 0x80 : 0x81;
            matrix[3 + i][3 + j] = pixel;
            matrix[3 + i][N - 4 + j] = pixel;
            matrix[N - 4 + i][3 + j] = pixel;
        }
    }
    for (var i = 0; i < 8; i++) {
        matrix[7][i] = matrix[i][7] =
        matrix[7][N - i - 1] = matrix[i][N - 8] =
        matrix[N - 8][i] = matrix[N - 1 - i][7] = 0x80;
    }
}
126246
public static void boundImage( GrayF32 img , float min , float max ) {
		ImplPixelMath.boundImage(img,min,max);
	}
353891
def get_background_threshold(image, mask = None):
    """"""
    cropped_image = np.array(image.flat) if mask is None else image[mask]
    if np.product(cropped_image.shape)==0:
        return 0
    img_min = np.min(cropped_image)
    img_max = np.max(cropped_image)
    if img_min == img_max:
        return cropped_image[0]
    
    # Only do the histogram between values a bit removed from saturation
    robust_min = 0.02 * (img_max - img_min) + img_min
    robust_max = 0.98 * (img_max - img_min) + img_min
    nbins = 256
    cropped_image = cropped_image[np.logical_and(cropped_image > robust_min,
                                                 cropped_image < robust_max)]
    if len(cropped_image) == 0:
        return robust_min
    
    h = scipy.ndimage.histogram(cropped_image, robust_min, robust_max, nbins)
    index = np.argmax(h)
    cutoff = float(index) / float(nbins-1)
    #
    # If we have a low (or almost no) background, the cutoff will be
    # zero since the background falls into the lowest bin. We want to
    # offset by the robust cutoff factor of .02. We rescale by 1.04
    # to account for the 0.02 at the top and bottom.
    #
    cutoff = (cutoff + 0.02) / 1.04
    return img_min + cutoff * 2 * (img_max - img_min)
88126
def cutout_source(x_pos, y_pos, image, kernelsize, shift=True):
    
    if kernelsize % 2 == 0:
        raise ValueError("even pixel number kernel size not supported!")
    x_int = int(round(x_pos))
    y_int = int(round(y_pos))
    n = len(image)
    d = (kernelsize - 1)/2
    x_max = int(np.minimum(x_int + d + 1, n))
    x_min = int(np.maximum(x_int - d, 0))
    y_max = int(np.minimum(y_int + d + 1, n))
    y_min = int(np.maximum(y_int - d, 0))
    image_cut = copy.deepcopy(image[y_min:y_max, x_min:x_max])
    shift_x = x_int - x_pos
    shift_y = y_int - y_pos
    if shift is True:
        kernel_shift = de_shift_kernel(image_cut, shift_x, shift_y, iterations=50)
    else:
        kernel_shift = image_cut
    kernel_final = np.zeros((kernelsize, kernelsize))

    k_l2_x = int((kernelsize - 1) / 2)
    k_l2_y = int((kernelsize - 1) / 2)

    xk_min = np.maximum(0, -x_int + k_l2_x)
    yk_min = np.maximum(0, -y_int + k_l2_y)
    xk_max = np.minimum(kernelsize, -x_int + k_l2_x + n)
    yk_max = np.minimum(kernelsize, -y_int + k_l2_y + n)

    kernel_final[yk_min:yk_max, xk_min:xk_max] = kernel_shift
    return kernel_final
684192
def _get_image_size(self, maxcharno, maxlineno):
        
        return (self._get_char_x(maxcharno) + self.image_pad,
                self._get_line_y(maxlineno + 0) + self.image_pad)
316177
def coordinates_inside_data(
        self,
        x,
        y
        ):

        

        return (self.min_x <= x < self.max_x) and (self.min_y <= y < self.max_y)
995929
public static void boundImage( GrayU16 img , int min , int max ) {
		ImplPixelMath.boundImage(img,min,max);
	}
1330641
public void process(GrayF32 intensityImage,
						@Nullable QueueCorner candidatesMin, @Nullable QueueCorner candidatesMax,
						QueueCorner foundMin , QueueCorner foundMax ) {

		this.input = intensityImage;

		// pixels indexes larger than these should not be examined
		endBorderX = intensityImage.width-ignoreBorder;
		endBorderY = intensityImage.height-ignoreBorder;

		search.initialize(intensityImage);

		if( candidatesMin != null ) {
			foundMin.reset();
			examineMinimum(intensityImage, candidatesMin, foundMin);
		}
		if( candidatesMax != null ) {
			foundMax.reset();
			examineMaximum(intensityImage, candidatesMax, foundMax);
		}

	}
1115165
def find_local_maxima(self, input_grid):
        
        pixels, q_data = self.quantize(input_grid)
        centers = OrderedDict()
        for p in pixels.keys():
            centers[p] = []
        marked = np.ones(q_data.shape, dtype=int) * self.UNMARKED
        MIN_INFL = int(np.round(1 + 0.5 * np.sqrt(self.max_size)))
        MAX_INFL = 2 * MIN_INFL
        marked_so_far = []
        # Find the maxima. These are high-values with enough clearance
        # around them.
        # Work from high to low bins. The pixels in the highest bin mark their
        # neighborhoods first. If you did it from low to high the lowest maxima
        # would mark their neighborhoods first and interfere with the identification of higher maxima.
        for b in sorted(pixels.keys(),reverse=True):
            # Square starts large with high intensity bins and gets smaller with low intensity bins.
            infl_dist = MIN_INFL + int(np.round(float(b) / self.max_bin * (MAX_INFL - MIN_INFL)))
            for p in pixels[b]:
                if marked[p] == self.UNMARKED:
                    ok = False
                    del marked_so_far[:]
                    # Temporarily mark unmarked points in square around point (keep track of them in list marked_so_far).
                    # If none of the points in square were marked already from a higher intensity center, 
                    # this counts as a new center and ok=True and points will remain marked.
                    # Otherwise ok=False and marked points that were previously unmarked will be unmarked.
                    for (i, j), v in np.ndenumerate(marked[p[0] - infl_dist:p[0] + infl_dist + 1,
                                                    p[1] - infl_dist:p[1]+ infl_dist + 1]):
                        if v == self.UNMARKED:
                            ok = True
                            marked[i - infl_dist + p[0],j - infl_dist + p[1]] = b
                           
                            marked_so_far.append((i - infl_dist + p[0],j - infl_dist + p[1]))
                        else:
                            # neighborhood already taken
                            ok = False
                            break
                    # ok if point and surrounding square were not marked already.
                    if ok:
                        # highest point in its neighborhood
                        centers[b].append(p)
                    else:
                        for m in marked_so_far:
                            marked[m] = self.UNMARKED
        # Erase marks and start over. You have a list of centers now.
        marked[:, :] = self.UNMARKED
        deferred_from_last = []
        deferred_to_next = []
        # delta (int): maximum number of increments the cluster is allowed to range over. Larger d results in clusters over larger scales.
        for delta in range(0, self.delta + 1):
            # Work from high to low bins.
            for b in sorted(centers.keys(), reverse=True):
                bin_lower = b - delta
                deferred_from_last[:] = deferred_to_next[:]
                del deferred_to_next[:]
                foothills = []
                n_centers = len(centers[b])
                tot_centers = n_centers + len(deferred_from_last)
                for i in range(tot_centers):
                    # done this way to minimize memory overhead of maintaining two lists
                    if i < n_centers:
                        center = centers[b][i]
                    else:
                        center = deferred_from_last[i - n_centers]
                    if bin_lower < 0:
                        bin_lower = 0
                    if marked[center] == self.UNMARKED:
                        captured = self.set_maximum(q_data, marked, center, bin_lower, foothills)
                        if not captured:
                            # decrement to lower value to see if it'll get big enough
                            deferred_to_next.append(center)
                        else:
                            pass
                # this is the last one for this bin
                self.remove_foothills(q_data, marked, b, bin_lower, centers, foothills)
            del deferred_from_last[:]
            del deferred_to_next[:]
        return marked
710491
def _best_res_pixels(self):
        
        factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order)
        pix_l = []
        for iv in self._interval_set._intervals:
            for val in range(iv[0] >> factor, iv[1] >> factor):
                pix_l.append(val)

        return np.asarray(pix_l)
1305226
protected static boolean checkMax(ImageBorder_F32 inten, float bestScore, int c_x, int c_y) {
		for( int y = c_y -1; y <= c_y+1; y++ ) {
			for( int x = c_x-1; x <= c_x+1; x++ ) {
				if( inten.get(x,y) >= bestScore ) {
					return false;
				}
			}
		}
		return true;
	}
921277
function(min, max) {
    return function limitVisibleY(params) {

      // Do nothing for a null viewport.
      if (params.width <= 0 || params.height <= 0) {
        return params;
      }

      // Calculate the X to Y conversion factor.
      var viewportAspectRatio = params.width / params.height;
      var factor = viewportAspectRatio / params.mediaAspectRatio;

      // Calculate the zoom value that makes the specified range fully visible.
      var maxZoom = (max - min) * factor;

      // Clamp zoom to the maximum value.
      if (params.zoom > maxZoom) {
        params.zoom = maxZoom;
      }

      // Bound Y such that the image is visible up to the range edges.
      var minY = min + 0.5 * params.zoom / factor;
      var maxY = max - 0.5 * params.zoom / factor;
      params.y = clamp(params.y, minY, maxY);

      return params;
    };
  }
163014
protected void findLocalScaleSpaceMax(PyramidFloat<T> ss, int layerID) {
		List<Point2D_I16> candidates = maximums;

		float scale0 = (float) ss.scale[layerID - 1];
		float scale1 = (float) ss.scale[layerID];
		float scale2 = (float) ss.scale[layerID + 1];

		float sigma0 = (float) ss.getSigma(layerID - 1);
		float sigma1 = (float) ss.getSigma(layerID);
		float sigma2 = (float) ss.getSigma(layerID + 1);

		// For laplacian its t^(2*gamma) where gamma = 3/4
		float ss0 = (float) (Math.pow(sigma0, 2.0 * 0.75)/scale0);// Is this divide by scale correct?
		float ss1 = (float) (Math.pow(sigma1, 2.0 * 0.75)/scale1);
		float ss2 = (float) (Math.pow(sigma2, 2.0 * 0.75)/scale2);

		for (Point2D_I16 c : candidates) {

			GrayF32 intensity = detector.getIntensity();

			float target = intensity.unsafe_get(c.x,c.y);
			float fx,fy;
			{
				float x0 = intensity.unsafe_get(c.x - 1, c.y);
				float x2 = intensity.unsafe_get(c.x + 1, c.y);
				float y0 = intensity.unsafe_get(c.x, c.y - 1);
				float y2 = intensity.unsafe_get(c.x, c.y + 1);

				fx = c.x + polyPeak(x0, target, x2);
				fy = c.y + polyPeak(y0, target, y2);
			}
//			fx=c.x;fy=c.y;

			sparseLaplace.setImage(ss.getLayer(layerID));
			float val = ss1 * (float) sparseLaplace.compute(c.x,c.y);
			// search for local maximum or local minimum
			float adj = Math.signum(val);
			val *= adj;


			// find pixel location in each image's local coordinate
			int x0 = (int) (fx * scale1 / scale0 + 0.5);
			int y0 = (int) (fy * scale1 / scale0 + 0.5);

			int x2 = (int) (fx * scale1 / scale2 + 0.5);
			int y2 = (int) (fy * scale1 / scale2 + 0.5);

			if (checkMax(ss.getLayer(layerID - 1), adj*ss0,val, x0, y0) && checkMax(ss.getLayer(layerID + 1), adj*ss2,val, x2, y2)) {
				sparseLaplace.setImage(ss.getLayer(layerID-1));
				float s0 = ss0 * (float) sparseLaplace.compute(x0,y0)*adj;
				sparseLaplace.setImage(ss.getLayer(layerID+1));
				float s2 = ss2 * (float) sparseLaplace.compute(x2,y2)*adj;

				double adjSigma;
				double sigmaInterp = polyPeak(s0, val, s2); // scaled from -1 to 1
				if( sigmaInterp < 0 ) {
					adjSigma = sigma0*(-sigmaInterp) + (1+sigmaInterp)*sigma1;
				} else {
					adjSigma = sigma2*sigmaInterp + (1-sigmaInterp)*sigma1;
				}

				// put features into the scale of the upper image
				foundPoints.add(new ScalePoint(fx * scale1, fy * scale1, adjSigma));
			}
		}
	}
1122817
protected void updateTrackLocation(T image) {
		get_subwindow(image, templateNew);

		// calculate response of the classifier at all locations
		// matlab: k = dense_gauss_kernel(sigma, x, z);
		dense_gauss_kernel(sigma, templateNew, template,k);

		fft.forward(k,kf);

		// response = real(ifft2(alphaf .* fft2(k)));   %(Eq. 9)
		DiscreteFourierTransformOps.multiplyComplex(alphaf, kf, tmpFourier0);
		fft.inverse(tmpFourier0, response);

		// find the pixel with the largest response
		int N = response.width*response.height;
		int indexBest = -1;
		double valueBest = -1;
		for( int i = 0; i < N; i++ ) {
			double v = response.data[i];
			if( v > valueBest ) {
				valueBest = v;
				indexBest = i;
			}
		}

		int peakX = indexBest % response.width;
		int peakY = indexBest / response.width;

		// sub-pixel peak estimation
		subpixelPeak(peakX, peakY);

		// peak in region's coordinate system
		float deltaX = (peakX+offX) - templateNew.width/2;
		float deltaY = (peakY+offY) - templateNew.height/2;

		// convert peak location into image coordinate system
		regionTrack.x0 = regionTrack.x0 + deltaX*stepX;
		regionTrack.y0 = regionTrack.y0 + deltaY*stepY;

		updateRegionOut();
	}