Encode the given tensor to given image shape.
192998
def encode_to_shape(inputs, shape, scope):
  """"""
  with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
    w, h = shape[1], shape[2]
    x = inputs
    x = tfl.flatten(x)
    x = tfl.dense(x, w * h, activation=None, name="enc_dense")
    x = tf.reshape(x, (-1, w, h, 1))
    return x
854263
def export(_):
  FLAGS = tf.app.flags.FLAGS

  """"""
  #with tf.Graph().as_default():
  tf.reset_default_graph()

  def preprocess_image(image_buffer):
    """Preprocess JPEG encoded bytes to 3D float Tensor."""

    # Decode the string as an RGB JPEG.
    # Note that the resulting image contains an unknown height and width
    # that is set dynamically by decode_jpeg. In other words, the height
    # and width of image is unknown at compile-time.
    image = tf.image.decode_jpeg(image_buffer, channels=3)
    # After this point, all image pixels reside in [0,1)
    # until the very end, when they're rescaled to (-1, 1).  The various
    # adjust_* ops all require this range for dtype float.
    image = tf.image.convert_image_dtype(image, dtype=tf.float32)
    # Crop the central region of the image with an area containing 87.5% of
    # the original image.
    image = tf.image.central_crop(image, central_fraction=0.875)
    # Resize the image to the original height and width.
    image = tf.expand_dims(image, 0)
    image = tf.image.resize_bilinear(
        image, [FLAGS.image_size, FLAGS.image_size], align_corners=False)
    image = tf.squeeze(image, [0])
    # Finally, rescale to [-1,1] instead of [0, 1)
    image = tf.subtract(image, 0.5)
    image = tf.multiply(image, 2.0)
    return image

  # Get images and labels from the dataset.
  jpegs = tf.placeholder(tf.string, [None], name='jpegs')
  images = tf.map_fn(preprocess_image, jpegs, dtype=tf.float32)
  labels = tf.placeholder(tf.int32, [None], name='labels')

  # Number of classes in the Dataset label set plus 1.
  # Label 0 is reserved for an (unused) background class.
  dataset = ImagenetData(subset=FLAGS.subset)

  num_classes = dataset.num_classes() + 1

  # Build a Graph that computes the logits predictions from the
  # inference model.
  logits, _ = inception.inference(images, num_classes)

  # Calculate predictions.
  top_1_op = tf.nn.in_top_k(logits, labels, 1)
  top_5_op = tf.nn.in_top_k(logits, labels, 5)

  # Restore the moving average version of the learned variables for eval.
  variable_averages = tf.train.ExponentialMovingAverage(
      inception.MOVING_AVERAGE_DECAY)
  variables_to_restore = variable_averages.variables_to_restore()
  saver = tf.train.Saver(variables_to_restore)

  with tf.Session() as sess:
    ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
    if not ckpt or not ckpt.model_checkpoint_path:
      raise Exception("No checkpoint file found at: {}".format(FLAGS.train_dir))
    print("ckpt.model_checkpoint_path: {0}".format(ckpt.model_checkpoint_path))

    saver.restore(sess, ckpt.model_checkpoint_path)

    # Assuming model_checkpoint_path looks something like:
    #   /my-favorite-path/imagenet_train/model.ckpt-0,
    # extract global_step from it.
    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
    print('Successfully loaded model from %s at step=%s.' %
          (ckpt.model_checkpoint_path, global_step))

    print("Exporting saved_model to: {}".format(FLAGS.export_dir))
    # exported signatures defined in code
    signatures = {
      tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: {
        'inputs': { 'jpegs': jpegs, 'labels': labels },
        'outputs': { 'top_5_acc': top_5_op },
        'method_name': tf.saved_model.signature_constants.PREDICT_METHOD_NAME
      }
    }
    TFNode.export_saved_model(sess,
                              FLAGS.export_dir,
                              tf.saved_model.tag_constants.SERVING,
                              signatures)
    print("Exported saved_model")
629246
def encode_numpy(array):
    '''

    '''
    return {'data' : base64.b64encode(array.data).decode('utf8'),
            'type' : array.dtype.name,
            'shape': array.shape}
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
1183602
def get_image(verbose=False):
  """"""
  base_data = tf.constant(image_data(verbose=verbose))
  base_image = tf.image.decode_image(base_data, channels=3)
  base_image.set_shape((IMAGE_HEIGHT, IMAGE_WIDTH, 3))
  parsed_image = tf.Variable(base_image, name='image', dtype=tf.uint8)
  return parsed_image
