Python numpy.rot90() Examples

The following are 30 code examples for showing how to use numpy.rot90(). 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: unicorn-hat-hd   Author: pimoroni   File: __init__.py    License: 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
Project: KAIR   Author: cszn   File: utils_image.py    License: 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 3
Project: KAIR   Author: cszn   File: utils_image.py    License: 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 4
Project: KAIR   Author: cszn   File: utils_image.py    License: 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 5
Project: kits19.MIScnn   Author: muellerdo   File: preprocessing.py    License: 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 6
Project: TENet   Author: guochengqian   File: Prepro.py    License: 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 7
Project: trax   Author: google   File: array_ops.py    License: 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 8
Project: pixelworld   Author: vicariousinc   File: pattern_generator.py    License: 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 9
Project: hamaa   Author: monitor1379   File: np_utils.py    License: 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 10
Project: MDT   Author: robbert-harms   File: matplotlib_renderer.py    License: 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 11
Project: unicorn-hat-hd   Author: pimoroni   File: __init__.py    License: 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 12
Project: FRIDA   Author: LCAV   File: mkl_fft.py    License: MIT License 5 votes vote down vote up
def cce2full(A):

    # Assume all square for now

    N = A.shape
    N_half = N[0]//2 + 1
    out = np.empty((A.shape[0], A.shape[0]), dtype=A.dtype)
    out[:, :N_half] = A

    out[1:, N_half:] = np.rot90(A[1:, 1:-1], 2).conj()

    # Complete the first row
    out[0, N_half:] = A[0, -2:0:-1].conj()

    return out 
Example 13
Project: alpha-zero   Author: blanyal   File: train.py    License: MIT License 5 votes vote down vote up
def augment_data(self, game_state, training_data, row, column):
        """Loop for each self-play game.

        Runs MCTS for each game state and plays a move based on the MCTS output.
        Stops when the game is over and prints out a winner.

        Args:
            game_state: An object containing the state, pis and value.
            training_data: A list to store self play states, pis and vs.
            row: An integer indicating the length of the board row.
            column: An integer indicating the length of the board column.
        """
        state = deepcopy(game_state[0])
        psa_vector = deepcopy(game_state[1])

        if CFG.game == 2 or CFG.game == 1:
            training_data.append([state, psa_vector, game_state[2]])
        else:
            psa_vector = np.reshape(psa_vector, (row, column))

            # Augment data by rotating and flipping the game state.
            for i in range(4):
                training_data.append([np.rot90(state, i),
                                      np.rot90(psa_vector, i).flatten(),
                                      game_state[2]])

                training_data.append([np.fliplr(np.rot90(state, i)),
                                      np.fliplr(
                                          np.rot90(psa_vector, i)).flatten(),
                                      game_state[2]]) 
Example 14
Project: rcan-tensorflow   Author: kozistr   File: util.py    License: MIT License 5 votes vote down vote up
def rotate(images):
    images = np.append(images, [np.fliplr(image) for image in images], axis=0)  # 180 degree
    images = np.append(images, [np.rot90(image) for image in images], axis=0)   # 90 degree
    return images 
Example 15
Project: open-solution-salt-identification   Author: neptune-ai   File: augmentation.py    License: MIT License 5 votes vote down vote up
def rotate(image, angle, axes=(0, 1)):
    if angle % 90 != 0:
        raise Exception('Angle must be a multiple of 90.')
    k = angle // 90
    return np.rot90(image, k, axes=axes) 
Example 16
Project: open-solution-salt-identification   Author: neptune-ai   File: utils.py    License: MIT License 5 votes vote down vote up
def get_cut_coordinates(mask, step=4, min_img_crop=20, min_size=50, max_size=300):
    h, w = mask.shape
    ts = []
    rots = [1, 2, 3, 0]
    for rot in rots:
        mask = np.rot90(mask)
        for t in range(min_img_crop, h, step):
            crop = mask[:t, :t]
            size = crop.mean() * h * w
            if min_size < size <= max_size:
                break
        ts.append((t, rot))
    try:
        ts = [(t, r) for t, r in ts if t < 99]
        best_t, best_rot = sorted(ts, key=lambda x: x[0], reverse=True)[0]
    except IndexError:
        return (0, w), (0, h), False
    if best_t < min_img_crop:
        return (0, w), (0, h), False

    if best_rot == 0:
        x1, x2, y1, y2 = 0, best_t, 0, best_t
    elif best_rot == 1:
        x1, x2, y1, y2 = 0, best_t, h - best_t, h
    elif best_rot == 2:
        x1, x2, y1, y2 = w - best_t, w, h - best_t, h
    elif best_rot == 3:
        x1, x2, y1, y2 = w - best_t, w, 0, best_t
    else:
        raise ValueError
    return (x1, x2), (y1, y2), True 
