Python skimage.transform 模块,AffineTransform() 实例源码

我们从Python开源项目中,提取了以下19个代码示例,用于说明如何使用skimage.transform.AffineTransform()

项目:KagglePlanetPytorch    作者:Mctigger    | 项目源码 | 文件源码
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
项目:tabea_video_project    作者:neilslater    | 项目源码 | 文件源码
def affine_zoom( img, zoom, spin = 0 ):
    '''Returns new image derived from img, after a central-origin affine transform has been applied'''
    img_copy = img.copy()

    # Shift transforms allow Affine to be applied with centre of image as 0,0
    shift_y, shift_x, _ = (np.array(img_copy.shape)-1) / 2.
    shift_fwd = transform.SimilarityTransform(translation=[-shift_x, -shift_y])
    shift_back = transform.SimilarityTransform(translation=[shift_x, shift_y])
    affine = transform.AffineTransform( scale=(zoom, zoom), rotation=(spin * math.pi/180) )

    img_copy = transform.warp( img_copy,
                     ( shift_fwd + ( affine + shift_back )).inverse,
                     order=3,
                     clip=False, preserve_range=True,
                     mode='reflect').astype(np.float32)
    return img_copy
项目:KagglePlanetPytorch    作者:Mctigger    | 项目源码 | 文件源码
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
项目:pyxem    作者:pyxem    | 项目源码 | 文件源码
def affine_transformation(z, order, **kwargs):
    """Apply an affine transformation to a 2-dimensional array.

    Parameters
    ----------
    matrix : np.array
        3x3 numpy array specifying the affine transformation to be applied.
    order : int
        Interpolation order.

    Returns
    -------
    trans : array
        Affine transformed diffraction pattern.
    """
    shift_y, shift_x = np.array(z.shape[:2]) / 2.
    tf_shift = tf.SimilarityTransform(translation=[-shift_x, -shift_y])
    tf_shift_inv = tf.SimilarityTransform(translation=[shift_x, shift_y])

    transformation = tf.AffineTransform(**kwargs)
    trans = tf.warp(z, (tf_shift + (transformation + tf_shift_inv)).inverse,
                    order=order)

    return trans
项目:pyxem    作者:pyxem    | 项目源码 | 文件源码
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., 1.]])

        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
项目:nuts-ml    作者:maet3608    | 项目源码 | 文件源码
def translate(image, dx, dy, **kwargs):
    """
    Shift image horizontally and vertically

    >>> image = np.eye(3, dtype='uint8') * 255
    >>> translate(image, 2, 1)
    array([[  0,   0,   0],
           [  0,   0, 255],
           [  0,   0,   0]], dtype=uint8)

    :param numpy array image: Numpy array with range [0,255] and dtype 'uint8'.
    :param dx: horizontal translation in pixels
    :param dy: vertical translation in pixels
    :param kwargs kwargs: Keyword arguments for the underlying scikit-image
       rotate function, e.g. order=1 for linear interpolation.
    :return: translated image
    :rtype:  numpy array with range [0,255] and dtype 'uint8'
    """
    set_default_order(kwargs)
    transmat = skt.AffineTransform(translation=(-dx, -dy))
    return skt.warp(image, transmat, preserve_range=True,
                    **kwargs).astype('uint8')
项目:nuts-ml    作者:maet3608    | 项目源码 | 文件源码
def shear(image, shear_factor, **kwargs):
    """
    Shear image.

    For details see:
    http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.AffineTransform

    >>> image = np.eye(3, dtype='uint8')
    >>> rotated = rotate(image, 45)

    :param numpy array image: Numpy array with range [0,255] and dtype 'uint8'.
    :param float shear_factor: Shear factor [0, 1]
    :param kwargs kwargs: Keyword arguments for the underlying scikit-image
       warp function, e.g. order=1 for linear interpolation.
    :return: Sheared image
    :rtype: numpy array with range [0,255] and dtype 'uint8'
    """
    set_default_order(kwargs)
    transform = skt.AffineTransform(shear=shear_factor)
    return skt.warp(image, transform, preserve_range=True,
                    **kwargs).astype('uint8')
