Python skimage.transform.warp() Examples

The following are 30 code examples of skimage.transform.warp(). 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 skimage.transform , or try the search function .
Example #1
Source File: scalable_reference_pattern.py    From pyxem with GNU General Public License v3.0 8 votes vote down vote up
def function(self, x, y):

        signal2D = self.signal.data
        order = self.order
        d11 = self.d11.value
        d12 = self.d12.value
        d21 = self.d21.value
        d22 = self.d22.value
        t1 = self.t1.value
        t2 = self.t2.value

        D = np.array([[d11, d12, t1], [d21, d22, t2], [0.0, 0.0, 1.0]])

        shifty, shiftx = np.array(signal2D.shape[:2]) / 2

        shift = tf.SimilarityTransform(translation=[-shiftx, -shifty])
        tform = tf.AffineTransform(matrix=D)
        shift_inv = tf.SimilarityTransform(translation=[shiftx, shifty])

        transformed = tf.warp(
            signal2D, (shift + (tform + shift_inv)).inverse, order=order
        )

        return transformed 
Example #2
Source File: image_processing_common.py    From tensorflow-litterbox with Apache License 2.0 7 votes vote down vote up
def distort_affine_skimage(image, rotation=10.0, shear=5.0, random_state=None):
    if random_state is None:
        random_state = np.random.RandomState(None)

    rot = np.deg2rad(np.random.uniform(-rotation, rotation))
    sheer = np.deg2rad(np.random.uniform(-shear, shear))

    shape = image.shape
    shape_size = shape[:2]
    center = np.float32(shape_size) / 2. - 0.5

    pre = transform.SimilarityTransform(translation=-center)
    affine = transform.AffineTransform(rotation=rot, shear=sheer, translation=center)
    tform = pre + affine

    distorted_image = transform.warp(image, tform.params, mode='reflect')

    return distorted_image.astype(np.float32) 
Example #3
Source File: ocr_utils.py    From PythonMachineLearningExamples with MIT License 6 votes vote down vote up
def shear(X, skew):
    ''' given a 2D image, shear and return a 2D image
    
    parameters:
        X is the 2D image of shape (nRows, nColumns)
        skew is the amount to shear in the range 0 to 1.0
    '''
    
    rows = X.shape[0]
    cols = X.shape[1]    
    ratioY = skew*cols/rows
    matrix =  np.array( [[1, ratioY, 0] ,[0, 1, 0] ,[0, 0, 1 ]])                                         
    tp=af.ProjectiveTransform(matrix=matrix) 
    #tp  = tf.AffineTransform(scale=(.3,.3), shear=skew)    
    f = af.warp(X, tp)      
    return f
# 
# class file_names(object):
#     ''' store variants of file a file name with .jpg, .png, .box variations
#     '''
#     def __init__(selp, base_name, dir_name = ''):
#         base = base_name
#         jpeg = base_name + '.jpg'
#         png = base_name + '.png'
#         box = base_name + '.box' 
Example #4
Source File: JN721.py    From facial_expressions with Apache License 2.0 6 votes vote down vote up
def transform_img__(self, img, fn, emotion):
        self.images[fn] = {'Image': img, 'Emotion': emotion}                                            # Store original
        counter = 0

        self.images["Trans" + str(counter) + "_" + fn] = {'Image': np.fliplr(img), 'Emotion': emotion}  # FLIP the image
        counter += 1

        for deg in range(-10, 15, 5):                                        # ROTATE to be robust to camera orientation
            if deg == 0:
                continue

            self.images["Trans" + str(counter) + "_" + fn] = {'Image': tf.rotate(img, deg), 'Emotion': emotion}
            counter += 1

        lenX, lenY = img.shape                                                           # CROP based on rough heuristic
        for crop_size in range(8, 14, 2):
            cropped = img[lenX / crop_size: - lenX / crop_size, lenY / crop_size: - lenY / crop_size]
            self.images["Trans" + str(counter) + "_" + fn] = {'Image': cropped, 'Emotion': emotion}
            counter += 1

        for i in range(2):                                           # SCALE down images (random factor btw 1.1 to 1.21)
            scale_factor = math.sqrt(1.1) ** np.random.randint(2, 5)
            scaled_img = tf.warp(img, tf.AffineTransform(scale=(scale_factor, scale_factor)))
            self.images["Trans" + str(counter) + "_" + fn] = {'Image': scaled_img, 'Emotion': emotion}
            counter += 1 
