Local equalization along a row.  Image must be at least the histogram's width (2*r+1) in width and height.
432016
public static void equalizeLocalRow( GrayU16 input , int radius , int startY , GrayU16 output ,
										 IWorkArrays workArrays ) {

		int width = 2*radius+1;
		int area = width*width;
		int maxValue = workArrays.length()-1;
		int[] histogram = workArrays.pop();
		int[] transform = workArrays.pop();

		// specify the top and bottom of the histogram window and make sure it is inside bounds
		int hist0 = startY;
		int hist1 = startY+width;
		if( hist1 > input.height ) {
			hist1 = input.height;
			hist0 = hist1 - width;
		}

		// the upper and lower bounds of the region being equalized
		int region0 = startY;
		int region1 = startY+radius;

		// local histogram and transformation
		localHistogram(input,0,hist0,width,hist1,histogram);

		int sum = 0;
		for( int i = 0; i < histogram.length; i++ ) {
			transform[i] = sum += histogram[i];
		}

		// equalize the first square region
		for( int y = region0; y < region1; y++ ) {
			int indexIn = input.startIndex + y*input.stride;
			int indexOut = output.startIndex + y*output.stride;

			for( int x = 0; x <= radius; x++ ) {
				int inputValue =  input.data[indexIn++] & 0xff;
				output.data[indexOut++] = (short)((transform[ inputValue ]*maxValue)/area);
			}
		}

		// move right while equalizing the columns one at a time
		for( int x = radius+1; x < input.width-radius-1; x++ ) {

			// remove the left most column
			int indexIn = input.startIndex + x-radius-1;
			for( int y = hist0; y < hist1; y++ ) {
				histogram[input.data[indexIn + y*input.stride] & 0xFFFF]--;
			}
			// add the right most column
			indexIn += width;
			for( int y = hist0; y < hist1; y++ ) {
				histogram[input.data[indexIn + y*input.stride] & 0xFFFF]++;
			}

			// compute transformation table
			sum = 0;
			for( int i = 0; i < histogram.length; i++ ) {
				transform[i] = sum += histogram[i];
			}

			// compute the output down the column
			indexIn = input.startIndex + region0*input.stride + x;
			int indexOut = output.startIndex + region0*output.stride + x;
			for( int y = 0; y < radius; y++ ) {
				int inputValue =  input.data[indexIn] & 0xff;
				output.data[indexOut] = (short)((transform[ inputValue ]*maxValue)/area);

				indexIn += input.stride;
				indexOut += output.stride;
			}
		}

		// equalize the final square region
		localHistogram(input,input.width-width,hist0,input.width,hist1,histogram);

		sum = 0;
		for( int i = 0; i < histogram.length; i++ ) {
			transform[i] = sum += histogram[i];
		}

		for( int y = region0; y < region1; y++ ) {
			int x = input.width-radius-1;

			int indexIn = input.startIndex + y*input.stride + x;
			int indexOut = output.startIndex + y*output.stride + x;

			for( ; x < input.width; x++ ) {
				int inputValue =  input.data[indexIn++] & 0xff;
				output.data[indexOut++] = (short)((transform[ inputValue ]*maxValue)/area);
			}
		}

		workArrays.recycle(histogram);
		workArrays.recycle(transform);
	}