Example 17
Project: robustness   Author: hendrycks   File: corruptions.py    License: Apache License 2.0 5 votes vote down vote up
def snow(x, severity=1):
    c = [(0.1, 0.3, 3, 0.5, 10, 4, 0.8),
         (0.2, 0.3, 2, 0.5, 12, 4, 0.7),
         (0.55, 0.3, 4, 0.9, 12, 8, 0.7),
         (0.55, 0.3, 4.5, 0.85, 12, 8, 0.65),
         (0.55, 0.3, 2.5, 0.85, 12, 12, 0.55)][severity - 1]

    x = np.array(x, dtype=np.float32) / 255.
    snow_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])  # [:2] for monochrome

    snow_layer = clipped_zoom(snow_layer[..., np.newaxis], c[2])
    snow_layer[snow_layer < c[3]] = 0

    snow_layer = PILImage.fromarray((np.clip(snow_layer.squeeze(), 0, 1) * 255).astype(np.uint8), mode='L')
    output = BytesIO()
    snow_layer.save(output, format='PNG')
    snow_layer = MotionImage(blob=output.getvalue())

    snow_layer.motion_blur(radius=c[4], sigma=c[5], angle=np.random.uniform(-135, -45))

    snow_layer = cv2.imdecode(np.fromstring(snow_layer.make_blob(), np.uint8),
                              cv2.IMREAD_UNCHANGED) / 255.
    snow_layer = snow_layer[..., np.newaxis]

    x = c[6] * x + (1 - c[6]) * np.maximum(x, cv2.cvtColor(x, cv2.COLOR_RGB2GRAY).reshape(224, 224, 1) * 1.5 + 0.5)
    return np.clip(x + snow_layer + np.rot90(snow_layer, k=2), 0, 1) * 255 
Example 18
Project: robustness   Author: hendrycks   File: make_imagenet_c.py    License: Apache License 2.0 5 votes vote down vote up
def snow(x, severity=1):
    c = [(0.1, 0.3, 3, 0.5, 10, 4, 0.8),
         (0.2, 0.3, 2, 0.5, 12, 4, 0.7),
         (0.55, 0.3, 4, 0.9, 12, 8, 0.7),
         (0.55, 0.3, 4.5, 0.85, 12, 8, 0.65),
         (0.55, 0.3, 2.5, 0.85, 12, 12, 0.55)][severity - 1]

    x = np.array(x, dtype=np.float32) / 255.
    snow_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])  # [:2] for monochrome

    snow_layer = clipped_zoom(snow_layer[..., np.newaxis], c[2])
    snow_layer[snow_layer < c[3]] = 0

    snow_layer = PILImage.fromarray((np.clip(snow_layer.squeeze(), 0, 1) * 255).astype(np.uint8), mode='L')
    output = BytesIO()
    snow_layer.save(output, format='PNG')
    snow_layer = MotionImage(blob=output.getvalue())

    snow_layer.motion_blur(radius=c[4], sigma=c[5], angle=np.random.uniform(-135, -45))

    snow_layer = cv2.imdecode(np.fromstring(snow_layer.make_blob(), np.uint8),
                              cv2.IMREAD_UNCHANGED) / 255.
    snow_layer = snow_layer[..., np.newaxis]

    x = c[6] * x + (1 - c[6]) * np.maximum(x, cv2.cvtColor(x, cv2.COLOR_RGB2GRAY).reshape(224, 224, 1) * 1.5 + 0.5)
    return np.clip(x + snow_layer + np.rot90(snow_layer, k=2), 0, 1) * 255 