Example #5
Source File: lfw.py    From autoencoding_beyond_pixels with MIT License 6 votes vote down vote up
def lfw_imgs(alignment):
    if alignment == 'landmarks':
        dataset = dp.dataset.LFW('original')
        imgs = dataset.imgs
        landmarks = dataset.landmarks('68')
        n_landmarks = 68
        landmarks_mean = np.mean(landmarks, axis=0)
        landmarks_mean = np.array([landmarks_mean[:n_landmarks],
                                   landmarks_mean[n_landmarks:]])
        aligned_imgs = []
        for img, points in zip(imgs, landmarks):
            points = np.array([points[:n_landmarks], points[n_landmarks:]])
            transf = transform.estimate_transform('similarity',
                                                  landmarks_mean.T, points.T)
            img = img / 255.
            img = transform.warp(img, transf, order=3)
            img = np.round(img*255).astype(np.uint8)
            aligned_imgs.append(img)
        imgs = np.array(aligned_imgs)
    else:
        dataset = dp.dataset.LFW(alignment)
        imgs = dataset.imgs
    return imgs 
Example #6
Source File: preprocessing.py    From face-identification-tpe with MIT License 6 votes vote down vote up
def align_face(self,
                   image,
                   face_rect, *,
                   dim=96,
                   border=0,
                   mask=FaceAlignMask.INNER_EYES_AND_BOTTOM_LIP):
        mask = np.array(mask.value)

        landmarks = self.get_landmarks(image, face_rect)
        proper_landmarks = border + dim * self.face_template[mask]
        A = np.hstack([landmarks[mask], np.ones((3, 1))]).astype(np.float64)
        B = np.hstack([proper_landmarks, np.ones((3, 1))]).astype(np.float64)
        T = np.linalg.solve(A, B).T

        wrapped = tr.warp(image,
                          tr.AffineTransform(T).inverse,
                          output_shape=(dim + 2 * border, dim + 2 * border),
                          order=3,
                          mode='constant',
                          cval=0,
                          clip=True,
                          preserve_range=True)

        return wrapped 
Example #7
Source File: transforms.py    From Face-Recognition with MIT License 6 votes vote down vote up
def __call__(self, img):
        img_data = np.array(img)
        h, w, n_chan = img_data.shape
        scale_x = np.random.uniform(*self.scale_range)
        scale_y = np.random.uniform(*self.scale_range)
        scale = (scale_x, scale_y)
        rotation = np.random.uniform(*self.rotation_range)
        shear = np.random.uniform(*self.shear_range)
        translation = (
            np.random.uniform(*self.translation_range) * w,
            np.random.uniform(*self.translation_range) * h
        )
        af = AffineTransform(scale=scale, shear=shear, rotation=rotation,
                             translation=translation)
        img_data1 = warp(img_data, af.inverse)
        img1 = Image.fromarray(np.uint8(img_data1 * 255))
        return img1 
Example #8
Source File: warp.py    From starfish with MIT License 6 votes vote down vote up
def run(self, stack: ImageStack, transforms_list: TransformsList,
            in_place: bool=False, verbose: bool=False, *args, **kwargs) -> Optional[ImageStack]:
        if not in_place:
            # create a copy of the ImageStack, call apply on that stack with in_place=True
            image_stack = deepcopy(stack)
            self.run(image_stack, transforms_list, in_place=True, **kwargs)
            return image_stack
        if verbose and StarfishConfig().verbose:
            transforms_list.transforms = tqdm(transforms_list.transforms)
        all_axes = {Axes.ROUND, Axes.CH, Axes.ZPLANE}
        for selector, _, transformation_object in transforms_list.transforms:
            other_axes = all_axes - set(selector.keys())
            # iterate through remaining axes
            for axes in stack._iter_axes(other_axes):
                # combine all axes data to select one tile
                selector.update(axes)  # type: ignore
                selected_image, _ = stack.get_slice(selector)
                warped_image = warp(selected_image, transformation_object, **kwargs
                                    ).astype(np.float32)
                stack.set_slice(selector, warped_image)
        return None 