122622
private void thresholdBlur(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha) {
		int index = 0;
		float[] matrix = kernel.getKernelData( null );
		int cols = kernel.getWidth();
		int cols2 = cols/2;

		for (int y = 0; y < height; y++) {
			int ioffset = y*width;
            int outIndex = y;
			for (int x = 0; x < width; x++) {
				float r = 0, g = 0, b = 0, a = 0;
				int moffset = cols2;

                int rgb1 = inPixels[ioffset+x];
                int a1 = (rgb1 >> 24) & 0xff;
                int r1 = (rgb1 >> 16) & 0xff;
                int g1 = (rgb1 >> 8) & 0xff;
                int b1 = rgb1 & 0xff;
				float af = 0, rf = 0, gf = 0, bf = 0;
                for (int col = -cols2; col <= cols2; col++) {
					float f = matrix[moffset+col];

					if (f != 0) {
						int ix = x+col;
						if (!(0 <= ix && ix < width))
							ix = x;
						int rgb2 = inPixels[ioffset+ix];
                        int a2 = (rgb2 >> 24) & 0xff;
                        int r2 = (rgb2 >> 16) & 0xff;
                        int g2 = (rgb2 >> 8) & 0xff;
                        int b2 = rgb2 & 0xff;

						int d;
                        d = a1-a2;
                        if ( d >= -threshold && d <= threshold ) {
                            a += f * a2;
                            af += f;
                        }
                        d = r1-r2;
                        if ( d >= -threshold && d <= threshold ) {
                            r += f * r2;
                            rf += f;
                        }
                        d = g1-g2;
                        if ( d >= -threshold && d <= threshold ) {
                            g += f * g2;
                            gf += f;
                        }
                        d = b1-b2;
                        if ( d >= -threshold && d <= threshold ) {
                            b += f * b2;
                            bf += f;
                        }
					}
				}
                a = af == 0 ? a1 : a/af;
                r = rf == 0 ? r1 : r/rf;
                g = gf == 0 ? g1 : g/gf;
                b = bf == 0 ? b1 : b/bf;
				int ia = alpha ? PixelUtils.clamp((int)(a+0.5)) : 0xff;
				int ir = PixelUtils.clamp((int)(r+0.5));
				int ig = PixelUtils.clamp((int)(g+0.5));
				int ib = PixelUtils.clamp((int)(b+0.5));
				outPixels[outIndex] = (ia << 24) | (ir << 16) | (ig << 8) | ib;
                outIndex += height;
			}
		}
	}
681279
public static void histogram_F32(Planar<GrayF32> image , Histogram_F64 histogram )
	{
		if (image.getNumBands() != histogram.getDimensions())
			throw new IllegalArgumentException("Number of bands in the image and histogram must be the same");

		if( !histogram.isRangeSet() )
			throw new IllegalArgumentException("Must specify range along each dimension in histogram");

		final int D = histogram.getDimensions();
		int coordinate[] = new int[ D ];

		histogram.fill(0);

		for (int y = 0; y < image.getHeight(); y++) {
			int imageIndex = image.getStartIndex() + y*image.getStride();
			for (int x = 0; x < image.getWidth(); x++ , imageIndex++) {
				for (int i = 0; i < D; i++) {
					coordinate[i] = histogram.getDimensionIndex(i,image.getBand(i).data[imageIndex]);
				}
				int index = histogram.getIndex(coordinate);
				histogram.value[index] += 1;
			}
		}
	}
424240
def viz_square(data, normalize=True, cmap=plt.cm.gray, padsize=1, padval=0):
    
    # normalize to 0-1 range
    if normalize:
        data -= data.min()
        data /= data.max()
    n = int(np.ceil(np.sqrt(data.shape[0]))) # force square 
    padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
    data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
    # tile the filters into an image
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    plt.matshow(data,cmap=cmap)
495529
def correct(self, image, keepSize=False, borderValue=0):
        '''
        
        '''
        image = imread(image)
        (h, w) = image.shape[:2]
        mapx, mapy = self.getUndistortRectifyMap(w, h)
        self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
                             borderMode=cv2.BORDER_CONSTANT,
                             borderValue=borderValue
                             )
        if not keepSize:
            xx, yy, ww, hh = self.roi
            self.img = self.img[yy: yy + hh, xx: xx + ww]
        return self.img
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
9638
public void computeHistogram( T image , RectangleRotate_F32 region ) {

		interpolate.setImage(image);

		c = (float)Math.cos( region.theta );
		s = (float)Math.sin( region.theta );

		for( int i = 0; i < histogram.length; i++ ) {
			histogram[i] = 0;
		}

		// if it is entirely inside the image, interpolate using a faster technique
		if( isInFastBounds(region) ) {
			computeHistogramInside( region);
		} else {
			computeHistogramBorder(image, region);
		}

		normalizeHistogram();
	}
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)
205559
def preprocess(net, image):
    '''
    
    '''
    return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]
