Python numpy.amax() Examples

The following are 30 code examples of numpy.amax(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: pose_dataset.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def get_heatmap(self, target_size):
        heatmap = np.zeros((CocoMetadata.__coco_parts, self.height, self.width), dtype=np.float32)

        for joints in self.joint_list:
            for idx, point in enumerate(joints):
                if point[0] < 0 or point[1] < 0:
                    continue
                CocoMetadata.put_heatmap(heatmap, idx, point, self.sigma)

        heatmap = heatmap.transpose((1, 2, 0))

        # background
        heatmap[:, :, -1] = np.clip(1 - np.amax(heatmap, axis=2), 0.0, 1.0)

        if target_size:
            heatmap = cv2.resize(heatmap, target_size, interpolation=cv2.INTER_AREA)

        return heatmap.astype(np.float16) 
Example #2
Source File: np_box_list_ops.py    From SlowFast-Network-pytorch with MIT License 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example #3
Source File: cartpole.py    From LearningX with MIT License 6 votes vote down vote up
def train(self, batch_size=32):
            # Train using replay experience
            minibatch = random.sample(self.memory, batch_size)
            for memory in minibatch:
                state, action, reward, state_next, done = memory
                # Build Q target:
                # -> Qtarget[!action] = Q[!action]
                #    Qtarget[action] = reward + gamma * max[a'](Q_next(state_next))
                Qtarget = self.model.predict(state)
                dQ = reward
                if not done:
                    dQ += self.gamma * np.amax(self.model.predict(state_next)[0])
                Qtarget[0][action] = dQ
                self.model.fit(state, Qtarget, epochs=1, verbose=0)

            # Decary exploration after training
            if self.epsilon > self.epsilon_min:
                self.epsilon *= self.epsilon_decay 
Example #4
Source File: spatial_heatmap.py    From NanoPlot with GNU General Public License v3.0 6 votes vote down vote up
def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
    """Taking channel information and creating post run channel activity plots."""
    logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
                 .format(array.size))
    activity_map = Plot(
        path=path + "." + figformat,
        title="Number of reads generated per channel")
    layout = make_layout(maxval=np.amax(array))
    valueCounts = pd.value_counts(pd.Series(array))
    for entry in valueCounts.keys():
        layout.template[np.where(layout.structure == entry)] = valueCounts[entry]
    plt.figure()
    ax = sns.heatmap(
        data=pd.DataFrame(layout.template, index=layout.yticks, columns=layout.xticks),
        xticklabels="auto",
        yticklabels="auto",
        square=True,
        cbar_kws={"orientation": "horizontal"},
        cmap=color,
        linewidths=0.20)
    ax.set_title(title or activity_map.title)
    activity_map.fig = ax.get_figure()
    activity_map.save(format=figformat)
    plt.close("all")
    return [activity_map] 
Example #5
Source File: reblock.py    From pyqmc with MIT License 6 votes vote down vote up
def optimally_reblocked(data):
    """
        Find optimal reblocking of input data. Takes in pandas
        DataFrame of raw data to reblock, returns DataFrame
        of reblocked data.
    """
    opt = opt_block(data)
    n_reblock = int(np.amax(opt))
    rb_data = reblock_by2(data, n_reblock)
    serr = rb_data.sem(axis=0)
    d = {
        "mean": rb_data.mean(axis=0),
        "standard error": serr,
        "standard error error": serr / np.sqrt(2 * (len(rb_data) - 1)),
        "reblocks": n_reblock,
    }
    return pd.DataFrame(d) 