Example #9
Source File: warp.py    From starfish with MIT License 6 votes vote down vote up
def warp(
        image: xr.DataArray,
        transformation_object: GeometricTransform,
        **kwargs
) -> xr.DataArray:
    """
    Wrapper around :py:func:`skimage.transform.warp`. Warps an image according to a
    given coordinate transformation.

    Parameters
    ----------
    image : xr.DataArray
        The image to be transformed
    transformation_object : :py:class:`~skimage.transform._geometric.GeometricTransform`
        The transformation object to apply.

    Returns
    -------
    np.ndarray :
        the warped image.
    """
    return transform.warp(image, transformation_object, **kwargs) 
Example #10
Source File: MaskDamager.py    From PReMVOS with MIT License 6 votes vote down vote up
def scale_mask(mask, factor=1.05):
  nzy, nzx, _ = mask.nonzero()
  if nzy.size == 0:
    return mask
  #center_y, center_x = nzy.mean(), nzx.mean()
  #print center_y, center_x
  center_y, center_x = (nzy.max() + nzy.min()) / 2, (nzx.max() + nzx.min()) / 2
  #print center_y, center_x

  shift_ = SimilarityTransform(translation=[-center_x, -center_y])
  shift_inv = SimilarityTransform(translation=[center_x, center_y])

  A = SimilarityTransform(scale=(factor, factor))
  mask_out = warp(mask, (shift_ + (A + shift_inv)).inverse)
  mask_out = (mask_out > 0.5).astype("float32")
  #import matplotlib.pyplot as plt
  #im = numpy.concatenate([mask, mask, mask_out],axis=2)
  #plt.imshow(im)
  #plt.show()
  return mask_out 
Example #11
Source File: transform_ops_test.py    From addons with Apache License 2.0 6 votes vote down vote up
def test_shear_y():
    image = np.random.randint(low=0, high=255, size=(4, 4, 3), dtype=np.uint8)
    color = tf.constant([255, 0, 255], tf.dtypes.uint8)
    level = tf.random.uniform(shape=(), minval=0, maxval=1)

    tf_image = tf.constant(image)
    sheared_img = transform_ops.shear_y(image=tf_image, level=level, replace=color)
    transform_matrix = transform.AffineTransform(
        np.array([[1, 0, 0], [level.numpy(), 1, 0], [0, 0, 1]])
    )
    expected_img = transform.warp(
        image, transform_matrix, order=0, cval=-1, preserve_range=True
    )

    mask = np.where(expected_img == -1)
    expected_img[mask[0], mask[1], :] = color

    np.testing.assert_equal(sheared_img.numpy(), expected_img) 
Example #12
Source File: transform_ops_test.py    From addons with Apache License 2.0 6 votes vote down vote up
def test_shear_x():
    image = np.random.randint(low=0, high=255, size=(4, 4, 3), dtype=np.uint8)
    color = tf.constant([255, 0, 255], tf.uint8)
    level = tf.random.uniform(shape=(), minval=0, maxval=1)

    tf_image = tf.constant(image)
    sheared_img = transform_ops.shear_x(tf_image, level, replace=color)
    transform_matrix = transform.AffineTransform(
        np.array([[1, level.numpy(), 0], [0, 1, 0], [0, 0, 1]])
    )
    expected_img = transform.warp(
        image, transform_matrix, order=0, cval=-1, preserve_range=True
    )

    mask = np.where(expected_img == -1)
    expected_img[mask[0], mask[1], :] = color

    np.testing.assert_equal(sheared_img.numpy(), expected_img)


# TODO: Parameterize on dtypes 
Example #13
Source File: bm_comp_perform.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _prepare_images(path_out, im_size=IMAGE_SIZE):
    """ generate and prepare synth. images for registration

    :param str path_out: path to the folder
    :param tuple(int,int) im_size: desired image size
    :return tuple(str,str): paths to target and source image
    """
    image = resize(data.astronaut(), output_shape=im_size, mode='constant')
    img_target = random_noise(image, var=IMAGE_NOISE)
    path_img_target = os.path.join(path_out, NAME_IMAGE_TARGET)
    io.imsave(path_img_target, img_target)

    # warp synthetic image
    tform = AffineTransform(scale=(0.9, 0.9),
                            rotation=0.2,
                            translation=(200, -50))
    img_source = warp(image, tform.inverse, output_shape=im_size)
    img_source = random_noise(img_source, var=IMAGE_NOISE)
    path_img_source = os.path.join(path_out, NAME_IMAGE_SOURCE)
    io.imsave(path_img_source, img_source)
    return path_img_target, path_img_source 