136417
def rgb2gray(rgb):
    

    w = sla.atleast_nd(rgb.ndim, np.array([0.299, 0.587, 0.144],
                                          dtype=rgb.dtype, ndmin=3))
    return np.sum(w * rgb, axis=2)
920491
def stretch_hist_equalize(self, ch_nb):
        
        logger.info("Perform a histogram equalized contrast stretch.")

        if(self.channels[ch_nb].size ==
           np.ma.count_masked(self.channels[ch_nb])):
            logger.warning("Nothing to stretch !")
            return

        arr = self.channels[ch_nb]

        nwidth = 2048.0

        carr = arr.compressed()

        cdf = np.arange(0.0, 1.0, 1 / nwidth)
        logger.debug("Make histogram bins having equal amount of data, " +
                     "using numpy percentile function:")
        bins = np.percentile(carr, list(cdf * 100))

        res = np.ma.empty_like(arr)
        res.mask = np.ma.getmaskarray(arr)
        res[~res.mask] = np.interp(carr, bins, cdf)

        self.channels[ch_nb] = res
1046981
def medianThreshold(img, threshold=0.1, size=3, condition='>', copy=True):
    '''
    
    '''
    from scipy.ndimage import median_filter

    indices = None
    if threshold > 0:
        blur = np.asfarray(median_filter(img, size=size))
        with np.errstate(divide='ignore', invalid='ignore', over='ignore'):

            if condition == '>':
                indices = abs((img - blur) / blur) > threshold
            else:
                indices = abs((img - blur) / blur) < threshold

        if copy:
            img = img.copy()

        img[indices] = blur[indices]
    return img, indices
16043
def _normalize_params(image, width, height, crop):
    
    if width is None and height is None:
        raise ValueError("Either width or height must be set. Otherwise "
                         "resizing is useless.")

    if width is None or height is None:
        aspect = float(image.width) / float(image.height)

        if crop:
            raise ValueError("Cropping the image would be useless since only "
                             "one dimention is give to resize along.")

        if width is None:
            width = int(round(height * aspect))
        else:
            height = int(round(width / aspect))

    return (width, height, crop)