项目:HandwritingRecognition    作者:eng-tsmith    | 项目源码 | 文件源码
def slant(img):
    # Load the image as a matrix
    """

    :param img:
    :return:
    """
    # Create random slant for data augmentation
    slant_factor = 0 #random.uniform(-0.2, 0.2) #TODO dataug

    # Create Afine transform
    afine_tf = tf.AffineTransform(shear=slant_factor)

    # Apply transform to image data
    img_slanted = tf.warp(img, afine_tf, order=0)
    return img_slanted
项目:EquationRecognition    作者:xyjiang94    | 项目源码 | 文件源码
def image_deformation(self,image):
        random_shear_angl = np.random.random() * np.pi/6 - np.pi/12
        random_rot_angl = np.random.random() * np.pi/6 - np.pi/12 - random_shear_angl
        random_x_scale = np.random.random() * .4 + .8
        random_y_scale = np.random.random() * .4 + .8
        random_x_trans = np.random.random() * image.shape[0] / 4 - image.shape[0] / 8
        random_y_trans = np.random.random() * image.shape[1] / 4 - image.shape[1] / 8
        dx = image.shape[0]/2. \
                - random_x_scale * image.shape[0]/2 * np.cos(random_rot_angl)\
                + random_y_scale * image.shape[1]/2 * np.sin(random_rot_angl + random_shear_angl)
        dy = image.shape[1]/2. \
                - random_x_scale * image.shape[0]/2 * np.sin(random_rot_angl)\
                - random_y_scale * image.shape[1]/2 * np.cos(random_rot_angl + random_shear_angl)
        trans_mat = AffineTransform(rotation=random_rot_angl,
                                    translation=(dx + random_x_trans,
                                                 dy + random_y_trans),
                                    shear = random_shear_angl,
                                    scale = (random_x_scale,random_y_scale))
        return warp(image,trans_mat.inverse,output_shape=image.shape)
项目:tensorflow-litterbox    作者:rwightman    | 项目源码 | 文件源码
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)
项目:face-identification-tpe    作者:meownoid    | 项目源码 | 文件源码
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
项目:UVA    作者:chiachun    | 项目源码 | 文件源码
def augmentation(photoname,label):
    img = cv2.imread(photoname)
    labels = []
    images = []
    zoom1s = [0.8,1.0,1.2]
    zoom2s = [0.8,1.0,1.2]
    rotations = [0,4,8,12]
    shears = [3,6,9,12]
    flips = [False, True]
    for zoom1 in zoom1s:
        for zoom2 in zoom2s:
            for rotation in rotations:
                for shear in shears:
                    for flip in flips:
                        tform_augment = AffineTransform(scale=(1/zoom1, 1/zoom2), 
                                                        rotation=np.deg2rad(rotation), 
                                                        shear=np.deg2rad(shear))

                        img2 = warp(img, tform_augment)
                        if flip == True:
                            images.append(cv2.flip(img2,1))
                            labels.append(label)
                        else:
                            images.append(img2)
                            labels.append(label)
    return images,labels
项目:py-data-augmentation    作者:taoyizhi68    | 项目源码 | 文件源码
def rotate(images, x_max_rotation, y_max_rotation, z_max_rotation, img_rows, img_cols):
    assert(x_max_rotation >= 0)
    assert(y_max_rotation >= 0)
    assert(z_max_rotation >= 0)
    for i in xrange(images.shape[0]):
        x_rotation = np.random.uniform(-x_max_rotation, x_max_rotation) * np.pi / 180
        y_rotation = np.random.uniform(-y_max_rotation, y_max_rotation) * np.pi / 180
        z_rotation = np.random.uniform(-z_max_rotation, z_max_rotation) * np.pi / 180

        center_matrix1 = np.array([[1, 0, -img_cols/2.], 
                                  [0, 1, -img_rows/2.],
                                  [0, 0, 1]])

        R = np.dot(np.dot(z_matirx(z_rotation), y_matrix(y_rotation)), x_matrix(x_rotation))
        rotate_matrix = np.array([[R[0][0], R[0][1], 0], 
                                  [R[1][0], R[1][1], 0],
                                  [0,       0,       1]])
        #print rotate_matrix
        center_matrix2 = np.array([[1, 0, img_cols/2.], 
                                  [0, 1, img_rows/2.],
                                  [0, 0, 1]]) 

        center_trans1 = transform.AffineTransform(center_matrix1)
        rotate_trans = transform.AffineTransform(rotate_matrix)
        center_trans2 = transform.AffineTransform(center_matrix2)

        affine_trans = center_trans1 + rotate_trans + center_trans2
        images[i] = transform.warp(images[i], affine_trans, mode='edge')
