transform into mxnet tensor,
    subtract pixel size and transform to correct format
    :param im: [height, width, channel] in BGR
    :param mean: [RGB pixel mean]
    :param std: [RGB pixel std var]
    :return: [batch, channel, height, width]
483165
def transform(im, mean, std):
    
    im_tensor = np.zeros((3, im.shape[0], im.shape[1]))
    for i in range(3):
        im_tensor[i, :, :] = (im[:, :, 2 - i] - mean[i]) / std[i]
    return im_tensor
618608
def dummy_batch(m: nn.Module, size:tuple=(64,64))->Tensor:
    ""
    ch_in = in_channels(m)
    return one_param(m).new(1, ch_in, *size).requires_grad_(False).uniform_(-1.,1.)
439776
def convert_batchnorm(builder, layer, input_names, output_names, keras_layer):
    

    # Get input and output names
    input_name, output_name = (input_names[0], output_names[0])

    axis = keras_layer.axis
    nb_channels = keras_layer.input_shape[axis]

    # Set parameters
    # Parameter arrangement in Keras: gamma, beta, mean, variance
    idx = 0
    gamma, beta = None, None
    if keras_layer.scale:
        gamma = keras_layer.get_weights()[idx]
        idx += 1
    if keras_layer.center:
        beta = keras_layer.get_weights()[idx]
        idx += 1
    mean = keras_layer.get_weights()[idx]
    std = keras_layer.get_weights()[idx+1]

    gamma = _np.ones(mean.shape) if gamma is None else gamma
    beta = _np.zeros(mean.shape) if beta is None else beta

    # compute adjusted parameters
    variance = std * std
    f = 1.0 / _np.sqrt(std + keras_layer.epsilon)
    gamma1 = gamma*f
    beta1 = beta - gamma*mean*f
    mean[:] = 0.0 #mean
    variance[:] = 1.0 - .00001 #stddev

    builder.add_batchnorm(
        name = layer,
        channels = nb_channels,
        gamma = gamma1,
        beta = beta1,
        mean = mean,
        variance = variance,
        input_name = input_name,
        output_name = output_name)
1061087
def subtract_imagenet_mean_preprocess_batch(batch):
    """"""
    batch = F.swapaxes(batch,0, 1)
    (r, g, b) = F.split(batch, num_outputs=3, axis=0)
    r = r - 123.680
    g = g - 116.779
    b = b - 103.939
    batch = F.concat(b, g, r, dim=0)
    batch = F.swapaxes(batch,0, 1)
    return batch
413589
def transformer(data, label):
    
    data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE)
    data = mx.nd.transpose(data, (2, 0, 1))
    data = data.astype(np.float32) / 128.0 - 1
    return data, label
698207
def _scaleTo8bit(self, img):
        '''
        
        '''
        r = scaleSignalCutParams(img, 0.02)  # , nSigma=3)
        self.signal_ranges.append(r)
        return toUIntArray(img, dtype=np.uint8, range=r)
1064209
def img2img_transformer2d_n31():
  """"""
  hparams = img2img_transformer2d_base()
  hparams.batch_size = 1
  hparams.num_encoder_layers = 6
  hparams.num_decoder_layers = 12
  hparams.num_heads = 8
  hparams.query_shape = (16, 32)
  hparams.memory_flange = (16, 32)
  return hparams
27848
def _get_fixed_params(im):
    
    
    p = Parameters()
    
    if not isinstance(im, np.ndarray):
        return p
    
    # Dimension of the inputs
    p.FixedImageDimension = im.ndim
    p.MovingImageDimension = im.ndim
    
    # Always write result, so I can verify
    p.WriteResultImage = True
    
    # How to write the result
    tmp = DTYPE_NP2ITK[im.dtype.name]
    p.ResultImagePixelType = tmp.split('_')[-1].lower()
    p.ResultImageFormat = "mhd"
    
    # Done
    return p
837953
def get_bytes_to_image_callback(image_dims=(224, 224)):
    """"""
    from keras.preprocessing import image
    import numpy as np
    from PIL import Image
    from io import BytesIO

    def preprocess_image_bytes(data_bytes):
        """Process image bytes for ImageNet."""
        try:
            img = Image.open(BytesIO(data_bytes))  # open image
        except OSError as e:
            raise ValueError('Please provide a raw image')
        img = img.resize(image_dims, Image.ANTIALIAS)  # model requires 224x224 pixels
        x = image.img_to_array(img)  # convert image to numpy array
        x = np.expand_dims(x, axis=0)  # model expects dim 0 to be iterable across images
        return x
    return preprocess_image_bytes