Example #6
Source File: test_0092_ag2_ae.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_gw(self):
    """ This is GW """
    mol = gto.M(verbose=0, atom='''Ag 0 0 -0.3707; Ag 0 0 0.3707''', basis = 'cc-pvdz-pp',)
    gto_mf = scf.RHF(mol)#.density_fit()
    gto_mf.kernel()
    #print('gto_mf.mo_energy:', gto_mf.mo_energy)
    s = nao(mf=gto_mf, gto=mol, verbosity=0)
    oref = s.overlap_coo().toarray()
    #print('s.norbs:', s.norbs, oref.sum())

    pb = prod_basis(nao=s, algorithm='fp')
    pab2v = pb.get_ac_vertex_array()
    mom0,mom1=pb.comp_moments()
    orec = np.einsum('p,pab->ab', mom0, pab2v)
    self.assertTrue(np.allclose(orec,oref, atol=1e-3), \
      "{} {}".format(abs(orec-oref).sum()/oref.size, np.amax(abs(orec-oref)))) 
Example #7
Source File: utilities.py    From pytim with GNU General Public License v3.0 6 votes vote down vote up
def guess_normal(universe, group):
    """
    Guess the normal of a liquid slab

    """
    universe.atoms.pack_into_box()
    dim = universe.coord.dimensions

    delta = []
    for direction in range(0, 3):
        histo, _ = np.histogram(
            group.positions[:, direction],
            bins=5,
            range=(0, dim[direction]),
            density=True)
        max_val = np.amax(histo)
        min_val = np.amin(histo)
        delta.append(np.sqrt((max_val - min_val)**2))

    if np.max(delta) / np.min(delta) < 5.0:
        print("Warning: the result of the automatic normal detection (",
              np.argmax(delta), ") is not reliable")
    return np.argmax(delta) 
Example #8
Source File: coords2sort_order.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def coords2sort_order(a2c):
  """ Delivers a list of atom indices which generates a near-diagonal overlap for a given set of atom coordinates """
  na  = a2c.shape[0]
  aa2d = squareform(pdist(a2c))
  mxd = np.amax(aa2d)+1.0
  a = 0
  lsa = []
  for ia in range(na):
    lsa.append(a)
    asrt = np.argsort(aa2d[a])
    for ja in range(1,na):
      b = asrt[ja]
      if b not in lsa: break
    aa2d[a,b] = aa2d[b,a] = mxd
    a = b
  return np.array(lsa) 
Example #9
Source File: m_ion_log.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def __init__(self, ao_log, sp):

    self.ion = ao_log.sp2ion[sp]
    self.rr,self.pp,self.nr = ao_log.rr,ao_log.pp,ao_log.nr
    self.interp_rr = log_interp_c(self.rr)
    self.interp_pp = log_interp_c(self.pp)
    
    self.mu2j = ao_log.sp_mu2j[sp]
    self.nmult= len(self.mu2j)
    self.mu2s = ao_log.sp_mu2s[sp]
    self.norbs= self.mu2s[-1]

    self.mu2ff = ao_log.psi_log[sp]
    self.mu2ff_rl = ao_log.psi_log_rl[sp]    
    self.mu2rcut = ao_log.sp_mu2rcut[sp]
    self.rcut = np.amax(self.mu2rcut)
    self.charge = ao_log.sp2charge[sp] 