Example #14
Source File: transforms.py    From KagglePlanetPytorch with MIT License 6 votes vote down vote up
def augment(
        rotation_fn=lambda: np.random.random_integers(0, 360),
        translation_fn=lambda: (np.random.random_integers(-20, 20), np.random.random_integers(-20, 20)),
        scale_factor_fn=random_zoom_range(),
        shear_fn=lambda: np.random.random_integers(-10, 10)
):
    def call(x):
        rotation = rotation_fn()
        translation = translation_fn()
        scale = scale_factor_fn()
        shear = shear_fn()

        tf_augment = AffineTransform(scale=scale, rotation=np.deg2rad(rotation), translation=translation, shear=np.deg2rad(shear))
        tf = tf_center + tf_augment + tf_uncenter

        x = warp(x, tf, order=1, preserve_range=True, mode='symmetric')

        return x

    return call 
Example #15
Source File: transforms.py    From KagglePlanetPytorch with MIT License 6 votes vote down vote up
def augment_deterministic(
        rotation=0,
        translation=0,
        scale_factor=1,
        shear=0
):
    def call(x):
        scale = scale_factor, scale_factor
        rotation_tmp = rotation

        tf_augment = AffineTransform(
            scale=scale,
            rotation=np.deg2rad(rotation_tmp),
            translation=translation,
            shear=np.deg2rad(shear)
        )
        tf = tf_center + tf_augment + tf_uncenter

        x = warp(x, tf, order=1, preserve_range=True, mode='symmetric')

        return x

    return call 
Example #16
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def _scale_mask(mask, scale_amount=0.025):
  """Damages a mask for a single object by randomly scaling it in numpy.

  Args:
    mask: Boolean numpy array of shape(height, width, 1).
    scale_amount: Float scalar, the maximum factor for random scaling.

  Returns:
    The scaled version of mask.
  """
  nzy, nzx, _ = mask.nonzero()
  cy = 0.5 * (nzy.max() - nzy.min())
  cx = 0.5 * (nzx.max() - nzx.min())
  scale_factor = np.random.uniform(1.0 - scale_amount, 1.0 + scale_amount)
  shift = transform.SimilarityTransform(translation=[-cx, -cy])
  inv_shift = transform.SimilarityTransform(translation=[cx, cy])
  s = transform.SimilarityTransform(scale=[scale_factor, scale_factor])
  m = (shift + (s + inv_shift)).inverse
  scaled_mask = transform.warp(mask, m) > 0.5
  return scaled_mask 
Example #17
Source File: mask_damaging.py    From models with Apache License 2.0 6 votes vote down vote up
def _rotate_mask(mask, max_rot_degrees=3.0):
  """Damages a mask for a single object by randomly rotating it in numpy.

  Args:
    mask: Boolean numpy array of shape(height, width, 1).
    max_rot_degrees: Float scalar, the maximum number of degrees to rotate.

  Returns:
    The scaled version of mask.
  """
  cy = 0.5 * mask.shape[0]
  cx = 0.5 * mask.shape[1]
  rot_degrees = np.random.uniform(-max_rot_degrees, max_rot_degrees)
  shift = transform.SimilarityTransform(translation=[-cx, -cy])
  inv_shift = transform.SimilarityTransform(translation=[cx, cy])
  r = transform.SimilarityTransform(rotation=np.deg2rad(rot_degrees))
  m = (shift + (r + inv_shift)).inverse
  scaled_mask = transform.warp(mask, m) > 0.5
  return scaled_mask 