项目:HandwritingRecognition    作者:eng-tsmith    | 项目源码 | 文件源码
def slant(img):
    """
    Creates random slant on images for data augmentation
    :param img: image
    :return: slanted image
    """
    # Create random slant for data augmentation
    slant_factor = random.uniform(-0.1, 0.1)

    # Create Afine transform
    afine_tf = tf.AffineTransform(shear=slant_factor)

    # Apply transform to image data
    img_slanted = tf.warp(img, afine_tf, order=0)
    return img_slanted
项目:tanda    作者:HazyResearch    | 项目源码 | 文件源码
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
项目:tanda    作者:HazyResearch    | 项目源码 | 文件源码
def TF_translate(img, x, y):
    return warp(img, AffineTransform(translation=(x, y)), mode='edge')
项目:luna16    作者:gzuidhof    | 项目源码 | 文件源码
def augment(images):
    pixels = images[0].shape[1]
    center = pixels/2.-0.5

    random_flip_x = P.AUGMENTATION_PARAMS['flip'] and np.random.randint(2) == 1
    random_flip_y = P.AUGMENTATION_PARAMS['flip'] and np.random.randint(2) == 1

    # Translation shift
    shift_x = np.random.uniform(*P.AUGMENTATION_PARAMS['translation_range'])
    shift_y = np.random.uniform(*P.AUGMENTATION_PARAMS['translation_range'])
    rotation_degrees = np.random.uniform(*P.AUGMENTATION_PARAMS['rotation_range'])
    zoom_factor = np.random.uniform(*P.AUGMENTATION_PARAMS['zoom_range'])
    #zoom_factor = 1 + (zoom_f/2-zoom_f*np.random.random())
    if CV2_AVAILABLE:
        M = cv2.getRotationMatrix2D((center, center), rotation_degrees, zoom_factor)
        M[0, 2] += shift_x
        M[1, 2] += shift_y

    for i in range(len(images)):
        image = images[i]

        if CV2_AVAILABLE:
            #image = image.transpose(1,2,0)
            image = cv2.warpAffine(image, M, (pixels, pixels))
            if random_flip_x:
                image = cv2.flip(image, 0)
            if random_flip_y:
                image = cv2.flip(image, 1)
            #image = image.transpose(2,0,1)
            images[i] = image
        else:
            if random_flip_x:
                #image = image.transpose(1,0)
                image[:,:] = image[::-1,:]
                #image = image.transpose(1,0)
            if random_flip_y:
                image = image.transpose(1,0)
                image[:,:] = image[::-1,:]
                image = image.transpose(1,0)

            rotate(image, rotation_degrees, reshape=False, output=image)
            #image2 = zoom(image, [zoom_factor,zoom_factor])
            image2 = crop_or_pad(image, pixels, -3000)
            shift(image2, [shift_x,shift_y], output=image)
            #affine_transform(image, np.array([[zoom_x,0], [0,zoom_x]]), output=image)
            #z = AffineTransform(scale=(2,2))
            #image = warp(image, z.params)
            images[i] = image



    return images
