Python numpy.squeeze() Examples
The following are 30 code examples for showing how to use numpy.squeeze(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: cat-bbs Author: aleju File: common.py License: MIT License | 6 votes |
def draw_heatmap(img, heatmap, alpha=0.5): """Draw a heatmap overlay over an image.""" assert len(heatmap.shape) == 2 or \ (len(heatmap.shape) == 3 and heatmap.shape[2] == 1) assert img.dtype in [np.uint8, np.int32, np.int64] assert heatmap.dtype in [np.float32, np.float64] if img.shape[0:2] != heatmap.shape[0:2]: heatmap_rs = np.clip(heatmap * 255, 0, 255).astype(np.uint8) heatmap_rs = ia.imresize_single_image( heatmap_rs[..., np.newaxis], img.shape[0:2], interpolation="nearest" ) heatmap = np.squeeze(heatmap_rs) / 255.0 cmap = plt.get_cmap('jet') heatmap_cmapped = cmap(heatmap) heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2) heatmap_cmapped = heatmap_cmapped * 255 mix = (1-alpha) * img + alpha * heatmap_cmapped mix = np.clip(mix, 0, 255).astype(np.uint8) return mix
Example 2
Project: neural-fingerprinting Author: StephanZheng File: utils.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def cleverhans_attack_wrapper(cleverhans_attack_fn, reset=True): def attack(a): session = tf.Session() with session.as_default(): model = RVBCleverhansModel(a) adversarial_image = cleverhans_attack_fn(model, session, a) adversarial_image = np.squeeze(adversarial_image, axis=0) if reset: # optionally, reset to ignore other adversarials # found during the search a._reset() # run predictions to make sure the returned adversarial # is taken into account min_, max_ = a.bounds() adversarial_image = np.clip(adversarial_image, min_, max_) a.predictions(adversarial_image) return attack
Example 3
Project: models Author: kipoi File: dataloader.py License: MIT License | 6 votes |
def __getitem__(self, idx): if self.fasta_extractor is None: self.fasta_extractor = FastaExtractor(self.fasta_file) interval = self.bt[idx] if interval.stop - interval.start != self.SEQ_WIDTH: raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}". format(self.SEQ_WIDTH, interval.stop - interval.start)) # Run the fasta extractor seq = np.squeeze(self.fasta_extractor([interval]), axis=0) return { "inputs": {"dna": seq}, "metadata": { "ranges": GenomicRanges.from_interval(interval) } }
Example 4
Project: models Author: kipoi File: dataloader.py License: MIT License | 6 votes |
def __getitem__(self, idx): if self.fasta_extractor is None: self.fasta_extractor = FastaExtractor(self.fasta_file) interval = self.bt[idx] if interval.stop - interval.start != self.SEQ_WIDTH: raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}". format(self.SEQ_WIDTH, interval.stop - interval.start)) # Run the fasta extractor seq = np.squeeze(self.fasta_extractor([interval]), axis=0) return { "inputs": {"dna": seq}, "metadata": { "ranges": GenomicRanges.from_interval(interval) } }
Example 5
Project: models Author: kipoi File: dataloader.py License: MIT License | 6 votes |
def __getitem__(self, idx): if self.fasta_extractor is None: self.fasta_extractor = FastaExtractor(self.fasta_file) interval = self.bt[idx] if interval.stop - interval.start != self.SEQ_WIDTH: raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}". format(self.SEQ_WIDTH, interval.stop - interval.start)) # Run the fasta extractor seq = np.squeeze(self.fasta_extractor([interval]), axis=0) return { "inputs": {"dna": seq}, "metadata": { "ranges": GenomicRanges.from_interval(interval) } }
Example 6
Project: models Author: kipoi File: dataloader.py License: MIT License | 6 votes |
def __getitem__(self, idx): if self.fasta_extractor is None: self.fasta_extractor = FastaExtractor(self.fasta_file) interval = self.bt[idx] if interval.stop - interval.start != self.SEQ_WIDTH: raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}". format(self.SEQ_WIDTH, interval.stop - interval.start)) # Run the fasta extractor seq = np.squeeze(self.fasta_extractor([interval]), axis=0) return { "inputs": {"dna": seq}, "metadata": { "ranges": GenomicRanges.from_interval(interval) } }
Example 7
Project: models Author: kipoi File: dataloader.py License: MIT License | 6 votes |
def __getitem__(self, idx): if self.fasta_extractor is None: self.fasta_extractor = FastaExtractor(self.fasta_file) interval = self.bt[idx] if interval.stop - interval.start != self.SEQ_WIDTH: raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}". format(self.SEQ_WIDTH, interval.stop - interval.start)) # Run the fasta extractor seq = np.squeeze(self.fasta_extractor([interval]), axis=0) return { "inputs": {"dna": seq}, "metadata": { "ranges": GenomicRanges.from_interval(interval) } }
Example 8
Project: neuropythy Author: noahbenson File: core.py License: GNU Affero General Public License v3.0 | 6 votes |
def apply_affine(aff, coords): ''' apply_affine(affine, coords) yields the result of applying the given affine transformation to the given coordinate or coordinates. This function expects coords to be a (dims X n) matrix but if the first dimension is neither 2 nor 3, coords.T is used; i.e.: apply_affine(affine3x3, coords2xN) ==> newcoords2xN apply_affine(affine4x4, coords3xN) ==> newcoords3xN apply_affine(affine3x3, coordsNx2) ==> newcoordsNx2 (for N != 2) apply_affine(affine4x4, coordsNx3) ==> newcoordsNx3 (for N != 3) ''' if aff is None: return coords (coords,tr) = (np.asanyarray(coords), False) if len(coords.shape) == 1: return np.squeeze(apply_affine(np.reshape(coords, (-1,1)), aff)) elif len(coords.shape) > 2: raise ValueError('cannot apply affine to ND-array for N > 2') if len(coords) == 2: aff = to_affine(aff, 2) elif len(coords) == 3: aff = to_affine(aff, 3) else: (coords,aff,tr) = (coords.T, to_affine(aff, coords.shape[1]), True) r = np.dot(aff, np.vstack([coords, np.ones([1,coords.shape[1]])]))[:-1] return r.T if tr else r
Example 9
Project: dynamic-training-with-apache-mxnet-on-aws Author: awslabs File: gradcam.py License: Apache License 2.0 | 6 votes |
def visualize(net, preprocessed_img, orig_img, conv_layer_name): # Returns grad-cam heatmap, guided grad-cam, guided grad-cam saliency imggrad = get_image_grad(net, preprocessed_img) conv_out, conv_out_grad = get_conv_out_grad(net, preprocessed_img, conv_layer_name=conv_layer_name) cam = get_cam(imggrad, conv_out) ggcam = get_guided_grad_cam(cam, imggrad) img_ggcam = grad_to_image(ggcam) img_heatmap = get_img_heatmap(orig_img, cam) ggcam_gray = to_grayscale(ggcam) img_ggcam_gray = np.squeeze(grad_to_image(ggcam_gray)) return img_heatmap, img_ggcam, img_ggcam_gray
Example 10
Project: DOTA_models Author: ringringyi File: seq2seq_attention_model.py License: Apache License 2.0 | 6 votes |
def decode_topk(self, sess, latest_tokens, enc_top_states, dec_init_states): """Return the topK results and new decoder states.""" feed = { self._enc_top_states: enc_top_states, self._dec_in_state: np.squeeze(np.array(dec_init_states)), self._abstracts: np.transpose(np.array([latest_tokens])), self._abstract_lens: np.ones([len(dec_init_states)], np.int32)} results = sess.run( [self._topk_ids, self._topk_log_probs, self._dec_out_state], feed_dict=feed) ids, probs, states = results[0], results[1], results[2] new_states = [s for s in states] return ids, probs, new_states
Example 11
Project: Deep_Learning_Weather_Forecasting Author: BruceBinBoxing File: competition_model_class.py License: Apache License 2.0 | 6 votes |
def predict(self, batch_inputs, batch_ruitu): assert batch_ruitu.shape[0] == batch_inputs.shape[0], 'Shape Error' assert batch_inputs.shape[1] == 28 and batch_inputs.shape[2] == 10 and batch_inputs.shape[3] == 9, 'Error! Obs input shape must be (None, 28,10,9)' assert batch_ruitu.shape[1] == 37 and batch_ruitu.shape[2] == 10 and batch_ruitu.shape[3] == 29, 'Error! Ruitu input shape must be (None, 37,10, 29)' #all_pred={} pred_result_list = [] for i in range(10): #print('Predict for station: 9000{}'.format(i+1)) result = self.model.predict(x=[batch_inputs[:,:,i,:], batch_ruitu[:,:,i,:]]) result = np.squeeze(result, axis=0) #all_pred[i] = result pred_result_list.append(result) #pass pred_result = np.stack(pred_result_list, axis=0) #return all_pred, pred_result print('Predict shape (10,37,3) means (stationID, timestep, features). Features include: t2m, rh2m and w10m') self.pred_result = pred_result return pred_result
Example 12
Project: Deep_Learning_Weather_Forecasting Author: BruceBinBoxing File: competition_model_class.py License: Apache License 2.0 | 6 votes |
def predict(self, batch_inputs, batch_ruitu, batch_ids): #assert batch_ruitu.shape[0] == batch_inputs.shape[0], 'Shape Error' #assert batch_inputs.shape[1] == 28 and batch_inputs.shape[2] == 10 and batch_inputs.shape[3] == 9, 'Error! Obs input shape must be (None, 28,10,9)' #assert batch_ruitu.shape[1] == 37 and batch_ruitu.shape[2] == 10 and batch_ruitu.shape[3] == 29, 'Error! Ruitu input shape must be (None, 37,10, 29)' pred_result_list = [] for i in range(10): #print('Predict for station: 9000{}'.format(i+1)) result = self.model.predict(x=[batch_inputs[:,:,i,:], batch_ruitu[:,:,i,:], batch_ids[:,:,i]]) result = np.squeeze(result, axis=0) #all_pred[i] = result pred_result_list.append(result) #pass pred_result = np.stack(pred_result_list, axis=0) #return all_pred, pred_result print('Predict shape (10,37,3) means (stationID, timestep, features). Features include: t2m, rh2m and w10m') self.pred_result = pred_result return pred_result
Example 13
Project: fine-lm Author: akzaidi File: metrics.py License: MIT License | 6 votes |
def set_recall(predictions, labels, weights_fn=common_layers.weights_nonzero): """Recall of set predictions. Args: predictions : A Tensor of scores of shape [batch, nlabels]. labels: A Tensor of int32s giving true set elements, of shape [batch, seq_length]. weights_fn: A function to weight the elements. Returns: hits: A Tensor of shape [batch, nlabels]. weights: A Tensor of shape [batch, nlabels]. """ with tf.variable_scope("set_recall", values=[predictions, labels]): labels = tf.squeeze(labels, [2, 3]) weights = weights_fn(labels) labels = tf.one_hot(labels, predictions.shape[-1]) labels = tf.reduce_max(labels, axis=1) labels = tf.cast(labels, tf.bool) return tf.to_float(tf.equal(labels, predictions)), weights
Example 14
Project: EXOSIMS Author: dsavransky File: keplerSTM_indprop.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, x0, mu, epsmult = 4.0, noc = False): #determine number of planets and validate input nplanets = x0.size/6. if (nplanets - np.floor(nplanets) > 0): raise Exception('The length of x0 must be a multiple of 6.') if (mu.size != nplanets): raise Exception('The length of mu must be the length of x0 divided by 6') self.nplanets = int(nplanets) self.mu = np.squeeze(mu) if (self.mu.size == 1): self.mu = np.array(mu) self.epsmult = epsmult if not(noc) and ('EXOSIMS.util.KeplerSTM_C.CyKeplerSTM' in sys.modules): self.havec = True self.x0 = np.squeeze(x0) else: self.havec = False self.updateState(np.squeeze(x0))
Example 15
Project: cat-bbs Author: aleju File: predict_video.py License: MIT License | 5 votes |
def _heatmap_to_rects(self, grid_pred, bb_img): """Convert a heatmap to rectangles / bounding box candidates.""" grid_pred = np.squeeze(grid_pred) # (1, H, W) => (H, W) # remove low activations grid_thresh = grid_pred >= self.heatmap_activation_threshold # find connected components grid_labeled, num_labels = morphology.label( grid_thresh, background=0, connectivity=1, return_num=True ) # for each connected components, # - draw a bounding box around it, # - shrink the bounding box to optimal size # - estimate a score/confidence value bbs = [] for label in range(1, num_labels+1): (yy, xx) = np.nonzero(grid_labeled == label) min_y, max_y = np.min(yy), np.max(yy) min_x, max_x = np.min(xx), np.max(xx) rect = RectangleOnImage(x1=min_x, x2=max_x+1, y1=min_y, y2=max_y+1, shape=grid_labeled) activation = self._rect_to_score(rect, grid_pred) rect_shrunk, activation_shrunk = self._shrink(grid_pred, rect) rect_rs_shrunk = rect_shrunk.on(bb_img) bbs.append((rect_rs_shrunk, activation_shrunk)) return bbs
Example 16
Project: cat-bbs Author: aleju File: train.py License: MIT License | 5 votes |
def generate_video_image(batch_idx, examples, model): """Generate frames for a video of the training progress. Each frame contains N examples shown in a grid. Each example shows the input image and the main heatmap predicted by the model.""" start_time = time.time() #print("A", time.time() - start_time) model.eval() # fw through network inputs, outputs_gt = examples_to_batch(examples, iaa.Noop()) inputs_torch = torch.from_numpy(inputs) inputs_torch = Variable(inputs_torch, volatile=True) if GPU >= 0: inputs_torch = inputs_torch.cuda(GPU) outputs_pred_torch = model(inputs_torch) #print("B", time.time() - start_time) outputs_pred = outputs_pred_torch.cpu().data.numpy() inputs = (inputs * 255).astype(np.uint8).transpose(0, 2, 3, 1) #print("C", time.time() - start_time) heatmaps = [] for i in range(inputs.shape[0]): hm_drawn = draw_heatmap(inputs[i], np.squeeze(outputs_pred[i][0]), alpha=0.5) heatmaps.append(hm_drawn) #print("D", time.time() - start_time) grid = ia.draw_grid(heatmaps, cols=11, rows=6).astype(np.uint8) #grid_rs = misc.imresize(grid, (720-32, 1280-32)) # pad by 42 for the text and to get the image to 720p aspect ratio grid_pad = np.pad(grid, ((0, 42), (0, 0), (0, 0)), mode="constant") grid_pad_text = ia.draw_text( grid_pad, x=grid_pad.shape[1]-220, y=grid_pad.shape[0]-35, text="Batch %05d" % (batch_idx,), color=[255, 255, 255] ) #print("E", time.time() - start_time) return grid_pad_text
Example 17
Project: FRIDA Author: LCAV File: tools_fri_doa_plane.py License: MIT License | 5 votes |
def Rmtx_ri(coef_ri, K, D, L): coef_ri = np.squeeze(coef_ri) coef_r = coef_ri[:K + 1] coef_i = coef_ri[K + 1:] R_r = linalg.toeplitz(np.concatenate((np.array([coef_r[-1]]), np.zeros(L - K - 1))), np.concatenate((coef_r[::-1], np.zeros(L - K - 1))) ) R_i = linalg.toeplitz(np.concatenate((np.array([coef_i[-1]]), np.zeros(L - K - 1))), np.concatenate((coef_i[::-1], np.zeros(L - K - 1))) ) return np.dot(np.vstack((np.hstack((R_r, -R_i)), np.hstack((R_i, R_r)))), D)
Example 18
Project: neural-fingerprinting Author: StephanZheng File: utils.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _logits_op(self, x, name=None): with tf.name_scope(name, "logits", [x]) as name: num_classes = self.adversarial.num_classes() def _backward_py(gradient_y, x): x = np.squeeze(x, axis=0) gradient_y = np.squeeze(gradient_y, axis=0) gradient_x = self.adversarial.backward(gradient_y, x) gradient_x = gradient_x.astype(np.float32) return gradient_x[np.newaxis] def _backward_tf(op, grad): images = op.inputs[0] gradient_x = tf.py_func( _backward_py, [grad, images], tf.float32) gradient_x.set_shape(images.shape) return gradient_x def _forward_py(x): predictions = self.adversarial.batch_predictions( x, strict=False)[0] predictions = predictions.astype(np.float32) return predictions op = py_func_grad( _forward_py, [x], [tf.float32], name=name, grad=_backward_tf) logits = op[0] logits.set_shape((x.shape[0], num_classes)) return logits
Example 19
Project: neural-fingerprinting Author: StephanZheng File: utils.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def pair_visual(original, adversarial, figure=None): """ This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perterbations have been applied :param figure: if we've already displayed images, use the same plot :return: the matplot figure to reuse for future samples """ import matplotlib.pyplot as plt # Squeeze the image to remove single-dimensional entries from array shape original = np.squeeze(original) adversarial = np.squeeze(adversarial) # Ensure our inputs are of proper shape assert(len(original.shape) == 2 or len(original.shape) == 3) # To avoid creating figures per input sample, reuse the sample plot if figure is None: plt.ion() figure = plt.figure() figure.canvas.set_window_title('Cleverhans: Pair Visualization') # Add the images to the plot perterbations = adversarial - original for index, image in enumerate((original, perterbations, adversarial)): figure.add_subplot(1, 3, index + 1) plt.axis('off') # If the image is 2D, then we have 1 color channel if len(image.shape) == 2: plt.imshow(image, cmap='gray') else: plt.imshow(image) # Give the plot some time to update plt.pause(0.01) # Draw the plot and return plt.show() return figure
Example 20
Project: models Author: kipoi File: dataloader.py License: MIT License | 5 votes |
def __getitem__(self, idx): if self.seq_extractor is None: self.seq_extractor = FastaExtractor(self.fasta_file) self.dist_extractor = DistToClosestLandmarkExtractor(gtf_file=self.gtf, landmarks=ALL_LANDMARKS) interval = self.bt[idx] if interval.stop - interval.start != self.SEQ_WIDTH: raise ValueError("Expected the interval to be {0} wide. Recieved stop - start = {1}". format(self.SEQ_WIDTH, interval.stop - interval.start)) out = {} out['inputs'] = {} # input - sequence out['inputs']['seq'] = np.squeeze(self.seq_extractor([interval]), axis=0) # input - distance dist_dict = self.dist_transformer.transform(self.dist_extractor([interval])) dist_dict = {k: np.squeeze(v, axis=0) for k, v in dist_dict.items()} # squeeze the batch axis out['inputs'] = {**out['inputs'], **dist_dict} # targets if self.target_dataset is not None: out["targets"] = np.array([self.target_dataset[idx]]) # metadata out['metadata'] = {} out['metadata']['ranges'] = GenomicRanges.from_interval(interval) return out
Example 21
Project: sklearn-audio-transfer-learning Author: jordipons File: audio_transfer_learning.py License: ISC License | 5 votes |
def extract_vggish_features(paths, path2gt, model): """Extracts VGGish features and their corresponding ground_truth and identifiers (the path). VGGish features are extracted from non-overlapping audio patches of 0.96 seconds, where each audio patch covers 64 mel bands and 96 frames of 10 ms each. We repeat ground_truth and identifiers to fit the number of extracted VGGish features. """ # 1) Extract log-mel spectrograms first_audio = True for p in paths: if first_audio: input_data = vggish_input.wavfile_to_examples(config['audio_folder'] + p) ground_truth = np.repeat(path2gt[p], input_data.shape[0], axis=0) identifiers = np.repeat(p, input_data.shape[0], axis=0) first_audio = False else: tmp_in = vggish_input.wavfile_to_examples(config['audio_folder'] + p) input_data = np.concatenate((input_data, tmp_in), axis=0) tmp_gt = np.repeat(path2gt[p], tmp_in.shape[0], axis=0) ground_truth = np.concatenate((ground_truth, tmp_gt), axis=0) tmp_id = np.repeat(p, tmp_in.shape[0], axis=0) identifiers = np.concatenate((identifiers, tmp_id), axis=0) # 2) Load Tensorflow model to extract VGGish features with tf.Graph().as_default(), tf.Session() as sess: vggish_slim.define_vggish_slim(training=False) vggish_slim.load_vggish_slim_checkpoint(sess, 'vggish_model.ckpt') features_tensor = sess.graph.get_tensor_by_name(vggish_params.INPUT_TENSOR_NAME) embedding_tensor = sess.graph.get_tensor_by_name(vggish_params.OUTPUT_TENSOR_NAME) extracted_feat = sess.run([embedding_tensor], feed_dict={features_tensor: input_data}) feature = np.squeeze(np.asarray(extracted_feat)) return [feature, ground_truth, identifiers]
Example 22
Project: neuropythy Author: noahbenson File: register_retinotopy.py License: GNU Affero General Public License v3.0 | 5 votes |
def _guess_surf_file(fl): # MGH/MGZ files try: return np.asarray(fsmgh.load(fl).dataobj).flatten() except Exception: pass # FreeSurfer Curv files try: return fsio.read_morph_data(fl) except Exception: pass # Nifti files try: return np.squeeze(nib.load(fl).dataobj) except Exception: pass raise ValueError('Could not determine filetype for: %s' % fl)
Example 23
Project: neuropythy Author: noahbenson File: files.py License: GNU Affero General Public License v3.0 | 5 votes |
def gifti_to_array(gii): ''' gifti_to_array(gii) yields the squeezed array of data contained in the given gifti object, gii, Note that if gii does not contain simple data in its darray object, then this will produce undefined results. This operation is effectively equivalent to: np.squeeze([x.data for x in gii.darrays]). gifti_to_array(gii_filename) is equivalent to gifti_to_array(neyropythy.load(gii_filename)). ''' if pimms.is_str(gii): return gifti_to_array(ny.load(gii, 'gifti')) elif pimms.is_nparray(gii): return gii #already done elif isinstance(gii, nib.gifti.gifti.GiftiImage): return np.squeeze(np.asarray([x.data for x in gii.darrays])) else: raise ValueError('Could not understand argument to gifti_to_array')
Example 24
Project: neuropythy Author: noahbenson File: files.py License: GNU Affero General Public License v3.0 | 5 votes |
def load_cifti(filename, to='auto'): ''' load_cifti(filename) yields the cifti image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are understood: * 'header' will yield just the image header * 'data' will yield the image's data-array * 'field' will yield a squeezed version of the image's data-array and will raise an error if the data object has more than 2 non-unitary dimensions (appropriate for loading surface properties stored in image files) * 'image' will yield the raw image object * 'auto' is equivalent to 'image' unless the image has no more than 2 non-unitary dimensions, in which case it is assumed to be a surface-field and the return value is equivalent to the 'field' value. ''' img = nib.load(filename) if not isinstance(img, nib.cifti2.Cifti2Image): raise ValueError('given file is not a cifti image') to = 'auto' if to is None else to.lower() if to == 'image': return img elif to == 'data': return img.dataobj elif to == 'header': return img.header elif to == 'field': dat = np.squeeze(np.asarray(img.dataobj)) if len(dat.shape) > 2: raise ValueError('image requested as field has more than 2 non-unitary dimensions') return dat elif to in ['auto', 'automatic']: dims = set(np.shape(img.dataobj)) if 1 < len(dims) < 4 and 1 in dims: return np.squeeze(np.asarray(img.dataobj)) else: return img else: raise ValueError('unrecognized \'to\' argument \'%s\'' % to)
Example 25
Project: neuropythy Author: noahbenson File: core.py License: GNU Affero General Public License v3.0 | 5 votes |
def load_mgh(filename, to='auto'): ''' load_mgh(filename) yields the MGHImage referened by the given filename by using the nibabel.freesurfer.mghformat.load function. The optional argument 'to' may be used to coerce the resulting data to a particular format; the following arguments are understood: * 'header' will yield just the image header * 'data' will yield the image's data-array * 'field' will yield a squeezed version of the image's data-array and will raise an error if the data object has more than 2 non-unitary dimensions (appropriate for loading surface properties stored in image files) * 'affine' will yield the image's affine transformation * 'image' will yield the raw image object * 'auto' is equivalent to 'image' unless the image has no more than 2 non-unitary dimensions, in which case it is assumed to be a surface-field and the return value is equivalent to the 'field' value. ''' img = fsmgh.load(filename) to = to.lower() if to == 'image': return img elif to == 'data': return img.dataobj elif to == 'affine': return img.affine elif to == 'header': return img.header elif to == 'field': dat = np.squeeze(img.dataobj) if len(dat.shape) > 2: raise ValueError('image requested as field has more than 2 non-unitary dimensions') return dat elif to in ['auto', 'automatic']: dims = set(img.dataobj.shape) if 1 < len(dims) < 4 and 1 in dims: return np.squeeze(img.dataobj) else: return img else: raise ValueError('unrecognized \'to\' argument \'%s\'' % to)
Example 26
Project: neuropythy Author: noahbenson File: core.py License: GNU Affero General Public License v3.0 | 5 votes |
def __call__(self, params): ''' pf(params) yields the tuple (z, dz) where z is the potential value at the given parameters vector, params, and dz is the vector of the potential gradient. ''' z = self.value(params) dz = self.jacobian(params) if sps.issparse(dz): dz = dz.toarray() z = np.squeeze(z) dz = np.squeeze(dz) return (z,dz)
Example 27
Project: neuropythy Author: noahbenson File: core.py License: GNU Affero General Public License v3.0 | 5 votes |
def jac(self): ''' pf.jac() yields a jacobian calculation function for the given potential function pf that is appropritate for passing to a minimizer. ''' def _jacobian(x): dz = self.jacobian(x) if sps.issparse(dz): dz = dz.toarray() dz = np.asarray(dz) return np.squeeze(dz) return _jacobian
Example 28
Project: neuropythy Author: noahbenson File: core.py License: GNU Affero General Public License v3.0 | 5 votes |
def load_nifti(filename, to='auto'): ''' load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are understood: * 'header' will yield just the image header * 'data' will yield the image's data-array * 'field' will yield a squeezed version of the image's data-array and will raise an error if the data object has more than 2 non-unitary dimensions (appropriate for loading surface properties stored in image files) * 'affine' will yield the image's affine transformation * 'image' will yield the raw image object * 'auto' is equivalent to 'image' unless the image has no more than 2 non-unitary dimensions, in which case it is assumed to be a surface-field and the return value is equivalent to the 'field' value. ''' img = nib.load(filename) to = to.lower() if to == 'image': return img elif to == 'data': return img.dataobj elif to == 'affine': return img.affine elif to == 'header': return img.header elif to == 'field': dat = np.squeeze(np.asarray(img.dataobj)) if len(dat.shape) > 2: raise ValueError('image requested as field has more than 2 non-unitary dimensions') return dat elif to in ['auto', 'automatic']: dims = set(np.shape(img.dataobj)) if 1 < len(dims) < 4 and 1 in dims: return np.squeeze(np.asarray(img.dataobj)) else: return img else: raise ValueError('unrecognized \'to\' argument \'%s\'' % to)
Example 29
Project: DOTA_models Author: ringringyi File: classify_image.py License: Apache License 2.0 | 5 votes |
def run_inference_on_image(image): """Runs inference on an image. Args: image: Image file name. Returns: Nothing """ if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. create_graph() with tf.Session() as sess: # Some useful tensors: # 'softmax:0': A tensor containing the normalized prediction across # 1000 labels. # 'pool_3:0': A tensor containing the next-to-last layer containing 2048 # float description of the image. # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG # encoding of the image. # Runs the softmax tensor by feeding the image_data as input to the graph. softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) # Creates node ID --> English string lookup. node_lookup = NodeLookup() top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1] for node_id in top_k: human_string = node_lookup.id_to_string(node_id) score = predictions[node_id] print('%s (score = %.5f)' % (human_string, score))
Example 30
Project: DOTA_models Author: ringringyi File: test_utils_test.py License: Apache License 2.0 | 5 votes |
def test_diagonal_gradient_image(self): """Tests if a good pyramid image is created.""" pyramid_image = test_utils.create_diagonal_gradient_image(3, 4, 2) # Test which is easy to understand. expected_first_channel = np.array([[3, 2, 1, 0], [4, 3, 2, 1], [5, 4, 3, 2]], dtype=np.float32) self.assertAllEqual(np.squeeze(pyramid_image[:, :, 0]), expected_first_channel) # Actual test. expected_image = np.array([[[3, 30], [2, 20], [1, 10], [0, 0]], [[4, 40], [3, 30], [2, 20], [1, 10]], [[5, 50], [4, 40], [3, 30], [2, 20]]], dtype=np.float32) self.assertAllEqual(pyramid_image, expected_image)