Python numpy.rot90() Examples

The following are 30 code examples of numpy.rot90(). 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: __init__.py    From unicorn-hat-hd with MIT License 6 votes vote down vote up
def show():
    """Output the contents of the buffer to Unicorn HAT HD."""
    setup()
    if _addressing_enabled:
        for address in range(8):
            display = _displays[address]
            if display.enabled:
                if _buffer_width == _buffer_height or _rotation in [0, 2]:
                    window = display.get_buffer_window(numpy.rot90(_buf, _rotation))
                else:
                    window = display.get_buffer_window(numpy.rot90(_buf, _rotation))

                _spi.xfer2([_SOF + 1 + address] + (window.reshape(768) * _brightness).astype(numpy.uint8).tolist())
                time.sleep(_DELAY)
    else:
        _spi.xfer2([_SOF] + (numpy.rot90(_buf, _rotation).reshape(768) * _brightness).astype(numpy.uint8).tolist())

    time.sleep(_DELAY) 
Example #2
Source File: pattern_generator.py    From pixelworld with MIT License 6 votes vote down vote up
def _create_bowl(self, altitude_changes):
        half_width = len(altitude_changes)
        height = sum(altitude_changes) + 1

        half_bowl = np.zeros((height, half_width))

        row = 0
        for idx, ac in enumerate(altitude_changes):
            half_bowl[row, idx] = 1
            for i in xrange(ac):
                row += 1
                half_bowl[row, idx] = 1

        assert row == height-1

        bowl = np.concatenate([half_bowl, np.fliplr(half_bowl)], axis=1)

        for _ in range(self.rotations):
            bowl = np.rot90(bowl)

        return bowl 