项目:kaggle_dsb    作者:syagev    | 项目源码 | 文件源码
def augment(images):
    pixels = images[0].shape[1]
    center = pixels/2.-0.5

    random_flip_x = P.AUGMENTATION_PARAMS['flip'] and np.random.randint(2) == 1
    random_flip_y = P.AUGMENTATION_PARAMS['flip'] and np.random.randint(2) == 1

    # Translation shift
    shift_x = np.random.uniform(*P.AUGMENTATION_PARAMS['translation_range'])
    shift_y = np.random.uniform(*P.AUGMENTATION_PARAMS['translation_range'])
    rotation_degrees = np.random.uniform(*P.AUGMENTATION_PARAMS['rotation_range'])
    zoom_factor = np.random.uniform(*P.AUGMENTATION_PARAMS['zoom_range'])
    #zoom_factor = 1 + (zoom_f/2-zoom_f*np.random.random())
    if CV2_AVAILABLE:
        M = cv2.getRotationMatrix2D((center, center), rotation_degrees, zoom_factor)
        M[0, 2] += shift_x
        M[1, 2] += shift_y

    for i in range(len(images)):
        image = images[i]

        if CV2_AVAILABLE:
            #image = image.transpose(1,2,0)
            image = cv2.warpAffine(image, M, (pixels, pixels))
            if random_flip_x:
                image = cv2.flip(image, 0)
            if random_flip_y:
                image = cv2.flip(image, 1)
            #image = image.transpose(2,0,1)
            images[i] = image
        else:
            if random_flip_x:
                #image = image.transpose(1,0)
                image[:,:] = image[::-1,:]
                #image = image.transpose(1,0)
            if random_flip_y:
                image = image.transpose(1,0)
                image[:,:] = image[::-1,:]
                image = image.transpose(1,0)

            rotate(image, rotation_degrees, reshape=False, output=image)
            #image2 = zoom(image, [zoom_factor,zoom_factor])
            image2 = crop_or_pad(image, pixels, -3000)
            shift(image2, [shift_x,shift_y], output=image)
            #affine_transform(image, np.array([[zoom_x,0], [0,zoom_x]]), output=image)
            #z = AffineTransform(scale=(2,2))
            #image = warp(image, z.params)
            images[i] = image



    return images
项目:EquationRecognition    作者:xyjiang94    | 项目源码 | 文件源码
def image_deformation(self,image):
        random_shear_angl = np.random.random() * np.pi/6 - np.pi/12
        random_rot_angl = np.random.random() * np.pi/6 - np.pi/12 - random_shear_angl
        random_x_scale = np.random.random() * .4 + .8
        random_y_scale = np.random.random() * .4 + .8
        random_x_trans = np.random.random() * image.shape[0] / 4 - image.shape[0] / 8
        random_y_trans = np.random.random() * image.shape[1] / 4 - image.shape[1] / 8
        dx = image.shape[0]/2. \
                - random_x_scale * image.shape[0]/2 * np.cos(random_rot_angl)\
                + random_y_scale * image.shape[1]/2 * np.sin(random_rot_angl + random_shear_angl)
        dy = image.shape[1]/2. \
                - random_x_scale * image.shape[0]/2 * np.sin(random_rot_angl)\
                - random_y_scale * image.shape[1]/2 * np.cos(random_rot_angl + random_shear_angl)
        trans_mat = AffineTransform(rotation=random_rot_angl,
                                    translation=(dx + random_x_trans,
                                                 dy + random_y_trans),
                                    shear = random_shear_angl,
                                    scale = (random_x_scale,random_y_scale))
        return warp(image,trans_mat.inverse,output_shape=image.shape)


    # def get_valid(self,size = 1000):
    #   data = self.mnist.train.next_batch(size)
    #   images = np.zeros((size,32,32))
    #   labels = data[1]
    #   for i in range(1000):
    #       images[i,:,:] = misc.imresize(np.reshape(data[0][i],(28,28)),(32,32))
    #   return images,labels
    # def shuffle(self):
    #   pass
    # def next_batch(self,batch_size):
    #   data = self.mnist.train.next_batch(batch_size)
    #   images = np.zeros((batch_size,32,32))
    #   labels = data[1]
    #   for i in range(batch_size):
    #       images[i,:,:] = misc.imresize(np.reshape(data[0][i],(28,28)),(32,32))
    #   return images,labels



    # def get_valid(self,size = 500):
    #   data = self.mnist.train.next_batch(size)
    #   images = np.zeros((size,32,32))
    #   labels = data[1]
    #   for i in range(500):
    #       images[i,:,:] = misc.imresize(np.reshape(data[0][i],(28,28)),(32,32))
    #   return images,labels
    # def shuffle(self):
    #   pass
    # def next_batch(self,batch_size):
    #   data = self.mnist.train.next_batch(batch_size)
    #   images = np.zeros((batch_size,32,32))
    #   labels = data[1]
    #   for i in range(batch_size):
    #       images[i,:,:] = misc.imresize(np.reshape(data[0][i],(28,28)),(32,32))
    #   return images,labels