Extract a region of the image defined by corners (x1, y1) and
        (x2, y2) and resample it to fit dimensions (new_wd, new_ht).

        `method` describes the method of interpolation used, where the
        default "basic" is nearest neighbor.
2671
def get_scaled_cutout_wdht(self, x1, y1, x2, y2, new_wd, new_ht,
                               method='basic'):
        

        if method in ('basic', 'view'):
            shp = self.shape

            (view, (scale_x, scale_y)) = \
                trcalc.get_scaled_cutout_wdht_view(shp, x1, y1, x2, y2,
                                                   new_wd, new_ht)
            newdata = self._slice(view)

        else:
            data_np = self._get_data()
            (newdata, (scale_x, scale_y)) = \
                trcalc.get_scaled_cutout_wdht(data_np, x1, y1, x2, y2,
                                              new_wd, new_ht,
                                              interpolation=method,
                                              logger=self.logger)

        res = Bunch.Bunch(data=newdata, scale_x=scale_x, scale_y=scale_y)
        return res
250833
def _extract_median(image, mask = slice(None), size = 1, voxelspacing = None):
    
    # set voxel spacing
    if voxelspacing is None:
        voxelspacing = [1.] * image.ndim
        
    # determine structure element size in voxel units
    size = _create_structure_array(size, voxelspacing)
        
    return _extract_intensities(median_filter(image, size), mask)
380263
def sampleLocationFromFeature(self, feature):
    
    if feature == "surface":
      return self.sampleLocationFromFeature('face') # Temporary workaround for surfaces
    elif feature=="face":
      indx = self.rng.choice(range(self.faces.count))
      rndFace = self.faces[indx]
      return self._sampleLocationOnFace(rndFace)

    elif feature == "edge":
      indx = self.rng.choice(range(self.faces.count))
      rndFace = self.faces[indx]
      rndVertices = self.rng.sample(self.vertices[rndFace],2)
      return self._sampleLocationOnEdge(rndVertices)

    elif feature == "vertex":
      rndVertexIndx = self.rng.choice(range(self.vertices.count))
      return np.array(self.vertices[rndVertexIndx].tolist())

    elif feature == "surface":
      return self.sampleLocationFromFeature("face")      # Temporary workaround for surfaces
    elif feature == "random":
      return self.sampleLocation()
    else:
      raise NameError("No such feature in {}: {}".format(self, feature))
36769
def image2array(image):
    
    nx, ny = image.shape  # find the size of the array
    imgh = np.reshape(image, nx*ny)  # change the shape to be 1d
    return imgh
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
1240193
def _extract_local_mean_gauss(image, mask = slice(None), sigma = 1, voxelspacing = None):
    
    # set voxel spacing
    if voxelspacing is None:
        voxelspacing = [1.] * image.ndim
        
    # determine gaussian kernel size in voxel units
    sigma = _create_structure_array(sigma, voxelspacing)
        
    return _extract_intensities(gaussian_filter(image, sigma), mask)
267127
def standardDeviation2d(img, ksize=5, blurred=None):
    '''
    
    '''
    if ksize not in (list, tuple):
        ksize = (ksize,ksize)

    if blurred is None:
        blurred = gaussian_filter(img, ksize)
    else:
        assert blurred.shape == img.shape
    
    std = np.empty_like(img)
    
    _calc(img, ksize[0], ksize[1], blurred, std)
    
    return std
1161655
def _nn(self, side, v, k=1, radius=np.inf, eps=0.0, p=2):
        
        if self.size > 0:
            dists, idxes = Dataset._nn(self, side, v, k, radius, eps, p)
        else:
            return self.buffer._nn(side, v, k, radius, eps, p)
        if self.buffer.size > 0:
            buffer_dists, buffer_idxes = self.buffer._nn(side, v, k, radius, eps, p)
            buffer_idxes = [i + self.size for i in buffer_idxes]
            ziped = zip(dists, idxes)
            buffer_ziped = zip(buffer_dists, buffer_idxes)
            sorted_dists_idxes = sorted(ziped + buffer_ziped, key=lambda di:di[0])
            knns = sorted_dists_idxes[:k]
            return [knn[0] for knn in knns], [knn[1] for knn in knns] 
        else:
            return dists, idxes