Example #3
Source File: matplotlib_renderer.py    From MDT with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _apply_transformations(plot_config, data_slice):
    """Rotate, flip and zoom the data slice.

    Depending on the plot configuration, this will apply some transformations to the given data slice.

    Args:
        plot_config (mdt.visualization.maps.base.MapPlotConfig): the plot configuration
        data_slice (ndarray): the 2d slice of data to transform

    Returns:
        ndarray: the transformed 2d slice of data
    """
    if plot_config.rotate:
        data_slice = np.rot90(data_slice, plot_config.rotate // 90)

    if not plot_config.flipud:
        # by default we flipud to correct for matplotlib lower origin. If the user
        # sets flipud, we do not need to to it
        data_slice = np.flipud(data_slice)

    data_slice = plot_config.zoom.apply(data_slice)
    return data_slice 
Example #4
Source File: np_utils.py    From hamaa with GNU General Public License v3.0 6 votes vote down vote up
def rot180(images):
    """
    旋转图片180度。
    支持HW/CHW/NCHW三种格式的images。
    """
    out = np.empty(shape=images.shape, dtype=images.dtype)
    if images.ndim == 2:
        out = np.rot90(images, k=2)
    elif images.ndim == 3:
        for c in xrange(images.shape[0]):
            out[c] = np.rot90(images[c], k=2)
    elif images.ndim == 4:
        for n in xrange(images.shape[0]):
            for c in xrange(images.shape[1]):
                out[n][c] = np.rot90(images[n][c], k=2)
    else:
        raise Exception('Invalid ndim: ' + str(images.ndim) +
                        ', only support ndim between 2 and 4.')
    return out


# 给定函数f,自变量x以及对f的梯度df,求对x的梯度 
Example #5
Source File: utils_image.py    From KAIR with MIT License 6 votes vote down vote up
def augment_img(img, mode=0):
    '''Kai Zhang (github: https://github.com/cszn)
    '''
    if mode == 0:
        return img
    elif mode == 1:
        return np.flipud(np.rot90(img))
    elif mode == 2:
        return np.flipud(img)
    elif mode == 3:
        return np.rot90(img, k=3)
    elif mode == 4:
        return np.flipud(np.rot90(img, k=2))
    elif mode == 5:
        return np.rot90(img)
    elif mode == 6:
        return np.rot90(img, k=2)
    elif mode == 7:
        return np.flipud(np.rot90(img, k=3)) 
Example #6
Source File: utils_image.py    From KAIR with MIT License 6 votes vote down vote up
def augment_img_tensor4(img, mode=0):
    '''Kai Zhang (github: https://github.com/cszn)
    '''
    if mode == 0:
        return img
    elif mode == 1:
        return img.rot90(1, [2, 3]).flip([2])
    elif mode == 2:
        return img.flip([2])
    elif mode == 3:
        return img.rot90(3, [2, 3])
    elif mode == 4:
        return img.rot90(2, [2, 3]).flip([2])
    elif mode == 5:
        return img.rot90(1, [2, 3])
    elif mode == 6:
        return img.rot90(2, [2, 3])
    elif mode == 7:
        return img.rot90(3, [2, 3]).flip([2]) 
Example #7
Source File: utils_image.py    From KAIR with MIT License 6 votes vote down vote up
def augment_imgs(img_list, hflip=True, rot=True):
    # horizontal flip OR rotate
    hflip = hflip and random.random() < 0.5
    vflip = rot and random.random() < 0.5
    rot90 = rot and random.random() < 0.5

    def _augment(img):
        if hflip:
            img = img[:, ::-1, :]
        if vflip:
            img = img[::-1, :, :]
        if rot90:
            img = img.transpose(1, 0, 2)
        return img

    return [_augment(img) for img in img_list] 
Example #8
Source File: array_ops.py    From trax with Apache License 2.0 6 votes vote down vote up
def rot90(m, k=1, axes=(0, 1)):  # pylint: disable=missing-docstring
  m_rank = tf.rank(m)
  ax1, ax2 = utils._canonicalize_axes(axes, m_rank)  # pylint: disable=protected-access

  k = k % 4
  if k == 0:
    return m
  elif k == 2:
    return flip(flip(m, ax1), ax2)
  else:
    perm = tf.range(m_rank)
    perm = tf.tensor_scatter_nd_update(perm, [[ax1], [ax2]], [ax2, ax1])

    if k == 1:
      return transpose(flip(m, ax2), perm)
    else:
      return flip(transpose(m, perm), ax2) 
Example #9
Source File: preprocessing.py    From kits19.MIScnn with GNU General Public License v3.0 6 votes vote down vote up
def rotate_patches(patches_vol, patches_seg):
    # Initialize lists for rotated patches
    rotated_vol = []
    rotated_seg = []
    # Iterate over 90,180,270 degree (1*90, 2*90, 3*90)
    for times in range(1,4):
        # Iterate over each patch
        for i in range(len(patches_vol)):
            # Rotate volume & segmentation and cache rotated patches
            patch_vol_rotated = np.rot90(patches_vol[i], k=times, axes=(2,3))
            rotated_vol.append(patch_vol_rotated)
            patch_seg_rotated = np.rot90(patches_seg[i], k=times, axes=(2,3))
            rotated_seg.append(patch_seg_rotated)
    # Add rotated patches to the original patches lists
    patches_vol.extend(rotated_vol)
    patches_seg.extend(rotated_seg)
    # Return processed patches lists
    return patches_vol, patches_seg

# Flip patches at the provided axes 
Example #10
Source File: Prepro.py    From TENet with MIT License 6 votes vote down vote up
def data_aug(img, mode=0):
    # data augmentation
    if mode == 0:
        return img
    elif mode == 1:
        return np.flipud(img)
    elif mode == 2:
        return np.rot90(img)
    elif mode == 3:
        return np.flipud(np.rot90(img))
    elif mode == 4:
        return np.rot90(img, k=2)
    elif mode == 5:
        return np.flipud(np.rot90(img, k=2))
    elif mode == 6:
        return np.rot90(img, k=3)
    elif mode == 7:
        return np.flipud(np.rot90(img, k=3)) 
Example #11
Source File: test_rotate90.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_spatial_axes(self):
        rotate = Rotate90(spatial_axes=(0, 1))
        rotated = rotate(self.imt[0])
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 1, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated, expected)) 
Example #12
Source File: __init__.py    From unicorn-hat-hd with MIT License 5 votes vote down vote up
def get_buffer_window(self, source):
        """Grab the correct portion of the supplied buffer for this display.

        :param source: source buffer, should be a numpy array

        """
        view = source[self.x:self.x + PANEL_SHAPE[0], self.y:self.y + PANEL_SHAPE[1]]
        return numpy.rot90(view, self.rotation + 1) 
