numpy.flipud

Here are the examples of the python api numpy.flipud taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

260 Examples 7

3 Source : util.py
with MIT License
from addisonElliott

def loadImage(filename, flipud=True, convertToGrayscale=False):
    image = imageio.imread(os.path.join(dataDirectory, filename), ignoregamma=True)

    if convertToGrayscale and image.ndim == 3:
        image = image[:, :, 0]
    elif image.ndim == 3 and image.shape[-1] == 4:
        image = image[:, :, 0:3]

    return np.flipud(image) if flipud else image


def loadVideo(filename, flipud=True, convertToGrayscale=False):

3 Source : test_twodim_base.py
with GNU General Public License v3.0
from adityaprakash-bobby

    def test_basic(self):
        a = get_mat(4)
        b = a[::-1, :]
        assert_equal(flipud(a), b)
        a = [[0, 1, 2],
             [3, 4, 5]]
        b = [[3, 4, 5],
             [0, 1, 2]]
        assert_equal(flipud(a), b)


class TestHistogram2d(object):

3 Source : airfoils.py
with Apache License 2.0
from airinnova

    def _order_data_points(self):
        """
        Order the data points so that x-coordinate starts at 0
        """

        if self._x_upper[0] > self._x_upper[-1]:
            self._x_upper = np.flipud(self._x_upper)
            self._y_upper = np.flipud(self._y_upper)

        if self._x_lower[0] > self._x_lower[-1]:
            self._x_lower = np.flipud(self._x_lower)
            self._y_lower = np.flipud(self._y_lower)

    def _normalise_data_points(self):

3 Source : utils.py
with MIT License
from andrewekhalel

def flip_ud(img):
	"""
	Flips an image upside-down

	:param img: input image

	:returns: flipped image
	"""
	return np.flipud(img)

def flip_lr(img):

3 Source : video_transforms.py
with MIT License
from artest08

    def __call__(self, clips):
        if random.random()   <   0.5:
            clips = np.flipud(clips)
            clips = np.ascontiguousarray(clips)
        return clips


class RandomSizedCrop(object):

3 Source : augment.py
with Apache License 2.0
from Ascend

    def __call__(self, img, labels, mode=None):
        if random.random()   <   self.p:
            img = np.flipud(img)
            if mode == 'cxywha': 
                labels[:, 2] = img.shape[0] - labels[:, 2]
                labels[:, 5] = -labels[:, 5]
            if mode == 'xyxyxyxy':
                labels[:, [1,3,5,7]] = img.shape[0] - labels[:, [1,3,5,7]]
            if mode == 'xywha':
                labels[:, 1] = img.shape[0] - labels[:, 1]
                labels[:, -1] = -labels[:, -1]   
        return img, labels 


class Affine(object):

3 Source : augmentation.py
with GNU General Public License v3.0
from bismex

    def __call__(self, image: torch.Tensor, is_mask=False):
        if isinstance(image, torch.Tensor):
            return self.crop_to_output(image.flip((2,)))
        else:
            return np.flipud(image)

class Translation(Transform):

3 Source : augmentations.py
with MIT License
from BloodAxe

    def __call__(self, img, mask=None):
        if random.random()   <   self.prob:
            img = np.flipud(img).copy()
            if mask is not None:
                mask = np.flipud(mask).copy()
        return img, mask


class HorizontalFlip:

3 Source : augmentation.py
with Apache License 2.0
from CASIA-IVA-Lab

    def __call__(self, image: torch.Tensor):
        if isinstance(image, torch.Tensor):
            return self.crop_to_output(image.flip((2,)))
        else:
            return np.flipud(image)

class Translation(Transform):

3 Source : viewer2D.py
with MIT License
from CEMES-CNRS

    def transform_image(self, data):
        if self.view.is_action_checked('flip_ud'):
            data = np.flipud(data)
        if self.view.is_action_checked('flip_lr'):
            data = np.fliplr(data)
        if self.view.is_action_checked('rotate'):
            data = np.flipud(np.transpose(data))
        return data

    def set_visible_items(self):