Example #10
Source File: np_box_mask_list_ops.py    From SlowFast-Network-pytorch with MIT License 6 votes vote down vote up
def prune_non_overlapping_masks(box_mask_list1, box_mask_list2, minoverlap=0.0):
  """Prunes the boxes in list1 that overlap less than thresh with list2.

  For each mask in box_mask_list1, we want its IOA to be more than minoverlap
  with at least one of the masks in box_mask_list2. If it does not, we remove
  it. If the masks are not full size image, we do the pruning based on boxes.

  Args:
    box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks.
    box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned box_mask_list with size [N', 4].
  """
  intersection_over_area = ioa(box_mask_list2, box_mask_list1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_box_mask_list1 = gather(box_mask_list1, keep_inds)
  return new_box_mask_list1 
Example #11
Source File: gw_iter.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def si_c_check (self, tol = 1e-5):
    """
    This compares np.solve and LinearOpt-lgmres methods for solving linear equation (1-v\chi_{0}) * W_c = v\chi_{0}v
    """
    import time
    import numpy as np
    ww = 1j*self.ww_ia
    t = time.time()
    si0_1 = self.si_c(ww)      #method 1:  numpy.linalg.solve
    t1 = time.time() - t
    print('numpy: {} sec'.format(t1))
    t2 = time.time()
    si0_2 = self.si_c2(ww)     #method 2:  scipy.sparse.linalg.lgmres
    t3 = time.time() - t2
    print('lgmres: {} sec'.format(t3))
    summ = abs(si0_1 + si0_2).sum()
    diff = abs(si0_1 - si0_2).sum() 
    if diff/summ < tol and diff/si0_1.size < tol:
       print('OK! scipy.lgmres methods and np.linalg.solve have identical results')
    else:
       print('Results (W_c) are NOT similar!')     
    return [[diff/summ] , [np.amax(abs(diff))] ,[tol]]

  #@profile 
Example #12
Source File: gw.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def get_wmin_wmax_tmax_ia_def(self, tol):
    from numpy import log, exp, sqrt, where, amin, amax
    """ 
      This is a default choice of the wmin and wmax parameters for a log grid along 
      imaginary axis. The default choice is based on the eigenvalues. 
    """
    E = self.ksn2e[0,0,:]
    E_fermi = self.fermi_energy
    E_homo = amax(E[where(E<=E_fermi)])
    E_gap  = amin(E[where(E>E_fermi)]) - E_homo  
    E_maxdiff = amax(E) - amin(E)
    d = amin(abs(E_homo-E)[where(abs(E_homo-E)>1e-4)])
    wmin_def = sqrt(tol * (d**3) * (E_gap**3)/(d**2+E_gap**2))
    wmax_def = (E_maxdiff**2/tol)**(0.250)
    tmax_def = -log(tol)/ (E_gap)
    tmin_def = -100*log(1.0-tol)/E_maxdiff
    return wmin_def, wmax_def, tmin_def,tmax_def 
Example #13
Source File: np_box_list_ops.py    From object_detector_app with MIT License 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example #14
Source File: np_box_mask_list_ops.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def prune_non_overlapping_masks(box_mask_list1, box_mask_list2, minoverlap=0.0):
  """Prunes the boxes in list1 that overlap less than thresh with list2.

  For each mask in box_mask_list1, we want its IOA to be more than minoverlap
  with at least one of the masks in box_mask_list2. If it does not, we remove
  it. If the masks are not full size image, we do the pruning based on boxes.

  Args:
    box_mask_list1: np_box_mask_list.BoxMaskList holding N boxes and masks.
    box_mask_list2: np_box_mask_list.BoxMaskList holding M boxes and masks.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned box_mask_list with size [N', 4].
  """
  intersection_over_area = ioa(box_mask_list2, box_mask_list1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_box_mask_list1 = gather(box_mask_list1, keep_inds)
  return new_box_mask_list1 
Example #15
Source File: np_box_list_ops.py    From vehicle_counting_tensorflow with MIT License 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example #16
Source File: OutlierDetection.py    From sparse-subspace-clustering-python with MIT License 6 votes vote down vote up
def OutlierDetection(CMat, s):
    n = np.amax(s)
    _, N = CMat.shape
    OutlierIndx = list()
    FailCnt = 0
    Fail = False

    for i in range(0, N):
        c = CMat[:, i]
        if np.sum(np.isnan(c)) >= 1:
            OutlierIndx.append(i)
            FailCnt += 1
    sc = s.astype(float)
    sc[OutlierIndx] = np.nan
    CMatC = CMat.astype(float)
    CMatC[OutlierIndx, :] = np.nan
    CMatC[:, OutlierIndx] = np.nan
    OutlierIndx = OutlierIndx

    if FailCnt > (N - n):
        CMatC = np.nan
        sc = np.nan
        Fail = True
    return CMatC, sc, OutlierIndx, Fail 
Example #17
Source File: util.py    From DeepFloorplan with GNU General Public License v3.0 6 votes vote down vote up
def refine_room_region(cw_mask, rm_ind):
	label_rm, num_label = ndimage.label((1-cw_mask))
	new_rm_ind = np.zeros(rm_ind.shape)
	for j in xrange(1, num_label+1):  
		mask = (label_rm == j).astype(np.uint8)
		ys, xs = np.where(mask!=0)
		area = (np.amax(xs)-np.amin(xs))*(np.amax(ys)-np.amin(ys))
		if area < 100:
			continue
		else:
			room_types, type_counts = np.unique(mask*rm_ind, return_counts=True)
			if len(room_types) > 1:
				room_types = room_types[1:] # ignore background type which is zero
				type_counts = type_counts[1:] # ignore background count
			new_rm_ind += mask*room_types[np.argmax(type_counts)]

	return new_rm_ind 
Example #18
Source File: np_box_list_ops.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def prune_non_overlapping_boxes(boxlist1, boxlist2, minoverlap=0.0):
  """Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.

  For each box in boxlist1, we want its IOA to be more than minoverlap with
  at least one of the boxes in boxlist2. If it does not, we remove it.

  Args:
    boxlist1: BoxList holding N boxes.
    boxlist2: BoxList holding M boxes.
    minoverlap: Minimum required overlap between boxes, to count them as
                overlapping.

  Returns:
    A pruned boxlist with size [N', 4].
  """
  intersection_over_area = ioa(boxlist2, boxlist1)  # [M, N] tensor
  intersection_over_area = np.amax(intersection_over_area, axis=0)  # [N] tensor
  keep_bool = np.greater_equal(intersection_over_area, np.array(minoverlap))
  keep_inds = np.nonzero(keep_bool)[0]
  new_boxlist1 = gather(boxlist1, keep_inds)
  return new_boxlist1 
Example #19
Source File: multi_input.py    From aboleth with Apache License 2.0 6 votes vote down vote up
def input_fn(df):
    """Format the downloaded data."""
    # Creates a dictionary mapping from each continuous feature column name (k)
    # to the values of that column stored in a constant Tensor.
    continuous_cols = [df[k].values for k in CONTINUOUS_COLUMNS]
    X_con = np.stack(continuous_cols).astype(np.float32).T

    # Standardise
    X_con -= X_con.mean(axis=0)
    X_con /= X_con.std(axis=0)

    # Creates a dictionary mapping from each categorical feature column name
    categ_cols = [np.where(pd.get_dummies(df[k]).values)[1][:, np.newaxis]
                  for k in CATEGORICAL_COLUMNS]
    n_values = [np.amax(c) + 1 for c in categ_cols]
    X_cat = np.concatenate(categ_cols, axis=1).astype(np.int32)

    # Converts the label column into a constant Tensor.
    label = df[LABEL_COLUMN].values[:, np.newaxis]

    # Returns the feature columns and the label.
    return X_con, X_cat, n_values, label 
Example #20
Source File: loss.py    From pygbm with MIT License 5 votes vote down vote up
def _logsumexp(a):
    """logsumexp(x) = log(sum(exp(x)))

    Custom logsumexp function with numerical stability, based on scipy's
    logsumexp which is unfortunately not supported (neither is
    np.logaddexp.reduce, which is equivalent). Only supports 1d arrays.
    """

    a_max = np.amax(a)
    if not np.isfinite(a_max):
        a_max = 0

    s = np.sum(np.exp(a - a_max))
    return np.log(s) + a_max 
Example #21
Source File: test_transformers.py    From deepchem with MIT License 5 votes vote down vote up
def test_X_normalization_transformer(self):
    """Tests normalization transformer."""
    solubility_dataset = dc.data.tests.load_solubility_data()
    normalization_transformer = dc.trans.NormalizationTransformer(
        transform_X=True, dataset=solubility_dataset)
    X, y, w, ids = (solubility_dataset.X, solubility_dataset.y,
                    solubility_dataset.w, solubility_dataset.ids)
    solubility_dataset = normalization_transformer.transform(solubility_dataset)
    X_t, y_t, w_t, ids_t = (solubility_dataset.X, solubility_dataset.y,
                            solubility_dataset.w, solubility_dataset.ids)
    # Check ids are unchanged.
    for id_elt, id_t_elt in zip(ids, ids_t):
      assert id_elt == id_t_elt
    # Check y is unchanged since this is a X transformer
    np.testing.assert_allclose(y, y_t)
    # Check w is unchanged since this is a y transformer
    np.testing.assert_allclose(w, w_t)
    # Check that X_t has zero mean, unit std.
    # np.set_printoptions(threshold='nan')
    mean = X_t.mean(axis=0)
    assert np.amax(np.abs(mean - np.zeros_like(mean))) < 1e-7
    orig_std_array = X.std(axis=0)
    std_array = X_t.std(axis=0)
    # Entries with zero std are not normalized
    for orig_std, std in zip(orig_std_array, std_array):
      if not np.isclose(orig_std, 0):
        assert np.isclose(std, 1)

    # TODO(rbharath): Untransform doesn't work properly for binary feature
    # vectors. Need to figure out what's wrong here. (low priority)
    ## Check that untransform does the right thing.
    # np.testing.assert_allclose(normalization_transformer.untransform(X_t), X) 
Example #22
Source File: snn_training.py    From Training-Neural-Networks-for-Event-Based-End-to-End-Robot-Control with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path):
		# Read DQN data
		h5f = h5py.File(path + '/dqn_data.h5', 'r')
		self.states = np.array(h5f['states'], dtype=float)
		self.actions = np.array(h5f['actions'])
		h5f.close()
		# Delete empty states at the end of array
		for i in range(self.states.shape[0]):
			if self.states[-i].any():
				break
		# Normalize states
		self.states = self.states[:-i+1]/np.amax(self.states)
		self.actions = self.actions[:-i+1] 
Example #23
Source File: plot_state_input_sample.py    From Training-Neural-Networks-for-Event-Based-End-to-End-Robot-Control with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path):
		h5f = h5py.File(path+'dqn_data.h5', 'r')
		self.states = np.array(h5f['states'], dtype=float)
		self.actions = np.array(h5f['actions'])
		h5f.close()
		for i in range(self.states.shape[0]):
			if self.states[-i].any():
				break
		self.states = self.states[:-i+1]/np.amax(self.states)
		self.actions = self.actions[:-i+1] 