Example #13
Source File: test_rotate90.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_prob_k_spatial_axes(self):
        rotate = Rotate90(k=2, spatial_axes=(0, 1))
        rotated = rotate(self.imt[0])
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 2, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated, expected)) 
Example #14
Source File: test_spatial_transformer_sampler.py    From chainer with MIT License 5 votes vote down vote up
def _rotate_BCHW(x):
    rotated_xs = []
    for i in range(x.shape[0]):
        x_i = x[i].transpose(1, 2, 0)
        x_i = numpy.rot90(x_i)
        rotated_xs.append(x_i.transpose(2, 0, 1))
    rotated_xs = numpy.concatenate([r_x[None] for r_x in rotated_xs], axis=0)
    return rotated_xs 
Example #15
Source File: svhn.py    From Activation-Visualization-Histogram with MIT License 5 votes vote down vote up
def get_data(self, id):
        # preprocessing and data augmentation
        m = self.data[id]['image'].value/255.
        l = self.data[id]['label'].value.astype(np.float32)

        # Data augmentation: rotate 0, 90, 180, 270
        """
        rot_num = np.floor(np.random.rand(1)*4)
        for i in range(rot_num):
            m = np.rot90(m, axes=(0, 1))
        m = m + np.random.randn(*m.shape) * 1e-2
        """
        return m, l 
Example #16
Source File: cnn.py    From PaddlePaddle_code with Apache License 2.0 5 votes vote down vote up
def bp_sensitivity_map(self, sensitivity_array,
                           activator):
        '''
        计算传递到上一层的sensitivity map
        sensitivity_array: 本层的sensitivity map
        activator: 上一层的激活函数
        '''
        # 处理卷积步长,对原始sensitivity map进行扩展
        expanded_array = self.expand_sensitivity_map(
            sensitivity_array)
        # full卷积,对sensitivitiy map进行zero padding
        # 虽然原始输入的zero padding单元也会获得残差
        # 但这个残差不需要继续向上传递,因此就不计算了
        expanded_width = expanded_array.shape[2]
        zp = (self.input_width +  
              self.filter_width - 1 - expanded_width) / 2
        padded_array = padding(expanded_array, zp)
        # 初始化delta_array,用于保存传递到上一层的
        # sensitivity map
        self.delta_array = self.create_delta_array()
        # 对于具有多个filter的卷积层来说,最终传递到上一层的
        # sensitivity map相当于所有的filter的
        # sensitivity map之和
        for f in range(self.filter_number):
            filter = self.filters[f]
            # 将filter权重翻转180度
            flipped_weights = np.array(map(
                lambda i: np.rot90(i, 2), 
                filter.get_weights()))
            # 计算与一个filter对应的delta_array
            delta_array = self.create_delta_array()
            for d in range(delta_array.shape[0]):
                conv(padded_array[f], flipped_weights[d],
                    delta_array[d], 1, 0)
            self.delta_array += delta_array
        # 将计算结果与激活函数的偏导数做element-wise乘法操作
        derivative_array = np.array(self.input_array)
        element_wise_op(derivative_array, 
                        activator.backward)
        self.delta_array *= derivative_array 
Example #17
Source File: test_spatial_transformer_sampler.py    From chainer with MIT License 5 votes vote down vote up
def _rotate_grid(in_shape):
    mesh = numpy.meshgrid(
        numpy.linspace(-1., 1., num=in_shape[2]),
        numpy.linspace(-1., 1., num=in_shape[3]))
    mesh = [numpy.rot90(mesh[0]), numpy.rot90(mesh[1])]
    grid = numpy.concatenate([mesh[0][None], mesh[1][None]], axis=0)
    grid = numpy.repeat(grid[None], in_shape[0], axis=0).astype(numpy.float32)
    return grid 
Example #18
Source File: dal_env.py    From dal with MIT License 5 votes vote down vote up
def generate_map_trans(self):
		self.grid_center = ((self.grid_rows-1)/2, (self.grid_cols-1)/2)
		self.map_trans = self.map_design
		self.map_trans = shift(self.map_trans, int(self.grid_center[0]-self.true_grid.row), axis = 0, fill=1.0)
		self.map_trans = shift(self.map_trans, int(self.grid_center[1]-self.true_grid.col), axis = 1, fill=1.0)
		self.map_trans = np.rot90(self.map_trans, -self.true_grid.head) 