1160069
def estimateFromImages(imgs1, imgs2=None, mn_mx=None, nbins=100):
    '''
    
    '''
    if imgs2 is None:
        imgs2 = [None] * len(imgs1)
    else:
        assert len(imgs1) == len(imgs2)

    y_vals = np.empty((len(imgs1), nbins))
    w_vals = np.zeros((len(imgs1), nbins))

    if mn_mx is None:
        print('estimating min and max image value')
        mn = 1e6
        mx = -1e6
        # get min and max image value checking all first images:
        for n, i1 in enumerate(imgs1):
            print('%s/%s' % (n + 1, len(imgs1)))
            i1 = imread(i1)
            mmn, mmx = _getMinMax(i1)
            mn = min(mn, mmn)
            mx = mx = max(mx, mmx)
        print('--> min(%s), max(%s)' % (mn, mx))
    else:
        mn, mx = mn_mx

    x = None
    print('get noise level function')
    for n, (i1, i2) in enumerate(zip(imgs1, imgs2)):
        print('%s/%s' % (n + 1, len(imgs1)))

        i1 = imread(i1)
        if i2 is not None:
            i2 = imread(i2)

        x, y, weights, _ = calcNLF(i1, i2, mn_mx_nbins=(mn, mx, nbins), x=x)
        y_vals[n] = y
        w_vals[n] = weights

    # filter empty places:
    filledPos = np.sum(w_vals, axis=0) != 0
    w_vals = w_vals[:, filledPos]
    y_vals = y_vals[:, filledPos]
    x = x[filledPos]

    y_avg = np.average(np.nan_to_num(y_vals),
                       weights=w_vals,
                       axis=0)
    w_vals = np.sum(w_vals, axis=0)
    w_vals /= w_vals.sum()

    fitParams, fn, i = _evaluate(x, y_avg, w_vals)
    return x, fn, y_avg, y_vals, w_vals, fitParams, i
197318
def resample(self, data, mask=None, omega=None):
        
        if not isinstance(data, list):
            assert isinstance(data, tuple) and len(data) == 2, \
                "datas must be an (x,y) tuple or a list of such tuples"
            data = [data]

        if mask is None:
            mask = [np.ones(y.shape, dtype=bool) for x, y in data]

        # Resample auxiliary variables if they are not given
        if omega is None:
            omega = self._resample_auxiliary_variables(data)

        # Make copies of parameters (for sample collection in calling methods)
        self.A = self.A.copy()
        self.b = self.b.copy()

        D = self.D_in
        for n in range(self.D_out):
            # Resample C_{n,:} given z, omega[:,n], and kappa[:,n]
            prior_Sigma = np.zeros((D + 1, D + 1))
            prior_Sigma[:D, :D] = self.sigmasq_A[n]
            prior_Sigma[D, D] = self.sigmasq_b[n]
            prior_J = np.linalg.inv(prior_Sigma)

            prior_h = prior_J.dot(np.concatenate((self.mu_A[n], [self.mu_b[n]])))

            lkhd_h = np.zeros(D + 1)
            lkhd_J = np.zeros((D + 1, D + 1))

            for d, m, o in zip(data, mask, omega):
                if isinstance(d, tuple):
                    x, y = d
                else:
                    x, y = d[:, :D], d[:, D:]
                augx = np.hstack((x, np.ones((x.shape[0], 1))))
                J = o * m
                h = self.kappa_func(y) * m

                lkhd_J += (augx * J[:, n][:, None]).T.dot(augx)
                lkhd_h += h[:, n].T.dot(augx)

            post_h = prior_h + lkhd_h
            post_J = prior_J + lkhd_J

            joint_sample = sample_gaussian(J=post_J, h=post_h)
            self.A[n, :] = joint_sample[:D]
            self.b[n] = joint_sample[D]