233995
def stretch(image, mask=None):
    '''
    '''
    image = np.array(image, float)
    if np.product(image.shape) == 0:
        return image
    if mask is None:
        minval = np.min(image)
        maxval = np.max(image)
        if minval == maxval:
            if minval < 0:
                return np.zeros_like(image)
            elif minval > 1:
                return np.ones_like(image)
            return image
        else:
            return (image - minval) / (maxval - minval)
    else:
        significant_pixels = image[mask]
        if significant_pixels.size == 0:
            return image
        minval = np.min(significant_pixels)
        maxval = np.max(significant_pixels)
        if minval == maxval:
            transformed_image = minval
        else:
            transformed_image = ((significant_pixels - minval) /
                                 (maxval - minval))
        result = image.copy()
        image[mask] = transformed_image
        return image
19748
public static void imageToTensor(Planar<GrayF32> input , Tensor_F32 output , int miniBatch) {
		if( input.isSubimage())
			throw new RuntimeException("Subimages not accepted");
		if( output.getDimension() != 4 )
			throw new IllegalArgumentException("Output should be 4-DOF.  batch + spatial (channel,height,width)");
		if( output.length(1) != input.getNumBands() )
			throw new IllegalArgumentException("Number of bands don't match");
		if( output.length(2) != input.getHeight() )
			throw new IllegalArgumentException("Spatial height doesn't match");
		if( output.length(3) != input.getWidth() )
			throw new IllegalArgumentException("Spatial width doesn't match");

		for (int i = 0; i < input.getNumBands(); i++) {
			GrayF32 band = input.getBand(i);
			int indexOut = output.idx(miniBatch,i,0,0);

			int length = input.width*input.height;
			System.arraycopy(band.data, 0,output.d,indexOut,length);
		}
	}
600860
def convert_cell_to_img(t, padding=16):
    """"""
    std = torch.Tensor([0.229, 0.224, 0.225]).reshape(-1, 1, 1)
    mu = torch.Tensor([0.485, 0.456, 0.406]).reshape(-1, 1, 1)
    output = t.mul(std)
    output.add_(mu)
    img = to_pil_image(output)
    w, h = img.size
    return img.crop((padding, padding, w - padding, h - padding))
1238132
def use_to_ned(tensor):
    '''
    
    '''
    return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE)
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
61576
def uint32_to_uint8(cls, img):
        
        return np.flipud(img.view(dtype=np.uint8).reshape(img.shape + (4,)))
120061
def export_to_tf_tensor(self, x, laid_out_x):
    
    return self.combine_slices(laid_out_x.all_slices, x.shape)
849516
def reshape_fortran(tensor, shape):
    
    return tensor.T.reshape(tuple(reversed(shape))).T
1316539
def convert_to_odl(image):
    """"""

    shape = image.shape

    if len(shape) == 2:
        space = odl.uniform_discr([0, 0], shape, shape)
    elif len(shape) == 3:
        d = shape[2]
        shape = shape[:2]
        image = np.transpose(image, (2, 0, 1))
        space = odl.uniform_discr([0, 0], shape, shape) ** d

    image = space.element(image)

    return image
1075084
def _get_dense_tensor(self, inputs, weight_collections=None, trainable=None):
    """"""
    del weight_collections, trainable  # Unused.
    m = module.Module(self.module_spec, trainable=False)
    images = inputs.get(self)
    return m({"images": images})
333007
def get_input_shape(sym, proto_obj):
    """"""
    arg_params = proto_obj.arg_dict
    aux_params = proto_obj.aux_dict

    model_input_shape = [data[1] for data  in proto_obj.model_metadata.get('input_tensor_data')]
    data_names = [data[0] for data  in proto_obj.model_metadata.get('input_tensor_data')]

    # creating dummy inputs
    inputs = []
    for  in_shape in model_input_shape:
        inputs.append(nd.ones(shape=in_shape))

    data_shapes = []
    for idx, input_name in enumerate(data_names):
        data_shapes.append((input_name, inputs[idx].shape))

    ctx = context.cpu()
    # create a module
    mod = module.Module(symbol=sym, data_names=data_names, context=ctx, label_names=None)
    mod.bind(for_training=False, data_shapes=data_shapes, label_shapes=None)
    mod.set_params(arg_params=arg_params, aux_params=aux_params)

    data_forward = []
    for idx, input_name in enumerate(data_names):
        val = inputs[idx]
        data_forward.append(val)

    mod.forward(io.DataBatch(data_forward))
    result = mod.get_outputs()[0].asnumpy()

    return result.shape
220916
def to_tensor(self):
    """"""
    a_shape = shape_list(self.a)
    b_shape = shape_list(self.b)
    inner_dim = b_shape[1]
    result_dim = b_shape[0]
    flat_a = tf.reshape(self.a, [-1, inner_dim])
    product = tf.matmul(flat_a, self.b, transpose_b=True)
    product_shape = a_shape[:-1] + [result_dim]
    product = tf.reshape(product, product_shape)
    product.set_shape(self.a.get_shape().as_list()[:-1] +
                      [self.b.get_shape()[0]])
    return product