Takes images scaled to [0, 1] and returns them appropriately scaled and
    mean-subtracted for VGG-16
178335
def _vgg16_data_prep(batch):
    
    from mxnet import nd
    mean = nd.array([123.68, 116.779, 103.939], ctx=batch.context)
    return nd.broadcast_sub(255 * batch, mean.reshape((-1, 1, 1)))
655557
def get_image_ratio(self, image):
        
        x, y = self.get_image_size(image)
        return float(x) / y
705603
def image_scale(xscale=1.0, yscale=1.0, axes="gca"):
    
    if axes == "gca": axes = _pylab.gca()

    e = axes.images[0].get_extent()
    x1 = e[0]*xscale
    x2 = e[1]*xscale
    y1 = e[2]*yscale
    y2 = e[3]*yscale

    image_set_extent([x1,x2],[y1,y2], axes)
1161233
def normalise_correlation(image_tile_dict, transformed_array, template, normed_tolerance=1):
    
    template_norm = np.linalg.norm(template)
    image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)])*template_norm for (x,y) in image_tile_dict.keys()}
    match_points = image_tile_dict.keys()
    # for correlation, then need to transofrm back to get correct value for division
    h, w = template.shape
    #points_from_transformed_array = [(match[0] + h - 1, match[1] + w - 1) for match in match_points]
    image_matches_normalised = {match_points[i]:transformed_array[match_points[i][0], match_points[i][1]]/image_norms[match_points[i]] for i in range(len(match_points))}
    result = {key:value for key, value in image_matches_normalised.items() if np.round(value, decimals=3) >= normed_tolerance}
    return result.keys()
654060
def _extract_shifted_mean_gauss(image, mask = slice(None), offset = None, sigma = 1, voxelspacing = None):
        
    # set voxel spacing
    if voxelspacing is None:
        voxelspacing = [1.] * image.ndim
    # set offset
    if offset is None:
        offset = [0] * image.ndim
    
    # determine gaussian kernel size in voxel units
    sigma = _create_structure_array(sigma, voxelspacing)
    
    # compute smoothed version of image
    smoothed = gaussian_filter(image, sigma)
    
    shifted = numpy.zeros_like(smoothed)
    in_slicer = []
    out_slicer = []
    for o in offset:
        in_slicer.append(slice(o, None))
        out_slicer.append(slice(None, -1 * o))
    shifted[out_slicer] = smoothed[in_slicer]
    
    return _extract_intensities(shifted, mask)
60477
def scaleSignal(img, fitParams=None,
                backgroundToZero=False, reference=None):
    '''
    
    '''
    img = imread(img)
    if reference is not None:
        #         def fn(ii, m,n):
        #             return ii*m+n
        #         curve_fit(fn, img[::10,::10], ref[::10,::10])

        low, high = signalRange(img, fitParams)
        low2, high2 = signalRange(reference)
        img = np.asfarray(img)
        ampl = (high2 - low2) / (high - low)
        img -= low
        img *= ampl
        img += low2
        return img
    else:
        offs, div = scaleParams(img, fitParams, backgroundToZero)
        img = np.asfarray(img) - offs
        img /= div
        print('offset: %s, divident: %s' % (offs, div))
        return img
228880
def fastMean(img, f=10, inplace=False):
    '''
    
    '''
    s0,s1 = img.shape[:2]
    ss0 = int(round(s0/f))
    ss1 = int(round(s1/f))

    small = cv2.resize(img,(ss1,ss0), interpolation=cv2.INTER_AREA)
        #bigger
    k = {'interpolation':cv2.INTER_LINEAR}
    if inplace:
        k['dst']=img
    return cv2.resize(small,(s1,s0), **k)
336396
def uint8sc(im):
    
    im = np.asarray(im)
    immin = im.min()
    immax = im.max()
    imrange = immax - immin
    return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)
859486
def _get_renditions(self, kwargs):
        
        img_1x, size = self.get_rendition(
            1, **utils.remap_args(kwargs, {"quality": "quality_ldpi"}))
        img_2x, _ = self.get_rendition(
            2, **utils.remap_args(kwargs, {"quality": "quality_hdpi"}))

        return (img_1x, img_2x, size)
843471
def resample_image(arr, max_size=400):
    """"""
    dim = np.max(arr.shape[0:2])
    if dim < max_size:
        max_size = dim
    x, y, _ = arr.shape
    sx = int(np.ceil(x / max_size))
    sy = int(np.ceil(y / max_size))
    img = np.zeros((max_size, max_size, 3), dtype=arr.dtype)
    arr = arr[0:-1:sx, 0:-1:sy, :]
    xl = (max_size - arr.shape[0]) // 2
    yl = (max_size - arr.shape[1]) // 2
    img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
    return img