Example #24
Source File: show_video_transforms.py    From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(argv):
    if len(argv) < 2:
        print("Usage: python show_video_transforms.py [video_file_path]")
        return

    # Read frames
    op = OpticalFlow(rgb_vid_in_p=argv[1])
    rgb_4d = op.vid_to_frames().astype(np.uint8) # ColorJitter need uint8
    tl = TestLearner()
    T = tl.get_transform("rgb", phase="train")
    rgb_4d = T(rgb_4d).numpy().transpose(1, 2, 3, 0)
    print(np.amin(rgb_4d), np.amax(rgb_4d))
    print(rgb_4d.shape)
    rgb_4d = cv2.normalize(rgb_4d, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
    op.frames_to_vid(rgb_4d, "../data/transformed.mp4") 
Example #25
Source File: utils.py    From sato with Apache License 2.0 5 votes vote down vote up
def logDot(a, b):

    # numeric stable way of calculating log (e^a, e^b)
    max_a = np.amax(a)
    max_b = np.amax(b)

    C = np.dot(np.exp(a - max_a), np.exp(b - max_b))
    np.log(C, out=C)
    # else:
    #   np.log(C + 1e-300, out=C)

    C += max_a + max_b

    return C 
Example #26
Source File: inference.py    From PoseWarper with Apache License 2.0 5 votes vote down vote up
def get_max_preds(batch_heatmaps):
    '''
    get predictions from score maps
    heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
    '''
    assert isinstance(batch_heatmaps, np.ndarray), \
        'batch_heatmaps should be numpy.ndarray'
    assert batch_heatmaps.ndim == 4, 'batch_images should be 4-ndim'

    batch_size = batch_heatmaps.shape[0]
    num_joints = batch_heatmaps.shape[1]
    width = batch_heatmaps.shape[3]
    heatmaps_reshaped = batch_heatmaps.reshape((batch_size, num_joints, -1))
    idx = np.argmax(heatmaps_reshaped, 2)
    maxvals = np.amax(heatmaps_reshaped, 2)

    maxvals = maxvals.reshape((batch_size, num_joints, 1))
    idx = idx.reshape((batch_size, num_joints, 1))

    preds = np.tile(idx, (1, 1, 2)).astype(np.float32)

    preds[:, :, 0] = (preds[:, :, 0]) % width
    preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)

    pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))
    pred_mask = pred_mask.astype(np.float32)

    preds *= pred_mask
    return preds, maxvals 
