Get threshold based on the mode of the image
    The threshold is calculated by calculating the mode and multiplying by
    2 (an arbitrary empirical factor). The user will presumably adjust the
    multiplication factor as needed.
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)
277885
public static <T extends ImageGray<T>>
	InputToBinary<T> threshold( ConfigThreshold config, Class<T> inputType) {

		switch( config.type ) {
			case FIXED:
				return globalFixed(config.fixedThreshold, config.down, inputType);

			case GLOBAL_OTSU:
				return globalOtsu(config.minPixelValue, config.maxPixelValue, config.scale, config.down, inputType);

			case GLOBAL_ENTROPY:
				return globalEntropy(config.minPixelValue, config.maxPixelValue, config.scale, config.down, inputType);

			case GLOBAL_LI:
				return globalLi(config.minPixelValue, config.maxPixelValue, config.scale, config.down, inputType);

			case GLOBAL_HUANG:
				return globalHuang(config.minPixelValue, config.maxPixelValue, config.scale, config.down, inputType);

			case LOCAL_GAUSSIAN:
				return localGaussian(config.width, config.scale, config.down, inputType);

			case LOCAL_SAVOLA:
				return localSauvola(config.width, config.down, config.savolaK, inputType);

			case LOCAL_NICK:
				return localNick(config.width, config.down, config.nickK, inputType);

			case LOCAL_MEAN:
				return localMean(config.width, config.scale, config.down, inputType);

			case LOCAL_OTSU: {
				ConfigThresholdLocalOtsu c = (ConfigThresholdLocalOtsu) config;
				return localOtsu(config.width, config.scale, config.down, c.useOtsu2, c.tuning, inputType);
			}

			case BLOCK_MIN_MAX: {
				ConfigThresholdBlockMinMax c = (ConfigThresholdBlockMinMax) config;
				return blockMinMax(c.width, c.scale , c.down, c.thresholdFromLocalBlocks, c.minimumSpread,
						inputType);
			}

			case BLOCK_MEAN:
				return blockMean(config.width, config.scale , config.down,
						config.thresholdFromLocalBlocks, inputType);

			case BLOCK_OTSU: {
				ConfigThresholdLocalOtsu c = (ConfigThresholdLocalOtsu) config;
				return blockOtsu(c.width, c.scale, c.down, c.thresholdFromLocalBlocks, c.useOtsu2, c.tuning,
						inputType);
			}

		}
		throw new IllegalArgumentException("Unknown type "+config.type);
	}
183294
function getThreshold(threshold) {
			if (min > threshold) {
				threshold = min;
			} else if (max < threshold) {
				threshold = max;
			}

			return translate(threshold, 0, 1);
		}
717074
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
    """"""

    img = load_image_from_disk(img_spec)

    if not np.issubdtype(img.dtype, np.floating):
        img = img.astype('float32')

    if ensure_num_dim == 3:
        img = check_image_is_3d(img)
    elif ensure_num_dim == 4:
        img = check_image_is_4d(img)

    return threshold_image(img, bkground_thresh)
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
1304698
def get_kapur_threshold(image, mask=None):
    """"""
    cropped_image = np.array(image.flat) if mask is None else image[mask]
    if np.product(cropped_image.shape)<3:
        return 0
    if np.min(cropped_image) == np.max(cropped_image):
        return cropped_image[0]
    log_image = np.log2(smooth_with_noise(cropped_image, 8))
    min_log_image = np.min(log_image)
    max_log_image = np.max(log_image)
    histogram = scipy.ndimage.histogram(log_image,
                                        min_log_image,
                                        max_log_image,
                                        256)
    histogram_values = (min_log_image + (max_log_image - min_log_image)*
                        np.arange(256, dtype=float) / 255)
    # drop any zero bins
    keep = histogram != 0
    histogram = histogram[keep]
    histogram_values = histogram_values[keep]
    # check for corner cases
    if np.product(histogram_values)==1:
        return 2**histogram_values[0] 
    # Normalize to probabilities
    p = histogram.astype(float) / float(np.sum(histogram))
    # Find the probabilities totals up to and above each possible threshold.
    lo_sum = np.cumsum(p);
    hi_sum = lo_sum[-1] - lo_sum;
    lo_e = np.cumsum(p * np.log2(p));
    hi_e = lo_e[-1] - lo_e;

    # compute the entropies
    lo_entropy = lo_e / lo_sum - np.log2(lo_sum);
    hi_entropy = hi_e / hi_sum - np.log2(hi_sum);

    sum_entropy = lo_entropy[:-1] + hi_entropy[:-1];
    sum_entropy[np.logical_not(np.isfinite(sum_entropy))] = np.Inf
    entry = np.argmin(sum_entropy);
    return 2**((histogram_values[entry] + histogram_values[entry+1]) / 2);