1122410
def region(self, rect):
        
        box = (int(rect[0]), int(rect[1]), int(rect[0]) + int(rect[2]),
               int(rect[1]) + int(rect[3]))
        if box[2] > self.img.size[0] or box[3] > self.img.size[1]:
            raise errors.RectangleError("Region out-of-bounds")
        self.img = self.img.crop(box)
        return self
949733
function resample_hermite(canvas, W, H, W2, H2){
	var time1 = Date.now();
	W2 = Math.round(W2);
	H2 = Math.round(H2);
	var img = canvas.getContext("2d").getImageData(0, 0, W, H);
	var img2 = canvas.getContext("2d").getImageData(0, 0, W2, H2);
	var data = img.data;
	var data2 = img2.data;
	var ratio_w = W / W2;
	var ratio_h = H / H2;
	var ratio_w_half = Math.ceil(ratio_w/2);
	var ratio_h_half = Math.ceil(ratio_h/2);
	
	for(var j = 0; j < H2; j++){
		for(var i = 0; i < W2; i++){
			var x2 = (i + j*W2) * 4;
			var weight = 0;
			var weights = 0;
			var weights_alpha = 0;
			var gx_r = gx_g = gx_b = gx_a = 0;
			var center_y = (j + 0.5) * ratio_h;
			for(var yy = Math.floor(j * ratio_h); yy < (j + 1) * ratio_h; yy++){
				var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
				var center_x = (i + 0.5) * ratio_w;
				var w0 = dy*dy //pre-calc part of w
				for(var xx = Math.floor(i * ratio_w); xx < (i + 1) * ratio_w; xx++){
					var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
					var w = Math.sqrt(w0 + dx*dx);
					if(w >= -1 && w <= 1){
						//hermite filter
						weight = 2 * w*w*w - 3*w*w + 1;
						if(weight > 0){
							dx = 4*(xx + yy*W);
							//alpha
							gx_a += weight * data[dx + 3];
							weights_alpha += weight;
							//colors
							if(data[dx + 3] < 255)
								weight = weight * data[dx + 3] / 250;
							gx_r += weight * data[dx];
							gx_g += weight * data[dx + 1];
							gx_b += weight * data[dx + 2];
							weights += weight;
							}
						}
					}		
				}
			data2[x2]     = gx_r / weights;
			data2[x2 + 1] = gx_g / weights;
			data2[x2 + 2] = gx_b / weights;
			data2[x2 + 3] = gx_a / weights_alpha;
			}
		}
	log( "pong-io","hermite = "+(Math.round(Date.now() - time1)/1000)+" s");
	canvas.getContext("2d").clearRect(0, 0, Math.max(W, W2), Math.max(H, H2));
	canvas.width = W2;
	canvas.height = H2;
	canvas.getContext("2d").putImageData(img2, 0, 0);
}
23471
def crop_2dimage(img, beg_coords, end_coords):
    """"""

    cropped_img = img[
                  beg_coords[0]:end_coords[0],
                  beg_coords[1]:end_coords[1],
                  ]

    return cropped_img
148654
def _grid_sample(x:TensorImage, coords:FlowField, mode:str='bilinear', padding_mode:str='reflection', remove_out:bool=True)->TensorImage:
    ""
    coords = coords.flow.permute(0, 3, 1, 2).contiguous().permute(0, 2, 3, 1) # optimize layout for grid_sample
    if mode=='bilinear': # hack to get smoother downwards resampling
        mn,mx = coords.min(),coords.max()
        # max amount we're affine zooming by (>1 means zooming in)
        z = 1/(mx-mn).item()*2
        # amount we're resizing by, with 100% extra margin
        d = min(x.shape[1]/coords.shape[1], x.shape[2]/coords.shape[2])/2
        # If we're resizing up by >200%, and we're zooming less than that, interpolate first
        if d>1 and d>z: x = F.interpolate(x[None], scale_factor=1/d, mode='area')[0]
    return F.grid_sample(x[None], coords, mode=mode, padding_mode=padding_mode)[0]
