Python numpy.flip() Examples

The following are 30 code examples of numpy.flip(). 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: utils.py    From tf2-yolo3 with Apache License 2.0 8 votes vote down vote up
def draw_labels(x, y, class_names=None):
    img = x.numpy()
    if img.ndim == 2 or img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    boxes, classes = tf.split(y, (4, 1), axis=-1)
    classes = classes[..., 0]
    wh = np.flip(img.shape[0:2])
    min_wh = np.amin(wh)
    if min_wh <= 100:
        font_size = 0.5
    else:
        font_size = 1
    for i in range(len(boxes)):
        x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
        x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
        img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
        if class_names:
            img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
                              (0, 0, 255), 1)
        else:
            img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)
    return img 
Example #2
Source File: utils.py    From tf2-yolo3 with Apache License 2.0 8 votes vote down vote up
def draw_outputs(img, outputs, class_names=None):
    boxes, objectness, classes = outputs
    #boxes, objectness, classes = boxes[0], objectness[0], classes[0]
    wh = np.flip(img.shape[0:2])
    if img.ndim == 2 or img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    min_wh = np.amin(wh)
    if min_wh <= 100:
        font_size = 0.5
    else:
        font_size = 1
    for i in range(classes.shape[0]):
        x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))
        x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))
        img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1)
        img = cv2.putText(img, '{}'.format(int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size,
                          (0, 0, 255), 1)
    return img 
Example #3
Source File: time_align.py    From scanorama with MIT License 7 votes vote down vote up
def time_align_visualize(alignments, time, y, namespace='time_align'):
    plt.figure()
    heat = np.flip(alignments + alignments.T +
                   np.eye(alignments.shape[0]), axis=0)
    sns.heatmap(heat, cmap="YlGnBu", vmin=0, vmax=1)
    plt.savefig(namespace + '_heatmap.svg')

    G = nx.from_numpy_matrix(alignments)
    G = nx.maximum_spanning_tree(G)

    pos = {}
    for i in range(len(G.nodes)):
        pos[i] = np.array([time[i], y[i]])

    mst_edges = set(nx.maximum_spanning_tree(G).edges())
    
    weights = [ G[u][v]['weight'] if (not (u, v) in mst_edges) else 8
                for u, v in G.edges() ]
    
    plt.figure()
    nx.draw(G, pos, edges=G.edges(), width=10)
    plt.ylim([-1, 1])
    plt.savefig(namespace + '.svg') 
Example #4
Source File: datagen.py    From StyleGAN2-Tensorflow-2.0 with MIT License 6 votes vote down vote up
def __init__(self, folder, im_size, mss = (1024 ** 3), flip = True, verbose = True):
        self.folder = folder
        self.im_size = im_size
        self.segment_length = mss // (im_size * im_size * 3)
        self.flip = flip
        self.verbose = verbose

        self.segments = []
        self.images = []
        self.update = 0

        if self.verbose:
            print("Importing images...")
            print("Maximum Segment Size: ", self.segment_length)

        try:
            os.mkdir("data/" + self.folder + "-npy-" + str(self.im_size))
        except:
            self.load_from_npy(folder)
            return

        self.folder_to_npy(self.folder)
        self.load_from_npy(self.folder) 
Example #5
Source File: inference.py    From HorizonNet with MIT License 6 votes vote down vote up
def augment_undo(x_imgs_augmented, aug_type):
    x_imgs_augmented = x_imgs_augmented.cpu().numpy()
    sz = x_imgs_augmented.shape[0] // len(aug_type)
    x_imgs = []
    for i, aug in enumerate(aug_type):
        x_img = x_imgs_augmented[i*sz : (i+1)*sz]
        if aug == 'flip':
            x_imgs.append(np.flip(x_img, axis=-1))
        elif aug.startswith('rotate'):
            shift = int(aug.split()[-1])
            x_imgs.append(np.roll(x_img, -shift, axis=-1))
        elif aug == '':
            x_imgs.append(x_img)
        else:
            raise NotImplementedError()

    return np.array(x_imgs) 
Example #6
Source File: randomized_argsort.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def randomized_argsort(A, method="numpy", order='ascending'):
    if method == "numpy":
        P = np.random.permutation(len(A))
        I = np.argsort(A[P], kind='quicksort')
        I = P[I]

    elif method == "quicksort":
        I = quicksort(A)

    else:
        raise Exception("Randomized sort method not known.")

    if order == 'ascending':
        return I
    elif order == 'descending':
        return np.flip(I, axis=0)
    else:
        raise Exception("Unknown sorting order: ascending or descending.") 
Example #7
Source File: viz.py    From signaltrain with GNU General Public License v3.0 6 votes vote down vote up
def show_2d(array_2d, title="weights_layer", colormap=rainbow, flip=True):

    #print("weights_layer.shape = ",weights_layer.shape)
    if len(array_2d.shape) < 2:
        return
    img = np.clip(array_2d*255 ,-255,255).astype(np.uint8)   # scale
    if flip:
        img = np.flip(np.transpose(img))
    img = np.repeat(img[:,:,np.newaxis],3,axis=2)            # add color channels
    img = cv2.applyColorMap(img, colormap)                   # rainbow: blue=low, red=high
    # see if it exists
    new_window = not check_window_exists(title)
    window = cv2.namedWindow(title,cv2.WINDOW_NORMAL)
    cv2.imshow(title, img)
    if new_window:
        cv2.resizeWindow(title, img.shape[1], img.shape[0])                      # show what we've got
    #aspect = img.shape[0] / img.shape[1]
    #if aspect > 3:
    #    cv2.resizeWindow(title, 200, 1024)   # zoom in/out (can use two-finger-scroll to zoom in)
        #print(f"size for {title} = 1024, {int(1024/aspect*img.shape[0])}")
    #else:
    #    cv2.resizeWindow(title, int(imWidth/2),int(imWidth/2))   # zoom in/out (can use two-finger-scroll to zoom in)


# draw weights for all layers using model state dict 
Example #8
Source File: dataset.py    From HorizonNet with MIT License 6 votes vote down vote up
def __init__(self, root_dir,
                 flip=False, rotate=False, gamma=False, stretch=False,
                 p_base=0.96, max_stretch=2.0,
                 normcor=False, return_cor=False, return_path=False):
        self.img_dir = os.path.join(root_dir, 'img')
        self.cor_dir = os.path.join(root_dir, 'label_cor')
        self.img_fnames = sorted([
            fname for fname in os.listdir(self.img_dir)
            if fname.endswith('.jpg') or fname.endswith('.png')
        ])
        self.txt_fnames = ['%s.txt' % fname[:-4] for fname in self.img_fnames]
        self.flip = flip
        self.rotate = rotate
        self.gamma = gamma
        self.stretch = stretch
        self.p_base = p_base
        self.max_stretch = max_stretch
        self.normcor = normcor
        self.return_cor = return_cor
        self.return_path = return_path

        self._check_dataset() 
Example #9
Source File: algs.py    From mabalgs with Apache License 2.0 6 votes vote down vote up
def select(self):
        """
            This method selects the best arm chosen by Thompsom Sampling.

            :return: Return selected arm number.
                    Arm number returned is (n_arm - 1).

                    Returns a list of arms by importance.
                    The chosen arm is the index 0 of this list.
        """
        rewards_0 = self.n_impressions - self.n_rewards
        rewards_0[rewards_0 <= 0] = 1
        theta_value = np.random.beta(self.n_rewards, rewards_0)
        ranked_arms = np.flip(np.argsort(theta_value), axis=0)
        chosen_arm = ranked_arms[0]
        self.n_impressions[chosen_arm] += 1

        return chosen_arm, ranked_arms 
Example #10
Source File: utils.py    From tensornets with MIT License 6 votes vote down vote up
def crop(img, crop_size, crop_loc=4, crop_grid=(3, 3)):
    if isinstance(crop_loc, list):
        imgs = np.zeros((img.shape[0], len(crop_loc), crop_size, crop_size, 3),
                        np.float32)
        for (i, loc) in enumerate(crop_loc):
            r, c = crop_idx(img.shape[1:3], crop_size, loc, crop_grid)
            imgs[:, i] = img[:, r:r+crop_size, c:c+crop_size, :]
        return imgs
    elif crop_loc == np.prod(crop_grid) + 1:
        imgs = np.zeros((img.shape[0], crop_loc, crop_size, crop_size, 3),
                        np.float32)
        r, c = crop_idx(img.shape[1:3], crop_size, 4, crop_grid)
        imgs[:, 0] = img[:, r:r+crop_size, c:c+crop_size, :]
        imgs[:, 1] = img[:, 0:crop_size, 0:crop_size, :]
        imgs[:, 2] = img[:, 0:crop_size, -crop_size:, :]
        imgs[:, 3] = img[:, -crop_size:, 0:crop_size, :]
        imgs[:, 4] = img[:, -crop_size:, -crop_size:, :]
        imgs[:, 5:] = np.flip(imgs[:, :5], axis=3)
        return imgs
    else:
        r, c = crop_idx(img.shape[1:3], crop_size, crop_loc, crop_grid)
        return img[:, r:r+crop_size, c:c+crop_size, :] 
Example #11
Source File: datagen.py    From StyleGAN2-Tensorflow-2.0 with MIT License 6 votes vote down vote up
def get_batch(self, num):

        if self.update > self.images.shape[0]:
            self.load_from_npy(self.folder)

        self.update = self.update + num

        idx = np.random.randint(0, self.images.shape[0] - 1, num)
        out = []

        for i in idx:
            out.append(self.images[i])
            if self.flip and random.random() < 0.5:
                out[-1] = np.flip(out[-1], 1)

        return np.array(out).astype('float32') / 255.0 
Example #12
Source File: bigan.py    From Keras-BiGAN with MIT License 6 votes vote down vote up
def __init__(self, steps = 1, lr = 0.0001, decay = 0.00001, silent = True):

        self.GAN = GAN(steps = steps, lr = lr, decay = decay)
        self.DisModel = self.GAN.DisModel()
        self.AdModel = self.GAN.AdModel()

        self.lastblip = time.clock()

        self.noise_level = 0

        self.im = dataGenerator(directory, suffix = suff, flip = True)

        self.silent = silent

        #Train Generator to be in the middle, not all the way at real. Apparently works better??
        self.ones = np.ones((BATCH_SIZE, 1), dtype=np.float32)
        self.zeros = np.zeros((BATCH_SIZE, 1), dtype=np.float32)
        self.nones = -self.ones 
Example #13
Source File: utils.py    From py360convert with MIT License 6 votes vote down vote up
def equirect_facetype(h, w):
    '''
    0F 1R 2B 3L 4U 5D
    '''
    tp = np.roll(np.arange(4).repeat(w // 4)[None, :].repeat(h, 0), 3 * w // 8, 1)

    # Prepare ceil mask
    mask = np.zeros((h, w // 4), np.bool)
    idx = np.linspace(-np.pi, np.pi, w // 4) / 4
    idx = h // 2 - np.round(np.arctan(np.cos(idx)) * h / np.pi).astype(int)
    for i, j in enumerate(idx):
        mask[:j, i] = 1
    mask = np.roll(np.concatenate([mask] * 4, 1), 3 * w // 8, 1)

    tp[mask] = 4
    tp[np.flip(mask, 0)] = 5

    return tp.astype(np.int32) 
Example #14
Source File: test_function_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_multiple_axes(self):
        a = np.array([[[0, 1],
                       [2, 3]],
                      [[4, 5],
                       [6, 7]]])

        assert_equal(np.flip(a, axis=()), a)

        b = np.array([[[5, 4],
                       [7, 6]],
                      [[1, 0],
                       [3, 2]]])

        assert_equal(np.flip(a, axis=(0, 2)), b)

        c = np.array([[[3, 2],
                       [1, 0]],
                      [[7, 6],
                       [5, 4]]])

        assert_equal(np.flip(a, axis=(1, 2)), c) 
Example #15
Source File: BuildAdjacency.py    From sparse-subspace-clustering-python with MIT License 6 votes vote down vote up
def BuildAdjacency(CMat, K):
    CMat = CMat.astype(float)
    CKSym = None
    N, _ = CMat.shape
    CAbs = np.absolute(CMat).astype(float)
    for i in range(0, N):
        c = CAbs[:, i]
        PInd = np.flip(np.argsort(c), 0)
        CAbs[:, i] = CAbs[:, i] / float(np.absolute(c[PInd[0]]))
    CSym = np.add(CAbs, CAbs.T).astype(float)
    if K != 0:
        Ind = np.flip(np.argsort(CSym, axis=0), 0)
        CK = np.zeros([N, N]).astype(float)
        for i in range(0, N):
            for j in range(0, K):
                CK[Ind[j, i], i] = CSym[Ind[j, i], i] / float(np.absolute(CSym[Ind[0, i], i]))
        CKSym = np.add(CK, CK.T)
    else:
        CKSym = CSym
    return CKSym 
Example #16
Source File: CausalIntegration.py    From pylops with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _rmatvec(self, x):
        if self.reshape:
            x = np.reshape(x, self.dims)
        if self.dir != -1:
            x = np.swapaxes(x, self.dir, -1)
        xflip = np.flip(x, axis=-1)
        if self.halfcurrent:
            y = self.sampling * (np.cumsum(xflip, axis=-1) - xflip/2.)
        else:
            y = self.sampling * np.cumsum(xflip, axis=-1)
        y = np.flip(y, axis=-1)

        if self.dir != -1:
            y = np.swapaxes(y, -1, self.dir)
        return y.ravel() 
Example #17
Source File: test_function_base.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_basic_ud(self):
        a = get_mat(4)
        b = a[::-1, :]
        assert_equal(np.flip(a, 0), b)
        a = [[0, 1, 2],
             [3, 4, 5]]
        b = [[3, 4, 5],
             [0, 1, 2]]
        assert_equal(np.flip(a, 0), b) 
Example #18
Source File: test_function_base.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_3d_swap_axis0(self):
        a = np.array([[[0, 1],
                       [2, 3]],
                      [[4, 5],
                       [6, 7]]])

        b = np.array([[[4, 5],
                       [6, 7]],
                      [[0, 1],
                       [2, 3]]])

        assert_equal(np.flip(a, 0), b) 
Example #19
Source File: test_function_base.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_3d_swap_axis1(self):
        a = np.array([[[0, 1],
                       [2, 3]],
                      [[4, 5],
                       [6, 7]]])

        b = np.array([[[2, 3],
                       [0, 1]],
                      [[6, 7],
                       [4, 5]]])

        assert_equal(np.flip(a, 1), b) 
Example #20
Source File: test_function_base.py    From lambda-packs with MIT License 5 votes vote down vote up
def test_basic_lr(self):
        a = get_mat(4)
        b = a[:, ::-1]
        assert_equal(np.flip(a, 1), b)
        a = [[0, 1, 2],
             [3, 4, 5]]
        b = [[2, 1, 0],
             [5, 4, 3]]
        assert_equal(np.flip(a, 1), b) 
Example #21
Source File: algs.py    From mabalgs with Apache License 2.0 5 votes vote down vote up
def select(self):
        """
            This method selects the best arm chosen by UCB1.

            :return: Return selected arm number.
                    Arm number returned is (n_arm - 1).

                    Returns a list of arms by importance.
                    The chosen arm is the index 0 of this list.
        """

        arm_dont_usage = np.where(self.number_of_selections == 0)[0]
        if len(arm_dont_usage) > 0:
            self.number_of_selections[arm_dont_usage[0]] += 1

            ranked_arms = list(range(len(self.number_of_selections)))

            if arm_dont_usage[0] != 0:
                ranked_arms = np.roll(ranked_arms, 1)
                first_element = ranked_arms[0]
                index_current = ranked_arms.tolist().index(arm_dont_usage[0])

                ranked_arms[0] = arm_dont_usage[0]
                ranked_arms[index_current] = first_element

            return arm_dont_usage[0], ranked_arms

        average_reward = self.rewards / self.number_of_selections
        total_counts = np.sum(self.number_of_selections)

        ucb_values = self._factor_importance_each_arm(
            total_counts,
            self.number_of_selections,
            average_reward
        )
        ranked_arms = np.flip(np.argsort(ucb_values), axis=0)
        chosen_arm = ranked_arms[0]

        self.number_of_selections[chosen_arm] += 1

        return chosen_arm, ranked_arms 
Example #22
Source File: Flip.py    From pylops with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _matvec(self, x):
        if self.reshape:
            x = np.reshape(x, self.dims)
        y = np.flip(x, axis=self.dir)
        if self.reshape:
            y = np.ndarray.flatten(y)
        return y 
Example #23
Source File: helpers.py    From DEXTR-KerasTensorflow with GNU General Public License v3.0 5 votes vote down vote up
def get_bbox(mask, points=None, pad=0, zero_pad=False):
    if points is not None:
        inds = np.flip(points.transpose(), axis=0)
    else:
        inds = np.where(mask > 0)

    if inds[0].shape[0] == 0:
        return None

    if zero_pad:
        x_min_bound = -np.inf
        y_min_bound = -np.inf
        x_max_bound = np.inf
        y_max_bound = np.inf
    else:
        x_min_bound = 0
        y_min_bound = 0
        x_max_bound = mask.shape[1] - 1
        y_max_bound = mask.shape[0] - 1

    x_min = max(inds[1].min() - pad, x_min_bound)
    y_min = max(inds[0].min() - pad, y_min_bound)
    x_max = min(inds[1].max() + pad, x_max_bound)
    y_max = min(inds[0].max() + pad, y_max_bound)

    return x_min, y_min, x_max, y_max 
Example #24
Source File: cmath.py    From ehtplot with GNU General Public License v3.0 5 votes vote down vote up
def factor(Cp,
           softening=1.0,
           bitonic=True,
           diffuse=True,  CpL=None, CpR=None,
           verbose=False):
    """Comput the factor required to perform several chroma operations"""
    S = Cp + softening
    s = S.copy()

    N = len(Cp)
    H = N//2
    m = np.minimum(s[:H], np.flip(s[-H:]))

    if bitonic: # force half of Cp increase monotonically
        if m[H-1] > s[H]:
            m[H-1] = s[H]
            if verbose:
                print("Enforce bitonic at {}".format(s[H]))
        for i in range(H-1,0,-1):
            if m[i-1] > m[i]:
                m[i-1] = m[i]
                if verbose:
                    print("Enforce bitonic at {}".format(m[i]))

    s[:+H] = m
    s[-H:] = np.flip(m)

    if CpL is not None:
        s[ 0] = CpL + softening
    if CpR is not None:
        s[-1] = CpR + softening

    if diffuse: # diffuse s using forward Euler
        for i in range(N):
            s[1:-1] += 0.5 * (s[2:] + s[:-2] - 2.0 * s[1:-1])

    return s / S 
Example #25
Source File: cmath.py    From ehtplot with GNU General Public License v3.0 5 votes vote down vote up
def interp(x, xp, yp):
    """Improve numpy's interp() function to allow decreasing `xp`"""
    if xp[0] < xp[-1]:
        return np.interp(x, xp, yp)
    else:
        return np.interp(x, np.flip(xp,0), np.flip(yp,0)) 
Example #26
Source File: video_transforms.py    From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __call__(self, imgs):
        """
        Args:
            img (seq Images): seq Images to be flipped.
        Returns:
            seq Images: Randomly flipped seq images.
        """
        if random.random() < self.p:
            # t x h x w
            return np.flip(imgs, axis=2).copy()
        return imgs 
Example #27
Source File: stereo_selfsupervised.py    From DSMnet with Apache License 2.0 5 votes vote down vote up
def flip_lr_tensor(self, tensor):
        data_numpy = np.flip(tensor.cpu().numpy(), axis=-1).copy()
        return torch.from_numpy(data_numpy).type_as(tensor) 
Example #28
Source File: img_rw.py    From DSMnet with Apache License 2.0 5 votes vote down vote up
def imwrite(fname, image):
    if(fname.find('.pfm') > 0):
        save_pfm(fname, image)
    else:
        image = np.flip(image, axis=2) # rgb --> bgr
        cv2.imwrite(fname, image) 
Example #29
Source File: img_rw.py    From DSMnet with Apache License 2.0 5 votes vote down vote up
def imread(fname):
    if(fname.find('.pfm') > 0):
        return load_pfm(fname)[0]
    else:
        image = cv2.imread(fname)
        image = np.flip(image, axis=2) # bgr --> rgb
        return np.array(image) 
Example #30
Source File: atlas.py    From ibllib with MIT License 5 votes vote down vote up
def plot_sslice(self, ml_coordinate, volume='image', **kwargs):
        """
        Imshow a sagittal slice
        :param: ml_coordinate (mm)
        :param: ax
        """
        vol = self.label if volume == 'annotation' else self.image
        return self._plot_slice(vol[:, self.bc.x2i(ml_coordinate / 1e3), :].transpose(),
                                extent=np.r_[self.bc.ylim * 1e3, np.flip(self.bc.zlim) * 1e3],
                                **kwargs)