3 Source : img_transforms.py
with MIT License
from chuchienshu

    def __call__(self, inputs):
        if random.random()   <   0.5:
            inputs[0] = np.copy(np.flipud(inputs[0]))
            inputs[1] = np.copy(np.flipud(inputs[1]))

        return inputs


class RandomRotate(object):

3 Source : video_utils.py
with MIT License
from CPJKU

def prepare_spec_for_render(spec, score, scale_factor=5):
    spec_excerpt = cv2.resize(np.flipud(spec), (spec.shape[1] * scale_factor, spec.shape[0] * scale_factor))

    perf_img = np.pad(cm.viridis(spec_excerpt)[:, :, :3],
                      ((score.shape[0] // 2 - spec_excerpt.shape[0] // 2 + 1,
                        score.shape[0] // 2 - spec_excerpt.shape[0] // 2),
                       (20, 20), (0, 0)), mode="constant")

    return perf_img


def get_transparent_cmap(source_cmap, alpha, n_steps_blend):

3 Source : image_transforms.py
with MIT License
from cypw

    def __call__(self, data):
        if self.rng.rand()   <   0.5:
            data = np.flipud(data)
            data = np.ascontiguousarray(data)
        return data

class RandomRGB(Transform):

3 Source : dataset_tests.py
with MIT License
from czbiohub

    def test_augment_image_ud(self):
        trans_im = self.data_inst._augment_image(self.im, 2)
        for i in range(2):
            np.testing.assert_array_equal(
                trans_im[..., i],
                np.flipud(self.im[..., i]),
            )

    def test_augment_image_rot90(self):

3 Source : test_twodim_base.py
with Apache License 2.0
from dashanji

    def test_basic(self):
        a = get_mat(4)
        b = a[::-1, :]
        assert_equal(flipud(a), b)
        a = [[0, 1, 2],
             [3, 4, 5]]
        b = [[3, 4, 5],
             [0, 1, 2]]
        assert_equal(flipud(a), b)


class TestHistogram2d:

3 Source : sprite_test.py
with Apache License 2.0
from deepmind

  def testContainsPoint(self, x, y, shape, angle, scale, containment):
    # As we use plots to prepare these tests, it's easier to write the matrix
    # "in the wrong orientation" (i.e. with origin='lower') and flip it.
    containment = np.flipud(containment)
    linspace = np.linspace(0.1, 0.9, 4)
    grid = np.stack(np.meshgrid(linspace, linspace), axis=-1)
    s = sprite.Sprite(x=x, y=y, shape=shape, angle=angle, scale=scale)

    eval_containment = np.array(
        [[s.contains_point(p) for p in row] for row in grid])
    self.assertTrue(np.allclose(eval_containment, containment))

  @parameterized.parameters(

3 Source : rotate_flip_invert.py
with Apache License 2.0
from DIAGNijmegen

def flip_x(np_array_in, preserve_dtype=True):
    """
    A method to flip horizontally (switch image left and right sides)
    If preserve_dtype is true then the result will be returned as the original
    data type.
    Resulting grey-values will be rescaled to min-max values of that dtype
    :param np_array_in: input image
    :param preserve_dtype: whether to preserve dtype
    :return: the horizontally flipped image
    """
    flipx = flipud(np_array_in)
    if preserve_dtype:
        # cast back to original type, first rescaling to min/max for that type
        flipx = rescale_to_min_max(flipx, np_array_in.dtype, new_min=None, new_max=None)
    return flipx


def flip_y(np_array_in, preserve_dtype=True):

3 Source : box3d_renderer.py
with MIT License
from DLR-RM

    def upload_edges(self, scale, pixels):
        H, W = pixels.shape[:2]
        pixels = np.ascontiguousarray(np.flipud(pixels))
        self._edge_tex.subImage(0, 0, 0, W, H, GL_RG, GL_FLOAT, pixels)

    def render(self, obj_id, K, R, t, near, far, row=0.0, col=0.0, reconst=False):

3 Source : world.py
with MIT License
from EvolutionGym

    def get_structure(self) -> np.ndarray:
        """
        Return an object's structure matrix.

        Return:
            np.ndarray: `(n, m)` array specifing the voxel structure of the object. See `evogym.VOXEL_TYPES`.
        """
        return np.flipud(self.grid)

    def get_connections(self) -> np.ndarray:

3 Source : image_transforms.py
with MIT License
from facebookresearch

    def __call__(self, data, idx=None, copy_id=0):
        if self.rng.rand()   <   0.5:
            data = np.flipud(data)
            data = np.ascontiguousarray(data)
        return data

class PixelJitter(Transform):

3 Source : utils.py
with MIT License
from fancompute

def imarr(arr):
    """ puts array 'arr' into form ready to plot """
    arr_value = get_value(arr)
    arr_plot = arr_value.copy()
    if len(arr.shape) == 3:
        arr_plot = arr_plot[:,:,0]
    return np.flipud(arr_plot.T)


""" ====================== FOURIER TRANSFORMS  ======================"""

3 Source : tsfm.py
with MIT License
from FarhadMaleki

    def __call__(self, image):
        """
        Args:
            image (skimag Image): Image to be flipped.

        Returns:
            skimage Image: Randomly flipped image.
        """
        if random.random()   <   self.p:
            image = np.flipud(image).copy()
        return image

    def __repr__(self):

3 Source : HarmonicVMDCylWidget.py
with MIT License
from geoscixyz

    def mirrorArray(self, x, direction="x"):
        X = x.reshape((self.nx_core, self.ny_core), order="F")
        if direction == "x" or direction == "y":
            X2 = np.vstack((-np.flipud(X), X))
        else:
            X2 = np.vstack((np.flipud(X), X))
        return X2

    def genMesh(self, h=0.0, cs=3.0, ncx=15, ncz=30, npad=20):

3 Source : Data_Augmentation.py
with GNU General Public License v3.0
from GongJingUSST

def img_flip_v(image,prob=1):
    generator = generator_class(prob)
    if generator:
        img = np.flipud(image)
    else:
        img = []
    return img

def img_exposure_gamma(image,gamma,prob=1):

3 Source : run.py
with Apache License 2.0
from gradio-app

def reverse_audio(audio):
    sr, data = audio
    return (sr, np.flipud(data))


iface = gr.Interface(reverse_audio, "microphone", "audio", examples="audio")

3 Source : flip.py
with MIT License
from harshavkumar

    def _augment_images(self, images, random_state, parents, hooks):
        nb_images = len(images)
        samples = self.p.draw_samples((nb_images,), random_state=random_state)
        for i in sm.xrange(nb_images):
            if samples[i] == 1:
                images[i] = np.flipud(images[i])
        return images

    def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks):

3 Source : data_augmentation.py
with GNU General Public License v3.0
from hsd1503

    def _random_flip_updown(self, batch):
        for i in range(len(batch)):
            if bool(random.getrandbits(1)):
                batch[i] = np.flipud(batch[i])
        return batch

    def _random_90degrees_rotation(self, batch, rotations=[0, 1, 2, 3]):

3 Source : data_utils.py
with GNU General Public License v3.0
from hsd1503

def random_flip_updown(x):
    if bool(random.getrandbits(1)):
        return np.flipud(x)
    else:
        return x


# ==================
#     DATA UTILS
# ==================


def shuffle(*arrs):

3 Source : ultrafastLaneDetector.py
with MIT License
from ibaiGorordo

	def draw_lanes(input_img, lanes_points, lanes_detected, cfg, draw_points=True):
		# Write the detected line points in the image
		visualization_img = cv2.resize(input_img, (cfg.img_w, cfg.img_h), interpolation = cv2.INTER_AREA)

		# Draw a mask for the current lane
		if(lanes_detected[1] and lanes_detected[2]):
			lane_segment_img = visualization_img.copy()
			
			cv2.fillPoly(lane_segment_img, pts = [np.vstack((lanes_points[1],np.flipud(lanes_points[2])))], color =(255,191,0))
			visualization_img = cv2.addWeighted(visualization_img, 0.7, lane_segment_img, 0.3, 0)

		if(draw_points):
			for lane_num,lane_points in enumerate(lanes_points):
				for lane_point in lane_points:
					cv2.circle(visualization_img, (lane_point[0],lane_point[1]), 3, lane_colors[lane_num], -1)

		return visualization_img

	







3 Source : data_utils.py
with MIT License
from imjoy-team

def fig2img(fig):
    """Convert a Matplotlib figure to a PIL Image and return it"""
    buf = io.BytesIO()
    fig.savefig(buf)
    buf.seek(0)
    img = np.flipud(imageio.imread(buf))
    return img


def plot_images(images, masks, original_image=None, original_mask=None):

3 Source : test_interactive_trainer.py
with MIT License
from imjoy-team

def test_aug_plot():
    tmp = trainer.plot_augmentations()
    tmp = np.flipud(tmp)
    imwrite("./data/hpa_dataset_v2/test_aug.png", tmp)


if __name__ == "__main__":

3 Source : edit.py
with MIT License
from J08nY

def reverse(trace: Trace) -> Trace:
    """
    Reverse the samples of the `trace`.

    :param trace:
    :return:
    """
    return trace.with_samples(np.flipud(trace.samples))


@public

3 Source : flip.py
with Apache License 2.0
from jim-schwoebel

    def _augment_images(self, images, random_state, parents, hooks):
        nb_images = len(images)
        samples = self.p.draw_samples((nb_images,), random_state=random_state)
        for i, (image, sample) in enumerate(zip(images, samples)):
            if sample > 0.5:
                images[i] = np.flipud(image)
        return images

    def _augment_heatmaps(self, heatmaps, random_state, parents, hooks):

3 Source : utils.py
with ISC License
from jordipons

def matrix_visualization(matrix,title=None):
    """ Visualize 2D matrices like spectrograms or feature maps.
    """
    plt.figure()
    plt.imshow(np.flipud(matrix.T),interpolation=None)
    plt.colorbar()
    if title!=None:
        plt.title(title)
    plt.show()


def wavefile_to_waveform(wav_file, features_type):

3 Source : flow_transforms.py
with MIT License
from jytime

    def __call__(self, inputs, target):
        if random.random()   <   0.5:
            inputs[0] = np.copy(np.flipud(inputs[0]))
            inputs[1] = np.copy(np.flipud(inputs[1]))
            target = np.copy(np.flipud(target))
            target[:,:,1] *= -1
        return inputs,target


class RandomRotate(object):

3 Source : asr.py
with Apache License 2.0
from k2-fsa

    def plot_alignments(self, cut: Cut):
        import matplotlib.pyplot as plt
        feats = self.compute_features(cut)
        phone_ids = self.align(cut)
        fig, axes = plt.subplots(2, squeeze=True, sharey=True, figsize=(10, 14))
        axes[0].imshow(np.flipud(feats[0].T))
        axes[1].imshow(torch.nn.functional.one_hot(phone_ids.repeat_interleave(4).to(torch.int64)).T)
        return fig, axes

    def plot_posteriors(self, cut: Cut):

3 Source : asr.py
with Apache License 2.0
from k2-fsa

    def plot_posteriors(self, cut: Cut):
        import matplotlib.pyplot as plt
        feats = self.compute_features(cut)
        posteriors = self.compute_posteriors(cut)
        fig, axes = plt.subplots(2, squeeze=True, sharey=True, figsize=(10, 14))
        axes[0].imshow(np.flipud(feats[0].T))
        axes[1].imshow(posteriors[0].exp().repeat_interleave(4, 1))
        return fig, axes

    @staticmethod

3 Source : mapping.py
with MIT License
from KMarkert

def _griddingWrapper(args):
    pts,rasterArr,xx,yy,method,i = args
    return np.flipud(interpolate.griddata(pts,rasterArr[:,:,0,i,0].ravel(),(xx,yy),method=method))

# @staticmethod
def swath2grid(rasterArr,xgrid,ygrid,resolution=500,method='nearest'):

3 Source : test_twodim_base.py
with MIT License
from ktraunmueller

    def test_basic(self):
        a = get_mat(4)
        b = a[::-1,:]
        assert_equal(flipud(a), b)
        a = [[0, 1, 2],
             [3, 4, 5]]
        b = [[3, 4, 5],
             [0, 1, 2]]
        assert_equal(flipud(a), b)

class TestRot90(TestCase):

3 Source : co_transforms.py
with MIT License
from Kwanss

    def __call__(self, inputs, targets):
        if random.random()   <   0.5:
            inputs = [np.copy(np.flipud(A)) for A in inputs]
            if targets is not None:
                targets = [np.copy(np.flipud(T)) for T in targets]
                for T in targets:
                    T[:, :, 1] *= -1
        return inputs, targets


class RandomRotate(object):

3 Source : _polyline_object.py
with BSD 2-Clause "Simplified" License
from lace

    def flipped(self):
        """
        Flip the polyline from end to end. Return a new polyline.
        """
        return Polyline(v=np.flipud(self.v), is_closed=self.is_closed)

    def flipped_if(self, condition):

3 Source : sample.py
with BSD 3-Clause "New" or "Revised" License
from leddartech

    def transform_image(self, image):
        # Transform the bottom left origin of LCAx to top-left camera origin
        image = np.flipud(image)

        operation = self._get_orientation_lut()
        if operation is not None:
            return np.copy(eval(operation.format('image')))

        return np.copy(image)

    @staticmethod

3 Source : data_utils.py
with MIT License
from limingwu8

def flip_masks(masks, y_flip=False, x_flip=False):
    masks = masks.copy()
    for i in range(masks.shape[0]):
        if y_flip:
            masks[i] = np.flipud(masks[i]).copy()
        if x_flip:
            masks[i] = np.fliplr(masks[i]).copy()
    return masks

def random_flip(img, y_random=False, x_random=False,

3 Source : flip.py
with GNU General Public License v3.0
from liuguiyangnwpu

    def _augment_images(self, images, random_state, parents, hooks):
        nb_images = len(images)
        samples = self.p.draw_samples((nb_images,), random_state=random_state)
        for i in range(nb_images):
            if samples[i] == 1:
                images[i] = np.flipud(images[i])
        return images

    def _augment_keypoints(self,

3 Source : misc.py
with Mozilla Public License 2.0
from mehrhardt

    def adjoint(self):
        adjoint_kernel = self.kernel.copy().conj()
        adjoint_kernel = np.fliplr(np.flipud(adjoint_kernel))

        return Blur2D(self.domain, adjoint_kernel, self.boundary_condition)

    def __repr__(self):

3 Source : test_numpy_functions.py
with MIT License
from mhostetter

def test_flipud(field):
    dtype = random.choice(field.dtypes)
    shape = (2,3)
    a = field.Random(shape, dtype=dtype)
    b = np.flipud(a)
    assert array_equal(b, a[::-1,:])
    assert type(b) is field


def test_roll(field):

3 Source : augmentation.py
with MIT License
from minerva-ml

def test_time_augmentation_transform(image, tta_parameters):
    if tta_parameters['ud_flip']:
        image = np.flipud(image)
    if tta_parameters['lr_flip']:
        image = np.fliplr(image)
    image = rotate(image, tta_parameters['rotation'])

    if tta_parameters['color_shift']:
        tta_intensity = reseed(tta_intensity_seq, deterministic=False)
        image = tta_intensity.augment_image(image)

    return image


def test_time_augmentation_inverse_transform(image, tta_parameters):

3 Source : augmentation.py
with MIT License
from minerva-ml

def per_channel_flipud(x):
    x_ = x.copy()
    for i, channel in enumerate(x):
        x_[i, :, :] = np.flipud(channel)
    return x_


def per_channel_fliplr(x):

3 Source : experiment.py
with MIT License
from mjablons1

    def calculate_cm_phase(self):
        input_frame = self.streaming_device.get_monitor()
        phase_frame = np.dot(self.rot_matrix_45, np.flipud(input_frame))
        return phase_frame.T

    def calculate_fm_fft(self, input_frame=None):

3 Source : loaders.py
with MIT License
from neptune-ai

def test_time_augmentation_transform(image, tta_parameters):
    if tta_parameters['ud_flip']:
        image = np.flipud(image)
    elif tta_parameters['lr_flip']:
        image = np.fliplr(image)
    elif tta_parameters['color_shift']:
        random_color_shift = reseed(color_seq, deterministic=False)
        image = random_color_shift.augment_image(image)
    image = rotate(image, tta_parameters['rotation'], preserve_range=True)
    return image


def test_time_augmentation_inverse_transform(image, tta_parameters):

See More Examples