263327
def get_sub_area(area, xslice, yslice):
    """"""
    new_area_extent = ((area.pixel_upper_left[0] +
                        (xslice.start - 0.5) * area.pixel_size_x),
                       (area.pixel_upper_left[1] -
                        (yslice.stop - 0.5) * area.pixel_size_y),
                       (area.pixel_upper_left[0] +
                        (xslice.stop - 0.5) * area.pixel_size_x),
                       (area.pixel_upper_left[1] -
                        (yslice.start - 0.5) * area.pixel_size_y))

    return AreaDefinition(area.area_id, area.name,
                          area.proj_id, area.proj_dict,
                          xslice.stop - xslice.start,
                          yslice.stop - yslice.start,
                          new_area_extent)
21687
def vqa_v2_preprocess_image(
    image,
    height,
    width,
    mode,
    resize_side=512,
    distort=True,
    image_model_fn="resnet_v1_152",
):
  """"""

  image = tf.image.convert_image_dtype(image, dtype=tf.float32)
  assert resize_side > 0
  if resize_side:
    image = _aspect_preserving_resize(image, resize_side)
  if mode == tf.estimator.ModeKeys.TRAIN:
    image = tf.random_crop(image, [height, width, 3])
  else:
    # Central crop, assuming resize_height > height, resize_width > width.
    image = tf.image.resize_image_with_crop_or_pad(image, height, width)

  image = tf.clip_by_value(image, 0.0, 1.0)

  if mode == tf.estimator.ModeKeys.TRAIN and distort:
    image = _flip(image)
    num_distort_cases = 4
    # pylint: disable=unnecessary-lambda
    image = _apply_with_random_selector(
        image, lambda x, ordering: _distort_color(x, ordering),
        num_cases=num_distort_cases)

  if image_model_fn.startswith("resnet_v1"):
    # resnet_v1 uses vgg preprocessing
    image = image * 255.
    image = _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])
  elif image_model_fn.startswith("resnet_v2"):
    # resnet v2 uses inception preprocessing
    image = tf.subtract(image, 0.5)
    image = tf.multiply(image, 2.0)

  return image
769730
def fit(self, X, y):
    '''
    '''
    X, y = self._prepare_inputs(X, y, ensure_min_samples=2)
    unique_classes, y = np.unique(y, return_inverse=True)
    n, d = X.shape
    num_classes = len(unique_classes)

    if self.num_dims is None:
      dim = d
    else:
      if not 0 < self.num_dims <= d:
        raise ValueError('Invalid num_dims, must be in [1,%d]' % d)
      dim = self.num_dims

    if self.k is None:
      k = min(7, d - 1)
    elif self.k >= d:
      warnings.warn('Chosen k (%d) too large, using %d instead.' % (self.k,d-1))
      k = d - 1
    else:
      k = int(self.k)
    tSb = np.zeros((d,d))
    tSw = np.zeros((d,d))

    for c in xrange(num_classes):
      Xc = X[y==c]
      nc = Xc.shape[0]

      # classwise affinity matrix
      dist = pairwise_distances(Xc, metric='l2', squared=True)
      # distances to k-th nearest neighbor
      k = min(k, nc - 1)
      sigma = np.sqrt(np.partition(dist, k, axis=0)[:, k])

      local_scale = np.outer(sigma, sigma)
      with np.errstate(divide='ignore', invalid='ignore'):
        A = np.exp(-dist/local_scale)
        A[local_scale==0] = 0

      G = Xc.T.dot(A.sum(axis=0)[:,None] * Xc) - Xc.T.dot(A).dot(Xc)
      tSb += G/n + (1-nc/n)*Xc.T.dot(Xc) + _sum_outer(Xc)/n
      tSw += G/nc

    tSb -= _sum_outer(X)/n - tSw

    # symmetrize
    tSb = (tSb + tSb.T) / 2
    tSw = (tSw + tSw.T) / 2

    vals, vecs = _eigh(tSb, tSw, dim)
    order = np.argsort(-vals)[:dim]
    vals = vals[order].real
    vecs = vecs[:,order]

    if self.embedding_type == 'weighted':
       vecs *= np.sqrt(vals)
    elif self.embedding_type == 'orthonormalized':
       vecs, _ = np.linalg.qr(vecs)

    self.transformer_ = vecs.T
    return self