241612
def convert_mean(binaryproto_fname, output=None):
    
    mean_blob = caffe_parser.caffe_pb2.BlobProto()
    with open(binaryproto_fname, 'rb') as f:
        mean_blob.ParseFromString(f.read())

    img_mean_np = np.array(mean_blob.data)
    img_mean_np = img_mean_np.reshape(
        mean_blob.channels, mean_blob.height, mean_blob.width
    )
    # swap channels from Caffe BGR to RGB
    img_mean_np[[0, 2], :, :] = img_mean_np[[2, 0], :, :]
    nd = mx.nd.array(img_mean_np)
    if output is not None:
        mx.nd.save(output, {"mean_image": nd})
    return nd
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)
1203370
function convertFace(imgIn, imgOut, faceIdx) {
	var inPix = shimImgData(imgIn),
				outPix = shimImgData(imgOut),
				faceSize = imgOut.width,
				pi = Math.PI,
				pi_2 = pi/2;

	for(var xOut=0;xOut<faceSize;xOut++) {
			for(var yOut=0;yOut<faceSize;yOut++) {

			var xyz = outImgToXYZ(xOut, yOut, faceIdx, faceSize);
			var theta = Math.atan2(xyz.y, xyz.x); // range -pi to pi
			var r = Math.hypot(xyz.x,xyz.y);
			var phi = Math.atan2(xyz.z,r); // range -pi/2 to pi/2

			// source img coords
			var uf = 0.5 * imgIn.width * (theta + pi) / pi;
			var vf = 0.5 * imgIn.width * (pi_2 - phi) / pi;

			// Use bilinear interpolation between the four surrounding pixels
			var ui = Math.floor(uf);  // coord of pixel to bottom left
			var vi = Math.floor(vf);
			var u2 = ui+1;       // coords of pixel to top right
			var v2 = vi+1;
			var mu = uf-ui;      // fraction of way across pixel
			var nu = vf-vi;

			// Pixel values of four corners
			var A = inPix.getPx(ui % imgIn.width, clip(vi, 0, imgIn.height-1));
			var B = inPix.getPx(u2 % imgIn.width, clip(vi, 0, imgIn.height-1));
			var C = inPix.getPx(ui % imgIn.width, clip(v2, 0, imgIn.height-1));
			var D = inPix.getPx(u2 % imgIn.width, clip(v2, 0, imgIn.height-1));

			// interpolate
			var rgb = {
			  r:A[0]*(1-mu)*(1-nu) + B[0]*(mu)*(1-nu) + C[0]*(1-mu)*nu+D[0]*mu*nu,
			  g:A[1]*(1-mu)*(1-nu) + B[1]*(mu)*(1-nu) + C[1]*(1-mu)*nu+D[1]*mu*nu,
			  b:A[2]*(1-mu)*(1-nu) + B[2]*(mu)*(1-nu) + C[2]*(1-mu)*nu+D[2]*mu*nu
			};

			rgb.r=Math.round(rgb.r);
			rgb.g=Math.round(rgb.g);
			rgb.b=Math.round(rgb.b);

			outPix.setPx(xOut, yOut, rgb);

		} // for(var yOut=0;yOut<faceSize;yOut++) {...}
	 } // for(var xOut=0;xOut<faceSize;xOut++) {...}
}
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)
383396
def mse(exp, obs):
    
    assert len(exp) == len(obs)
    return numpy.mean((numpy.array(exp) - numpy.array(obs)) ** 2)
675366
def ct2mu(im):
    ''' 
    '''

    # convert nans to -1024 for the HU values only
    im[np.isnan(im)] = -1024
    # constants
    muwater  = 0.096
    mubone   = 0.172
    rhowater = 0.184
    rhobone  = 0.428
    uim = np.zeros(im.shape, dtype=np.float32)
    uim[im<=0] = muwater * ( 1+im[im<=0]*1e-3 )
    uim[im> 0] = muwater+im[im>0]*(rhowater*(mubone-muwater)/(1e3*(rhobone-rhowater)))
    # remove negative values
    uim[uim<0] = 0
    return uim
273559
def _normalize_batch(b:Tuple[Tensor,Tensor], mean:FloatTensor, std:FloatTensor, do_x:bool=True, do_y:bool=False)->Tuple[Tensor,Tensor]:
    ""
    x,y = b
    mean,std = mean.to(x.device),std.to(x.device)
    if do_x: x = normalize(x,mean,std)
    if do_y and len(y.shape) == 4: y = normalize(y,mean,std)
    return x,y
463841
def get_image(self, img, is_train):
        """"""
        img_arr = mx.image.imread(img)
        img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
        return img_arr