Example 19
Project: robustness   Author: hendrycks   File: make_cifar_c.py    License: Apache License 2.0 5 votes vote down vote up
def snow(x, severity=1):
    c = [(0.1,0.2,1,0.6,8,3,0.95),
         (0.1,0.2,1,0.5,10,4,0.9),
         (0.15,0.3,1.75,0.55,10,4,0.9),
         (0.25,0.3,2.25,0.6,12,6,0.85),
         (0.3,0.3,1.25,0.65,14,12,0.8)][severity - 1]

    x = np.array(x, dtype=np.float32) / 255.
    snow_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])  # [:2] for monochrome

    snow_layer = clipped_zoom(snow_layer[..., np.newaxis], c[2])
    snow_layer[snow_layer < c[3]] = 0

    snow_layer = PILImage.fromarray((np.clip(snow_layer.squeeze(), 0, 1) * 255).astype(np.uint8), mode='L')
    output = BytesIO()
    snow_layer.save(output, format='PNG')
    snow_layer = MotionImage(blob=output.getvalue())

    snow_layer.motion_blur(radius=c[4], sigma=c[5], angle=np.random.uniform(-135, -45))

    snow_layer = cv2.imdecode(np.fromstring(snow_layer.make_blob(), np.uint8),
                              cv2.IMREAD_UNCHANGED) / 255.
    snow_layer = snow_layer[..., np.newaxis]

    x = c[6] * x + (1 - c[6]) * np.maximum(x, cv2.cvtColor(x, cv2.COLOR_RGB2GRAY).reshape(32, 32, 1) * 1.5 + 0.5)
    return np.clip(x + snow_layer + np.rot90(snow_layer, k=2), 0, 1) * 255 
Example 20
Project: robustness   Author: hendrycks   File: make_tinyimagenet_c.py    License: Apache License 2.0 5 votes vote down vote up
def snow(x, severity=1):
    c = [(0.1,0.2,1,0.6,8,3,0.8),
         (0.1,0.2,1,0.5,10,4,0.8),
         (0.15,0.3,1.75,0.55,10,4,0.7),
         (0.25,0.3,2.25,0.6,12,6,0.65),
         (0.3,0.3,1.25,0.65,14,12,0.6)][severity - 1]

    x = np.array(x, dtype=np.float32) / 255.
    snow_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])  # [:2] for monochrome

    snow_layer = clipped_zoom(snow_layer[..., np.newaxis], c[2])
    snow_layer[snow_layer < c[3]] = 0

    snow_layer = PILImage.fromarray((np.clip(snow_layer.squeeze(), 0, 1) * 255).astype(np.uint8), mode='L')
    output = BytesIO()
    snow_layer.save(output, format='PNG')
    snow_layer = MotionImage(blob=output.getvalue())

    snow_layer.motion_blur(radius=c[4], sigma=c[5], angle=np.random.uniform(-135, -45))

    snow_layer = cv2.imdecode(np.fromstring(snow_layer.make_blob(), np.uint8),
                              cv2.IMREAD_UNCHANGED) / 255.
    snow_layer = snow_layer[..., np.newaxis]

    x = c[6] * x + (1 - c[6]) * np.maximum(x, cv2.cvtColor(x, cv2.COLOR_RGB2GRAY).reshape(64, 64, 1) * 1.5 + 0.5)
    return np.clip(x + snow_layer + np.rot90(snow_layer, k=2), 0, 1) * 255 