Example #18
Source File: utils.py    From brats17 with MIT License 5 votes vote down vote up
def read_label(path, is_training=True):
    seg = nib.load(glob.glob(os.path.join(path, '*_seg.nii.gz'))[0]).get_data().astype(np.float32)
    # Crop to 128*128*64
    crop_size = (128, 128, 64)
    crop = [int((seg.shape[0] - crop_size[0]) / 2), int((seg.shape[1] - crop_size[1]) / 2),
            int((seg.shape[2] - crop_size[2]) / 2)]
    seg = seg[crop[0] : crop[0] + crop_size[0], crop[1] : crop[1] + crop_size[1], crop[2] : crop[2] + crop_size[2]]
    label = np.zeros((seg.shape[0], seg.shape[1], seg.shape[2], 3), dtype=np.float32)
    label[seg == 1, 0] = 1
    label[seg == 2, 1] = 1
    label[seg == 4, 2] = 1
    
    final_label = np.empty((16, 16, 16, 3), dtype=np.float32)
    for z in range(label.shape[3]):
        final_label[..., z] = resize(label[..., z], (16, 16, 16), mode='constant')
        
    # Augmentation
    if is_training:
        im_size = final_label.shape[:-1]
        translation = [np.random.uniform(-2, 2), np.random.uniform(-2, 2), np.random.uniform(-2, 2)]
        rotation = euler2mat(0, 0, np.random.uniform(-5, 5) / 180.0 * np.pi, 'sxyz')
        scale = [1, 1, 1]
        warp_mat = compose(translation, rotation, scale)
        tform_coords = get_tform_coords(im_size)
        w = np.dot(warp_mat, tform_coords)
        w[0] = w[0] + im_size[0] / 2
        w[1] = w[1] + im_size[1] / 2
        w[2] = w[2] + im_size[2] / 2
        warp_coords = w[0:3].reshape(3, im_size[0], im_size[1], im_size[2])
        for z in range(label.shape[3]):
            final_label[..., z] = warp(final_label[..., z], warp_coords)

    return final_label 
Example #19
Source File: nyu_depth_v2.py    From pytorch-mono-depth with MIT License 5 votes vote down vote up
def __call__(self, image):
        scale = self.random_state.uniform(self.scale_range[0],
                                          self.scale_range[1])
        if isinstance(image, np.ndarray):
            af = AffineTransform(scale=(scale, scale))
            image = warp(image, af.inverse)
            rgb = image[:, :, 0:3]
            depth = image[:, :, 3:4] / scale
            mask = image[:, :, 4:5]
            return np.concatenate([rgb, depth, mask], axis=2)
        else:
            raise Exception('unsupported type') 
Example #20
Source File: image_tfs.py    From tanda with MIT License 5 votes vote down vote up
def TF_shear(x, shear=0.0):
    assert len(x.shape) == 3
    h, w, nc = x.shape

    # Perform shear
    xc = warp(x, AffineTransform(shear=shear), mode='edge')
    return xc 
Example #21
Source File: q3_removing_affine_distortion.py    From PythonMachineLearningExamples with MIT License 5 votes vote down vote up
def shear(X, skew):
    rows = X.shape[0]
    cols = X.shape[1]    
    ratioY = skew*cols/rows
    matrix =  np.array( [[1, ratioY, 0] ,[0, 1, 0] ,[0, 0, 1 ]])                                         
    tp=tf.ProjectiveTransform(matrix=matrix) 
    f = tf.warp(X, tp)      
    return f