Example #27
Source File: misc.py    From graph_distillation with Apache License 2.0 5 votes vote down vote up
def softmax(w, t=1.0, axis=None):
  w = np.array(w) / t
  e = np.exp(w - np.amax(w, axis=axis, keepdims=True))
  dist = e / np.sum(e, axis=axis, keepdims=True)
  return dist 
Example #28
Source File: visualize.py    From graph_distillation with Apache License 2.0 5 votes vote down vote up
def visualize_warp(rgb, oflow):
  """TODO: add info."""
  rgb = utils.to_numpy(rgb)
  oflow = utils.to_numpy(oflow)

  mean = np.array([0.485, 0.456, 0.406])
  std = np.array([0.229, 0.224, 0.225])
  rgb = np.moveaxis(rgb, -3, -1)
  rgb = rgb*std+mean
  rgb = np.clip(rgb*255, 0, 255)
  bgr = rgb[..., ::-1].astype(np.uint8)
  bgr = bgr[0, 0]  # subsample
  print(bgr.shape, np.amin(bgr), np.amax(bgr), np.mean(bgr),
        np.mean(np.absolute(bgr)))

  oflow = np.moveaxis(oflow, -3, -1)
  oflow = oflow[0, 0]  # subsample
  print(oflow.shape, np.amin(oflow), np.amax(oflow), np.mean(oflow),
        np.mean(np.absolute(oflow)))

  warp = imgproc.warp(bgr[4], bgr[5], oflow[4])

  root = '/home/luoa/research'
  cv2.imwrite(os.path.join(root, 'bgr1.jpg'), bgr[4])
  cv2.imwrite(os.path.join(root, 'bgr2.jpg'), bgr[5])
  cv2.imwrite(os.path.join(root, 'warp.jpg'), warp) 