Example 21
Project: robustness   Author: hendrycks   File: make_imagenet_c_inception.py    License: Apache License 2.0 5 votes vote down vote up
def snow(x, severity=1):
    c = [(0.1, 0.3, 3, 0.5, 10, 4, 0.8),
         (0.2, 0.3, 2, 0.5, 12, 4, 0.7),
         (0.55, 0.3, 4, 0.9, 12, 8, 0.7),
         (0.55, 0.3, 4.5, 0.85, 12, 8, 0.65),
         (0.55, 0.3, 2.5, 0.85, 12, 12, 0.55)][severity - 1]

    x = np.array(x, dtype=np.float32) / 255.
    snow_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])  # [:2] for monochrome

    snow_layer = clipped_zoom(snow_layer[..., np.newaxis], c[2])
    snow_layer[snow_layer < c[3]] = 0

    snow_layer = PILImage.fromarray((np.clip(snow_layer.squeeze(), 0, 1) * 255).astype(np.uint8), mode='L')
    output = BytesIO()
    snow_layer.save(output, format='PNG')
    snow_layer = MotionImage(blob=output.getvalue())

    snow_layer.motion_blur(radius=c[4], sigma=c[5], angle=np.random.uniform(-135, -45))

    snow_layer = cv2.imdecode(np.fromstring(snow_layer.make_blob(), np.uint8),
                              cv2.IMREAD_UNCHANGED) / 255.
    snow_layer = snow_layer[..., np.newaxis]

    x = c[6] * x + (1 - c[6]) * np.maximum(x, cv2.cvtColor(x, cv2.COLOR_RGB2GRAY).reshape(299, 299, 1) * 1.5 + 0.5)
    return np.clip(x + snow_layer + np.rot90(snow_layer, k=2), 0, 1) * 255 
Example 22
Project: openag_brain_box   Author: OpenAgricultureFoundation   File: gui.py    License: GNU General Public License v3.0 5 votes vote down vote up
def convertFigureToSurface(self, fig):
        fig.canvas.draw()
        buf = fig.canvas.tostring_rgb()
        ncols, nrows = fig.canvas.get_width_height()
        array = np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3)
        array = np.fliplr(array)
        array = np.rot90(array)
        surface = pygame.surfarray.make_surface(array)
        pygame.transform.scale(surface,(800,480))
        return surface 
Example 23
Project: openag_brain_box   Author: OpenAgricultureFoundation   File: gui.py    License: GNU General Public License v3.0 5 votes vote down vote up
def runMatplotEx(self):
        x = np.arange (0, 100, 0.1)
        y = np.sin(x)/x
        self.plot.plot(x, y)
        array = self.convertFigureToRGB(self.figure)
        array = np.fliplr(array)
        array = np.rot90(array)
        surface = pygame.surfarray.make_surface(array)
        surface = pygame.transform.scale(surface,(800,480))
        self.screen.blit(surface,(0,0)) 
Example 24
Project: sonopy   Author: MycroftAI   File: comparison.py    License: Apache License 2.0 5 votes vote down vote up
def show_audio(url):
    signal = np.squeeze(wavio.read(BytesIO(requests.get(url).content)).data).astype('f')
    signal /= signal.max()
    for name, calc_mfcc, get_args in libraries:
        res = calc_mfcc(**get_args(signal, 0.01, 512))
        if len(res) < len(res[0]):
            res = np.rot90(res)
        Arriz.show(name, res[:, 1:]) 
Example 25
Project: chainer-compiler   Author: pfnet-research   File: random_rotate.py    License: MIT License 5 votes vote down vote up
def random_rotate(img, return_param=False):
    """Randomly rotate images by 90, 180, 270 or 360 degrees.

    Args:
        img (~numpy.ndarray): An arrays that get flipped. This is in
            CHW format.
        return_param (bool): Returns information of rotation.

    Returns:
        ~numpy.ndarray or (~numpy.ndarray, dict):

        If :obj:`return_param = False`,
        returns an array :obj:`out_img` that is the result of rotation.

        If :obj:`return_param = True`,
        returns a tuple whose elements are :obj:`out_img, param`.
        :obj:`param` is a dictionary of intermediate parameters whose
        contents are listed below with key, value-type and the description
        of the value.

        * **k** (*int*): The integer that represents the number of\
            times the image is rotated by 90 degrees.

    """
    warnings.warn(
        'chainercv.transforms.random_rotate is deprecated. '
        'Please use a random function and chainercv.transforms.rotate '
        'instead.', DeprecationWarning)
    k = np.random.randint(4)
    img = np.transpose(img, axes=(1, 2, 0))
    img = np.rot90(img, k)
    img = np.transpose(img, axes=(2, 0, 1))
    if return_param:
        return img, {'k': k}
    else:
        return img 
Example 26
Project: terrain-erosion-3-ways   Author: dandrino   File: generate_training_images.py    License: MIT License 5 votes vote down vote up
def get_variants(a):
  for b in (a, a.T):  # Original and flipped.
    for k in range(0, 4):   # Rotated 90 degrees x 4
      yield np.rot90(b, k) 