Example #19
Source File: test_to_numpy.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_tensor_input(self):
        test_data = torch.tensor([[1, 2], [3, 4]])
        test_data = test_data.rot90()
        self.assertFalse(test_data.is_contiguous())
        result = ToNumpy()(test_data)
        self.assertTrue(isinstance(result, np.ndarray))
        self.assertTrue(result.flags["C_CONTIGUOUS"])
        np.testing.assert_allclose(result, test_data.numpy()) 
Example #20
Source File: test_rotate90.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_k(self):
        rotate = Rotate90(k=2)
        rotated = rotate(self.imt[0])
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 2, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated, expected)) 
Example #21
Source File: test_rand_rotate90d.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_prob_k_spatial_axes(self):
        key = "test"
        rotate = RandRotate90d(keys=key, prob=1.0, max_k=2, spatial_axes=(0, 1))
        rotate.set_random_state(234)
        rotated = rotate({key: self.imt[0]})
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 1, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated[key], expected)) 
Example #22
Source File: test_rand_rotate90d.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_spatial_axes(self):
        key = "test"
        rotate = RandRotate90d(keys=key, spatial_axes=(0, 1))
        rotate.set_random_state(234)
        rotated = rotate({key: self.imt[0]})
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 0, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated[key], expected)) 
Example #23
Source File: test_rand_rotate90d.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_k(self):
        key = "test"
        rotate = RandRotate90d(keys=key, max_k=2)
        rotate.set_random_state(234)
        rotated = rotate({key: self.imt[0]})
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 0, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated[key], expected)) 
Example #24
Source File: test_rand_rotate90d.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_default(self):
        key = None
        rotate = RandRotate90d(keys=key)
        rotate.set_random_state(123)
        rotated = rotate({key: self.imt[0]})
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 0, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated[key], expected)) 
Example #25
Source File: test_rand_rotate90.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_prob_k_spatial_axes(self):
        rotate = RandRotate90(prob=1.0, max_k=2, spatial_axes=(0, 1))
        rotate.set_random_state(234)
        rotated = rotate(self.imt[0])
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 1, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated, expected)) 
Example #26
Source File: test_rand_rotate90.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_k(self):
        rotate = RandRotate90(max_k=2)
        rotate.set_random_state(234)
        rotated = rotate(self.imt[0])
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 0, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated, expected)) 
Example #27
Source File: test_rand_rotate90.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_default(self):
        rotate = RandRotate90()
        rotate.set_random_state(123)
        rotated = rotate(self.imt[0])
        expected = list()
        for channel in self.imt[0]:
            expected.append(np.rot90(channel, 0, (0, 1)))
        expected = np.stack(expected)
        self.assertTrue(np.allclose(rotated, expected)) 
Example #28
Source File: test_to_numpyd.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_tensor_input(self):
        test_data = torch.tensor([[1, 2], [3, 4]])
        test_data = test_data.rot90()
        self.assertFalse(test_data.is_contiguous())
        result = ToNumpyd(keys="img")({"img": test_data})["img"]
        self.assertTrue(isinstance(result, np.ndarray))
        self.assertTrue(result.flags["C_CONTIGUOUS"])
        np.testing.assert_allclose(result, test_data.numpy()) 
Example #29
Source File: test_to_numpyd.py    From MONAI with Apache License 2.0 5 votes vote down vote up
def test_numpy_input(self):
        test_data = np.array([[1, 2], [3, 4]])
        test_data = np.rot90(test_data)
        self.assertFalse(test_data.flags["C_CONTIGUOUS"])
        result = ToNumpyd(keys="img")({"img": test_data})["img"]
        self.assertTrue(isinstance(result, np.ndarray))
        self.assertTrue(result.flags["C_CONTIGUOUS"])
        np.testing.assert_allclose(result, test_data) 
Example #30
Source File: hierar_map_train.py    From dal with MIT License 5 votes vote down vote up
def generate_map_trans(self):
        self.grid_center = ((self.grid_rows-1)/2, (self.grid_cols-1)/2)
        self.map_trans = self.map_2d
        self.map_trans = shift(self.map_trans, int(self.grid_center[0]-self.true_grid.row), axis = 0, fill=1.0)
        self.map_trans = shift(self.map_trans, int(self.grid_center[1]-self.true_grid.col), axis = 1, fill=1.0)
        self.map_trans = np.rot90(self.map_trans, -self.true_grid.head)