675211
public void selectThreshold( ImageRectangle r ) {
		double variance = computeVarianceSafe(r.x0, r.y0, r.x1, r.y1);

		thresholdLower = variance*0.5;
	}
710865
def getIRThreshold(self):
    """"""
    command = '$GO'
    threshold = self.sendCommand(command)
    if threshold[0] == 'NK':
      return 0
    else:
      return float(threshold[2])/10
846272
private void computeScales() {
		int width = getWidth();
		int height = getHeight();

		width = (width-borderSize)/2;

		// compute the scale factor for each image
		scaleLeft = scaleRight = 1;
		if( leftImage.getWidth() > width || leftImage.getHeight() > height ) {
			double scaleX = (double)width/(double)leftImage.getWidth();
			double scaleY = (double)height/(double)leftImage.getHeight();
			scaleLeft = Math.min(scaleX,scaleY);
		}
		if( rightImage.getWidth() > width || rightImage.getHeight() > height ) {
			double scaleX = (double)width/(double)rightImage.getWidth();
			double scaleY = (double)height/(double)rightImage.getHeight();
			scaleRight = Math.min(scaleX,scaleY);
		}
	}
1019451
def _parse(self, threshold):
        
        match = re.search(r'^(@?)((~|\d*):)?(\d*)$', threshold)

        if not match:
            raise ValueError('Error parsing Threshold: {0}'.format(threshold))

        if match.group(1) == '@':
            self._inclusive = True

        if match.group(3) == '~':
            self._min = float('-inf')
        elif match.group(3):
            self._min = float(match.group(3))
        else:
            self._min = float(0)

        if match.group(4):
            self._max = float(match.group(4))
        else:
            self._max = float('inf')

        if self._max < self._min:
            raise ValueError('max must be superior to min')
419406
def step(self):
        """"""
        # Assign attributes to local variables for convenience.
        u = self._u
        gI = self._data
        dgI = self._ddata
        theta = self._theta
        v = self._v
        
        if u is None:
            raise ValueError("the levelset is not set (use set_levelset)")
        
        res = np.copy(u)
        
        # Balloon.
        if v > 0:
            aux = binary_dilation(u, self.structure)
        elif v < 0:
            aux = binary_erosion(u, self.structure)
        if v!= 0:
            res[self._threshold_mask_v] = aux[self._threshold_mask_v]
        
        # Image attachment.
        aux = np.zeros_like(res)
        dres = np.gradient(res)
        for el1, el2 in zip(dgI, dres):
            aux += el1*el2
        res[aux > 0] = 1
        res[aux < 0] = 0
        
        # Smoothing.
        for i in range(self.smoothing):
            res = curvop(res)
        
        self._u = res
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
727136
def ambient_light_intensity(self):
        
        self._ensure_mode(self.MODE_AMBIENT)
        return self.value(0) * self._scale('AMBIENT')
854020
static boolean positionSquareIntensityCheck(float values[] , float threshold ) {
		if( values[0] > threshold || values[1] < threshold )
			return false;
		if( values[2] > threshold || values[3] > threshold || values[4] > threshold  )
			return false;
		if( values[5] < threshold || values[6] > threshold )
			return false;
		return true;
	}
141152
def threshold(self, vmin=None, vmax=None, replaceWith=None):
        
        th = vtk.vtkImageThreshold()
        th.SetInputData(self.image)
        
        if vmin is not None and vmax is not None:
            th.ThresholdBetween(vmin, vmax)
        elif vmin is not None:
            th.ThresholdByUpper(vmin)
        elif vmax is not None:
            th.ThresholdByLower(vmax)       

        if replaceWith:
            th.ReplaceOutOn()
            th.SetOutValue(replaceWith)
        th.Update()
        
        self.image = th.GetOutput()
        self.mapper.SetInputData(self.image)
        self.mapper.Modified()
        return self
605373
def guess_mode(self, data):
        
        # TODO: do we want to support dimensions being at the beginning of the array?
        if data.ndim == 2:
            return "L"
        elif data.shape[-1] == 3:
            return "RGB"
        elif data.shape[-1] == 4:
            return "RGBA"
        else:
            raise ValueError(
                "Un-supported shape for image conversion %s" % list(data.shape))
974353
def getScale(self, zoom):
        """"""
        if self.unit == 'degrees':
            resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT
        else:
            resolution = self.getResolution(zoom)
        return resolution / STANDARD_PIXEL_SIZE