598054
def processFrame(frame):
    """"""
    # The pixels are grey-scale values from 0-255 - white = 255, black = 0
    # We want to turn the image into two values, one for the left "sensor" and one for the right.
    # There are many possible ways to do this. The very simplest way would be
    # to examine the values of two pixels - one in the centre of the left half of the image,
    # and one in the centre of the right half. What are the obvious problems with this?

    # NB: The pixels are stored in a flat (1 dimensional) array, so to calculate the index of the pixels
    # at (x,y), we do:
    # index = x + (y * width)

    width = frame.width
    height = frame.height
    pixels = frame.pixels

    USE_SIMPLE_APPROACH = False  # Change this to False to use more sophisticated approach.

    if USE_SIMPLE_APPROACH:
        # Simplest approach.
        left_centre_x = int(width / 4)      # Centre of left half
        right_centre_x = int(3 * width / 4) # Centre of right half
        centre_y = int(height / 2)          # Middle row
        left_pixel_index = left_centre_x + (centre_y * width)
        right_pixel_index = right_centre_x + (centre_y * width)
        left_sensor = float(pixels[left_pixel_index]) / 255.0
        right_sensor = float(pixels[right_pixel_index]) / 255.0
    else:
        # Obviously, the simple approach misses a lot of data, and is very susceptible to noise.
        # A better approach would be to consider more pixels.
        # You could take the average of all the pixels - it's slower but better.
        # Or you could use the median value, which is less noisy than the mean.
        # Here we calculate both, and estimate the median using histograms:
        left_total = 0
        right_total = 0
        left_hist = [0 for i in range(256)]
        right_hist = [0 for i in range(256)]
        # Create a histogram for each half of the image:
        for y in range(height):
            for x in range(int(width/2)):
                i = pixels[x + y*width]
                left_hist[i] += 1
                left_total += float(i)/255.0
            for x in range(int(width/2), width):
                i = pixels[x + y*width]
                right_hist[i] += 1
                right_total += float(i)/255.0
        # Calculate the mean values:
        left_mean, right_mean = left_total / (width*height/2), right_total / (width*height/2)
        # Now use the histogram to estimate the median value
        left_total, right_total = 0, 0
        pixels_per_half = width * height / 2
        cut_off_value = pixels_per_half / 2
        left_cut_off_point, right_cut_off_point = 0, 0
        while (left_total < cut_off_value):
            left_total += left_hist[left_cut_off_point]
            left_cut_off_point += 1
        while(right_total < cut_off_value):
            right_total += right_hist[right_cut_off_point]
            right_cut_off_point += 1
        left_median, right_median = left_cut_off_point / 255.0, right_cut_off_point / 255.0
        
        # Use the median values:
        left_sensor, right_sensor = left_median, right_median
        # Or uncomment this line to use the mean values:
        # left_sensor, right_sensor = left_mean, right_mean
    
    # In our gloomy arena, we never get particularly bright, so the sensor values tend to be low.
    # To get more action from our vehicle, we can scale up (keeping 1.0 as the max).
    # What values work well for GAIN? What happens if it's too high or too low?
    GAIN = 1.8
    left_sensor = min(1, left_sensor * GAIN)
    right_sensor = min(1, right_sensor * GAIN)
    # Done - return the values:
    return left_sensor, right_sensor
105975
def convert_la_to_rgba(self, row, result):
        """"""
        for i in range(len(row) // 3):
            for j in range(3):
                result[(4 * i) + j] = row[2 * i]
            result[(4 * i) + 3] = row[(2 * i) + 1]
1013178
def match_via_squared_difference(image, template, raw_tolerance=1, sq_diff_tolerance=0.1):
    
    h, w = image.shape
    th, tw = template.shape
    # fft based convolution enables fast matching of large images
    correlation = fftconvolve(image, template[::-1,::-1])
    # trim the returned image, fftconvolve returns an image of width: (Temp_w-1) + Im_w + (Temp_w -1), likewise height
    correlation = correlation[th-1:h, tw-1:w]
    # find images regions which are potentially matches
    match_position_dict = get_tiles_at_potential_match_regions(image, template, correlation, raw_tolerance=raw_tolerance)
    # bright spots in images can lead to false positivies- the normalisation carried out here eliminates those
    results = calculate_squared_differences(match_position_dict, correlation, template, sq_diff_tolerance=sq_diff_tolerance)
    return results
1179999
public static void horizontal(GrayF64 input, GrayF64 output, int radius) {

		boolean processed = BOverrideConvolveImageMean.invokeNativeHorizontal(input, output, radius);

		if( !processed ) {
			Kernel1D_F64 kernel = FactoryKernel.table1D_F64(radius, true);
			if (kernel.width > input.width) {
				ConvolveImageNormalized.horizontal(kernel, input, output);
			} else {
				InputSanityCheck.checkSameShape(input, output);
				ConvolveNormalized_JustBorder_SB.horizontal(kernel, input, output);
				if(BoofConcurrency.USE_CONCURRENT) {
					ImplConvolveMean_MT.horizontal(input, output, radius);
				} else {
					ImplConvolveMean.horizontal(input, output, radius);
				}
			}
		}
	}