Example 27
Project: st7789-python   Author: pimoroni   File: __init__.py    License: MIT License 5 votes vote down vote up
def image_to_data(self, image, rotation=0):
        """Generator function to convert a PIL image to 16-bit 565 RGB bytes."""
        # NumPy is much faster at doing this. NumPy code provided by:
        # Keith (https://www.blogger.com/profile/02555547344016007163)
        pb = np.rot90(np.array(image.convert('RGB')), rotation // 90).astype('uint8')

        result = np.zeros((self._width, self._height, 2), dtype=np.uint8)
        result[..., [0]] = np.add(np.bitwise_and(pb[..., [0]], 0xF8), np.right_shift(pb[..., [1]], 5))
        result[..., [1]] = np.add(np.bitwise_and(np.left_shift(pb[..., [1]], 3), 0xE0), np.right_shift(pb[..., [2]], 3))
        return result.flatten().tolist() 
Example 28
Project: Text-Recognition   Author: mayank-git-hub   File: dete_loader.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def rotate(self, image, target, link, contour, angle):

		if angle == 0:
			if link is None:
				return image, target, contour
			return image, target, link, contour

		elif angle == 90:
			image = image.transpose(Image.ROTATE_90)
			target = target.transpose(Image.ROTATE_90)
			link = np.rot90(link)

			contour_f = self.contour_rotate(contour, 90, image.size[0], image.size[1])

		elif angle == 180:

			image = image.transpose(Image.ROTATE_180)
			target = target.transpose(Image.ROTATE_180)
			link = np.rot90(np.rot90(link))
			contour_f = self.contour_rotate(contour, 180, image.size[1], image.size[0])

		elif angle == 270:
			image = image.transpose(Image.ROTATE_270)
			target = target.transpose(Image.ROTATE_270)
			link = np.rot90(np.rot90(np.rot90(link)))
			contour_f = self.contour_rotate(contour, 270, image.size[0], image.size[1])

		if link is None:
				return image, target, contour_f

		return image, target, link, contour_f 
Example 29
Project: vae_tacotron2   Author: rishikksh20   File: plot.py    License: MIT License 5 votes vote down vote up
def plot_spectrogram(spectrogram, path, info=None, split_title=False):
	plt.figure()
	plt.imshow(np.rot90(spectrogram))
	plt.colorbar(shrink=0.65, orientation='horizontal')
	plt.ylabel('mels')
	xlabel = 'frames'
	if info is not None:
		if split_title:
			title = split_title_line(info)
		else:
			title = info
	plt.xlabel(xlabel)
	plt.title(title)
	plt.tight_layout()
	plt.savefig(path, format='png') 
Example 30
Project: aletheia   Author: daniellerch   File: models.py    License: MIT License 5 votes vote down vote up
def _train_data_generator(cover_files, stego_files, data_augm=False, 
                   shuffle=True, crop_size=256):

    cover_list = sorted(cover_files)
    stego_list = sorted(stego_files)
    nb_data = len(cover_list)

    if len(cover_list) != len(stego_list) or len(cover_list)==0:
        print("Error, check the number of files:", 
            len(cover_list), "!=", len(stego_list))
        sys.exit(0)

    img = imread(cover_list[0])[:crop_size,:crop_size]
    batch = np.empty((2, img.shape[0], img.shape[1],1), dtype='uint8')
    iterable = list(zip(cover_list, stego_list))
    while True:
        if shuffle:
            random.shuffle(iterable)
        for cover_path, stego_path in iterable:
            labels = np.array([0, 1], dtype='uint8')
            batch[0,:,:,0] = imread(cover_path)[:crop_size,:crop_size]
            batch[1,:,:,0] = imread(stego_path)[:crop_size,:crop_size]

            if data_augm:
                rot = random.randint(0,3)
                if random.random() < 0.5:
                    yield [np.rot90(batch, rot, axes=[1,2]), 
                           np.array([0,1], dtype='uint8')]
                    continue
                else:
                    yield [np.flip(np.rot90(batch, rot, axes=[1,2]), axis=2), 
                        np.array([0,1], dtype='uint8')]
                    continue

            yield [batch, labels]
# }}}        

# {{{ _test_data_generator()