# make some skewed versions of the shapes 
Example #22
Source File: crop.py    From whale-2015 with Apache License 2.0 5 votes vote down vote up
def crop(path, bonnet, blowhole):
    im = io.imread(path).astype(np.uint8)
    if doscale == 1:
        bonnet['y'] *= float(im.shape[0]) / imwidth
        bonnet['x'] *= float(im.shape[1]) / imwidth
        blowhole['y'] *= float(im.shape[0]) / imwidth
        blowhole['x'] *= float(im.shape[1]) / imwidth
    y = bonnet['y'] - blowhole['y']
    x = bonnet['x'] - blowhole['x']
    dist = math.hypot(x, y)
    minh = 10
    minw = 20
    croph = int((im.shape[0] - 1.0 * dist) // 2)
    cropw = int((im.shape[1] - 2.0 * dist) // 2)
    newh = im.shape[0] - 2 * croph
    neww = im.shape[1] - 2 * cropw
    if croph <= 0 or cropw <= 0 or newh < minh or neww < minw:
        print(' %s unchanged' % os.path.basename(path))
    else:
        angle = math.atan2(y, x) * 180 / math.pi
        centery = 0.4 * bonnet['y'] + 0.6 * blowhole['y']
        centerx = 0.4 * bonnet['x'] + 0.6 * blowhole['x']
        center = (centerx, centery)
        im = tf.rotate(im, angle, resize=False, center=center,
                       preserve_range=True)
        imcenter = (im.shape[1] / 2, im.shape[0] / 2)
        trans = (center[0] - imcenter[0], center[1] - imcenter[1])
        tform = tf.SimilarityTransform(translation=trans)
        im = tf.warp(im, tform)
        im = im[croph:-croph, cropw:-cropw]
    path = os.path.join(dstdir, os.path.basename(path))
    io.imsave(path, im.astype(np.uint8))
    return im.shape[0], im.shape[1] 
Example #23
Source File: image_tfs.py    From tanda with MIT License 5 votes vote down vote up
def TF_translate(img, x, y):
    return warp(img, AffineTransform(translation=(x, y)), mode='edge') 
Example #24
Source File: image.py    From OverwatchDataAnalysis with GNU General Public License v3.0 5 votes vote down vote up
def shear(img, shear_rad):
    """
    Shear a image to a given radian.
    @Author: Rigel
    @param img: image to be sheared
    @param shear_rad: radian to which the image will be sheared
    @return: a numpy.ndarray object of this image
    """
    affine_tf = tf.AffineTransform(shear=shear_rad)
    return tf.warp(img, inverse_map=affine_tf) 
Example #25
Source File: geometric.py    From ViolenceDetection with Apache License 2.0 5 votes vote down vote up
def _warp_skimage(self, image, scale_x, scale_y, translate_x_px, translate_y_px, rotate, shear, cval, mode, order):
        height, width = image.shape[0], image.shape[1]
        shift_x = width / 2.0 - 0.5
        shift_y = height / 2.0 - 0.5

        matrix_to_topleft = tf.SimilarityTransform(translation=[-shift_x, -shift_y])
        matrix_transforms = tf.AffineTransform(
            scale=(scale_x, scale_y),
            translation=(translate_x_px, translate_y_px),
            rotation=math.radians(rotate),
            shear=math.radians(shear)
        )
        matrix_to_center = tf.SimilarityTransform(translation=[shift_x, shift_y])
        matrix = (matrix_to_topleft + matrix_transforms + matrix_to_center)
        image_warped = tf.warp(
            image,
            matrix.inverse,
            order=order,
            mode=mode,
            cval=cval,
            preserve_range=True
        )
        # warp changes uint8 to float64, making this necessary
        if image_warped.dtype != image.dtype:
            image_warped = image_warped.astype(image.dtype, copy=False)
        return image_warped 
Example #26
Source File: geometric.py    From ViolenceDetection with Apache License 2.0 5 votes vote down vote up
def _warp_cv2(self, image, scale_x, scale_y, translate_x_px, translate_y_px, rotate, shear, cval, mode, order):
        height, width = image.shape[0], image.shape[1]
        shift_x = width / 2.0 - 0.5
        shift_y = height / 2.0 - 0.5

        matrix_to_topleft = tf.SimilarityTransform(translation=[-shift_x, -shift_y])
        matrix_transforms = tf.AffineTransform(
            scale=(scale_x, scale_y),
            translation=(translate_x_px, translate_y_px),
            rotation=math.radians(rotate),
            shear=math.radians(shear)
        )
        matrix_to_center = tf.SimilarityTransform(translation=[shift_x, shift_y])
        matrix = (matrix_to_topleft + matrix_transforms + matrix_to_center)

        image_warped = cv2.warpAffine(
            image,
            matrix.params[:2],
            #np.zeros((2, 3)),
            dsize=(width, height),
            flags=order,
            borderMode=mode,
            borderValue=cval
        )

        # cv2 warp drops last axis if shape is (H, W, 1)
        if image_warped.ndim == 2:
            image_warped = image_warped[..., np.newaxis]

        return image_warped 
Example #27
Source File: geometric.py    From ViolenceDetection with Apache License 2.0 5 votes vote down vote up
def _augment_images(self, images, random_state, parents, hooks):
        result = images
        nb_images = len(images)

        seeds = ia.copy_random_state(random_state).randint(0, 10**6, (nb_images+1,))

        seed = seeds[-1]
        nb_rows_samples = self.nb_rows.draw_samples((nb_images,), random_state=ia.new_random_state(seed + 1))
        nb_cols_samples = self.nb_cols.draw_samples((nb_images,), random_state=ia.new_random_state(seed + 2))
        cval_samples = self.cval.draw_samples((nb_images,), random_state=ia.new_random_state(seed + 3))
        mode_samples = self.mode.draw_samples((nb_images,), random_state=ia.new_random_state(seed + 4))
        order_samples = self.order.draw_samples((nb_images,), random_state=ia.new_random_state(seed + 5))

        for i in sm.xrange(nb_images):
            rs_image = ia.new_random_state(seeds[i])
            h, w = images[i].shape[0:2]
            transformer = self._get_transformer(h, w, nb_rows_samples[i], nb_cols_samples[i], rs_image)

            if transformer is not None:
                #print("transformer vertices img", transformer._tesselation.vertices)
                image_warped = tf.warp(
                    images[i],
                    transformer,
                    order=order_samples[i],
                    mode=mode_samples[i],
                    cval=cval_samples[i],
                    preserve_range=True,
                    output_shape=images[i].shape
                )

                # warp changes uint8 to float64, making this necessary
                if image_warped.dtype != images[i].dtype:
                    image_warped = image_warped.astype(images[i].dtype, copy=False)

                result[i] = image_warped

        return result 
Example #28
Source File: geometric.py    From ViolenceDetection with Apache License 2.0 5 votes vote down vote up
def _augment_images(self, images, random_state, parents, hooks):
        result = images
        if not self.keep_size:
            result = list(result)

        matrices, max_heights, max_widths = self._create_matrices(
            [image.shape for image in images],
            random_state
        )

        for i, (M, max_height, max_width) in enumerate(zip(matrices, max_heights, max_widths)):
            # cv2.warpPerspective only supports <=4 channels
            #ia.do_assert(images[i].shape[2] <= 4, "PerspectiveTransform is currently limited to images with 4 or less channels.")
            nb_channels = images[i].shape[2]
            if nb_channels <= 4:
                warped = cv2.warpPerspective(images[i], M, (max_width, max_height))
                if warped.ndim == 2 and images[i].ndim == 3:
                    warped = np.expand_dims(warped, 2)
            else:
                # warp each channel on its own, re-add channel axis, then stack
                # the result from a list of [H, W, 1] to (H, W, C).
                warped = [cv2.warpPerspective(images[i][..., c], M, (max_width, max_height)) for c in sm.xrange(nb_channels)]
                warped = [warped_i[..., np.newaxis] for warped_i in warped]
                warped = np.dstack(warped)
            #print(np.min(warped), np.max(warped), warped.dtype)
            if self.keep_size:
                h, w = images[i].shape[0:2]
                warped = ia.imresize_single_image(warped, (h, w), interpolation="cubic")
            result[i] = warped

        return result 
Example #29
Source File: SPM.py    From pySPM with Apache License 2.0 5 votes vote down vote up
def align(self, tform, cut=True):
        """
        Apply an Affine transform on the data

        Parameters
        ----------
        tform : skimage.transform
            the affine transform to perform
        cut : bool
            If True cut the data
        """
        New = copy.deepcopy(self)
        New.pixels = tf.warp(self.pixels, tform, preserve_range=True)
        if not cut:
            return New
        cut = [0, 0] + list(self.pixels.shape)
        if tform.translation[0] >= 0:
            cut[2] -= tform.translation[0]
        elif tform.translation[0] < 0:
            cut[0] -= tform.translation[0]
        if tform.translation[1] >= 0:
            cut[1] += tform.translation[1]
        elif tform.translation[1] < 0:
            cut[3] += tform.translation[1]
        cut = [int(x) for x in cut]
        New.cut(cut, inplace=True)
        return New, cut 
Example #30
Source File: SPM.py    From pySPM with Apache License 2.0 5 votes vote down vote up
def warp_and_cut(img, tform, cut=True):
    """
    Perform an Affine transform on the input data and cut them if cut=True

    Parameters
    ----------
    img : 2D numpy array
        input data
    tform : skimage.transform
        An Affine fransform to perform on the data
    cut : bool
        Should the data be cutted?
    """
    New = tf.warp(img, tform, preserve_range=True)
    Cut = [0, 0] + list(img.shape)
    if tform.translation[0] >= 0:
        Cut[2] -= tform.translation[0]
    elif tform.translation[0] < 0:
        Cut[0] -= tform.translation[0]
    if tform.translation[1] >= 0:
        Cut[1] += tform.translation[1]
    elif tform.translation[1] < 0:
        Cut[3] += tform.translation[1]
    Cut = [int(x) for x in Cut]
    if cut:
        New = cut(New, Cut)
    return New, Cut