459381
def sample_image(d, data, u, v, w, i=-1, verbose=0, imager='xy', wres=100):
    

    if i == -1:
        i = len(data)/2

    if imager == 'xy':
        image = rtlib.imgonefullxy(n.outer(u, d['freq']/d['freq_orig'][0]), n.outer(v, d['freq']/d['freq_orig'][0]), data[i], d['npixx'], d['npixy'], d['uvres'], verbose=verbose)
    elif imager == 'w':
        npix = max(d['npixx'], d['npixy'])
        bls, uvkers = rtlib.genuvkernels(w, wres, npix, d['uvres'], ksize=21, oversample=1)
        image = rtlib.imgonefullw(n.outer(u, d['freq']/d['freq_orig'][0]), n.outer(v, d['freq']/d['freq_orig'][0]), data[i], npix, d['uvres'], bls, uvkers, verbose=verbose)

#        bls, lmkers = rtlib.genlmkernels(w, wres, npix, d['uvres'])
#        image = rtlib.imgonefullw(n.outer(u, d['freq']/d['freq_orig'][0]), n.outer(v, d['freq']/d['freq_orig'][0]), data[i], npix, d['uvres'], [bls[0]], [lmkers[0]], verbose=verbose)

    return image
534083
def to_rectangular(image):
    
    # xy image, vertical scaled to 360 degrees
    xy = pyvips.Image.xyz(image.width, image.height)
    xy *= [1, 360.0 / image.height]

    index = xy.rect()

    # scale to image rect
    scale = min(image.width, image.height) / float(image.width)
    index *= scale / 2.0
    index += [image.width / 2.0, image.height / 2.0]

    return image.mapim(index)
663270
def _correctArtefacts(self, image, threshold):
        '''
        
        '''
        image = np.nan_to_num(image)
        medianThreshold(image, threshold, copy=False)
        return image
31083
protected static<T extends ImageGray<T>>
	void imageNormalization(T image1, T image2, GrayF32 normalized1, GrayF32 normalized2 )
	{
		// find the max and min of both images
		float max1 = (float)GImageStatistics.max(image1);
		float max2 = (float)GImageStatistics.max(image2);
		float min1 = (float)GImageStatistics.min(image1);
		float min2 = (float)GImageStatistics.min(image2);

		// obtain the absolute max and min
		float max = max1 > max2 ? max1 : max2;
		float min = min1 < min2 ? min1 : min2;
		float range = max - min;

		if(range > 0) {
			// normalize both images
			int indexN = 0;
			for (int y = 0; y < image1.height; y++) {
				for (int x = 0; x < image1.width; x++,indexN++) {
					// this is a slow way to convert the image type into a float, but everything else is much
					// more expensive
					float pv1 = (float)GeneralizedImageOps.get(image1, x, y);
					float pv2 = (float)GeneralizedImageOps.get(image2,x,y);

					normalized1.data[indexN] = (pv1 - min) / range;
					normalized2.data[indexN] = (pv2 - min) / range;
				}
			}
		} else {
			GConvertImage.convert(image1, normalized1);
			GConvertImage.convert(image2, normalized2);
		}
	}
1082079
def feature_scaling(x, xmin, xmax, a=0, b=1):
    ''''''
    return a + float(x - xmin) * (b - a) / (xmax - xmin)
1075946
def array_to_img(x, scale=True):
    
    from PIL import Image
    if x.ndim != 3:
        raise Exception('Unsupported shape : ', str(x.shape), '. Need (channels, width, height)')
    if scale:
        x += max(-np.min(x), 0)
        x /= np.max(x)
        x *= 255
    if x.shape[0] == 3:
        # RGB
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.astype('uint8'), 'RGB')
    elif x.shape[0] == 1:
        # grayscale
        if x.dtype != 'uint8':
            x = x.astype('uint8')
        return Image.fromarray(x.reshape(x.shape[1], x.shape[2]), 'L')
    else:
        raise Exception('Unsupported channel number: ', x.shape[0])
4711
def get_per_pixel_mean(names=('train', 'test', 'extra')):
        
        for name in names:
            assert name in ['train', 'test', 'extra'], name
        images = [SVHNDigit(x).X for x in names]
        return np.concatenate(tuple(images)).mean(axis=0)