Example #29
Source File: np_box_list_ops.py    From vehicle_counting_tensorflow with MIT License 5 votes vote down vote up
def gather(boxlist, indices, fields=None):
  """Gather boxes from BoxList according to indices and return new BoxList.

  By default, gather returns boxes corresponding to the input index list, as
  well as all additional fields stored in the boxlist (indexing into the
  first dimension).  However one can optionally only gather from a
  subset of fields.

  Args:
    boxlist: BoxList holding N boxes
    indices: a 1-d numpy array of type int_
    fields: (optional) list of fields to also gather from.  If None (default),
        all fields are gathered from.  Pass an empty fields list to only gather
        the box coordinates.

  Returns:
    subboxlist: a BoxList corresponding to the subset of the input BoxList
        specified by indices

  Raises:
    ValueError: if specified field is not contained in boxlist or if the
        indices are not of type int_
  """
  if indices.size:
    if np.amax(indices) >= boxlist.num_boxes() or np.amin(indices) < 0:
      raise ValueError('indices are out of valid range.')
  subboxlist = np_box_list.BoxList(boxlist.get()[indices, :])
  if fields is None:
    fields = boxlist.get_extra_fields()
  for field in fields:
    extra_field_data = boxlist.get_field(field)
    subboxlist.add_field(field, extra_field_data[indices, ...])
  return subboxlist 
Example #30
Source File: lattice_test.py    From lattice with Apache License 2.0 5 votes vote down vote up
def _Max(self, x):
    return np.amax(x)