Python cv2.getRotationMatrix2D() Examples

The following are 30 code examples of cv2.getRotationMatrix2D(). 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 cv2 , or try the search function .
Example #1
Source File: geometry.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def get_transform(self, img):
        center = img.shape[1::-1] * self._rand_range(
            self.center_range[0], self.center_range[1], (2,))
        deg = self._rand_range(-self.max_deg, self.max_deg)
        if self.step_deg:
            deg = deg // self.step_deg * self.step_deg
        """
        The correct center is shape*0.5-0.5. This can be verified by:

        SHAPE = 7
        arr = np.random.rand(SHAPE, SHAPE)
        orig = arr
        c = SHAPE * 0.5 - 0.5
        c = (c, c)
        for k in range(4):
            mat = cv2.getRotationMatrix2D(c, 90, 1)
            arr = cv2.warpAffine(arr, mat, arr.shape)
        assert np.all(arr == orig)
        """
        mat = cv2.getRotationMatrix2D(tuple(center - 0.5), deg, 1)
        return WarpAffineTransform(
            mat, img.shape[1::-1], interp=self.interp,
            borderMode=self.border, borderValue=self.border_value) 
Example #2
Source File: morpher.py    From yry with Apache License 2.0 6 votes vote down vote up
def merge_img(src_img, dst_img, dst_matrix, dst_points, blur_detail_x=None, blur_detail_y=None, mat_multiple=None):
    face_mask = np.zeros(src_img.shape, dtype=src_img.dtype)

    for group in core.OVERLAY_POINTS:
        cv2.fillConvexPoly(face_mask, cv2.convexHull(dst_matrix[group]), (255, 255, 255))

    r = cv2.boundingRect(np.float32([dst_points[:core.FACE_END]]))

    center = (r[0] + int(r[2] / 2), r[1] + int(r[3] / 2))

    if mat_multiple:
        mat = cv2.getRotationMatrix2D(center, 0, mat_multiple)
        face_mask = cv2.warpAffine(face_mask, mat, (face_mask.shape[1], face_mask.shape[0]))

    if blur_detail_x and blur_detail_y:
        face_mask = cv2.blur(face_mask, (blur_detail_x, blur_detail_y), center)

    return cv2.seamlessClone(np.uint8(dst_img), src_img, face_mask, center, cv2.NORMAL_CLONE) 
Example #3
Source File: train_yadav.py    From robust_physical_perturbations with MIT License 6 votes vote down vote up
def transform_image(image,ang_range,shear_range,trans_range):

    # Rotation

    ang_rot = np.random.uniform(ang_range)-ang_range/2
    rows,cols,ch = image.shape    
    Rot_M = cv2.getRotationMatrix2D((cols/2,rows/2),ang_rot,1)

    # Translation
    tr_x = trans_range*np.random.uniform()-trans_range/2
    tr_y = trans_range*np.random.uniform()-trans_range/2
    Trans_M = np.float32([[1,0,tr_x],[0,1,tr_y]])

    # Shear
    pts1 = np.float32([[5,5],[20,5],[5,20]])

    pt1 = 5+shear_range*np.random.uniform()-shear_range/2
    pt2 = 20+shear_range*np.random.uniform()-shear_range/2

    pts2 = np.float32([[pt1,5],[pt2,pt1],[5,pt2]])

    shear_M = cv2.getAffineTransform(pts1,pts2)

    image = cv2.warpAffine(image,Rot_M,(cols,rows))
    image = cv2.warpAffine(image,Trans_M,(cols,rows))
    image = cv2.warpAffine(image,shear_M,(cols,rows))

    image = pre_process_image(image.astype(np.uint8))

    #image = cv2.cvtColor(image, cv2.COLOR_BGR2YUV)
    #image = image[:,:,0]
    #image = cv2.resize(image, (img_resize,img_resize),interpolation = cv2.INTER_CUBIC)

    return image 
Example #4
Source File: dataset.py    From RESCAN with MIT License 5 votes vote down vote up
def rotate(self, O, B):
        angle = self.rand_state.randint(-30, 30)
        patch_size = self.patch_size
        center = (int(patch_size / 2), int(patch_size / 2))
        M = cv2.getRotationMatrix2D(center, angle, 1)
        O = cv2.warpAffine(O, M, (patch_size, patch_size))
        B = cv2.warpAffine(B, M, (patch_size, patch_size))
        return O, B 
Example #5
Source File: image_augmentation.py    From youtube-video-face-swap with MIT License 5 votes vote down vote up
def random_transform( image, rotation_range, zoom_range, shift_range, random_flip ):
    h,w = image.shape[0:2]
    rotation = numpy.random.uniform( -rotation_range, rotation_range )
    scale = numpy.random.uniform( 1 - zoom_range, 1 + zoom_range )
    tx = numpy.random.uniform( -shift_range, shift_range ) * w
    ty = numpy.random.uniform( -shift_range, shift_range ) * h
    mat = cv2.getRotationMatrix2D( (w//2,h//2), rotation, scale )
    mat[:,2] += (tx,ty)
    result = cv2.warpAffine( image, mat, (w,h), borderMode=cv2.BORDER_REPLICATE )
    if numpy.random.random() < random_flip:
        result = result[:,::-1]
    return result

# get pair of random warped images from aligened face image 
Example #6
Source File: transforms.py    From SCNN_Pytorch with MIT License 5 votes vote down vote up
def __call__(self, sample):
        img = sample.get('img')
        segLabel = sample.get('segLabel', None)

        u = np.random.uniform()
        degree = (u-0.5) * self.theta
        R = cv2.getRotationMatrix2D((img.shape[1]//2, img.shape[0]//2), degree, 1)
        img = cv2.warpAffine(img, R, (img.shape[1], img.shape[0]), flags=cv2.INTER_LINEAR)
        if segLabel is not None:
            segLabel = cv2.warpAffine(segLabel, R, (segLabel.shape[1], segLabel.shape[0]), flags=cv2.INTER_NEAREST)

        _sample = sample.copy()
        _sample['img'] = img
        _sample['segLabel'] = segLabel
        return _sample 
Example #7
Source File: rotateImage.py    From FaceRecognition with GNU General Public License v3.0 5 votes vote down vote up
def rotateFunction(img):

    # img = cv2.imread(imagePath)
    # get image height, width
    (h, w) = img.shape[:2
             ]
    # calculate the center of the image
    center = (w / 2, h / 2)

    angle90 = 90
    angle180 = 180

    scale = 1.0

    # Perform the counter clockwise rotation holding at the center
    # 90 degrees
    M = cv2.getRotationMatrix2D(center, angle90, scale)
    rotated90 = cv2.warpAffine(img, M, (h, w))

    # 180 degrees
    M = cv2.getRotationMatrix2D(center, angle180, scale)
    rotated180 = cv2.warpAffine(img, M, (w, h))

    cv2.imshow('Image rotated by 90 degrees', rotated90)
    cv2.waitKey(0)  # waits until a key is pressed
    cv2.destroyAllWindows()  # destroys the window showing image

    cv2.imshow('Image rotated by 180 degrees', rotated180)
    cv2.waitKey(0)  # waits until a key is pressed
    cv2.destroyAllWindows()  # destroys the window showing image

    return rotated90, rotated180 
Example #8
Source File: text_detection_app.py    From text-detection-ocr with Apache License 2.0 5 votes vote down vote up
def dumpRotateImage(img, degree, pt1, pt2, pt3, pt4):
    height, width = img.shape[:2]
    heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
    widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))
    matRotation = cv2.getRotationMatrix2D((width // 2, height // 2), degree, 1)
    matRotation[0, 2] += (widthNew - width) // 2
    matRotation[1, 2] += (heightNew - height) // 2
    imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))
    pt1 = list(pt1)
    pt3 = list(pt3)

    [[pt1[0]], [pt1[1]]] = np.dot(matRotation, np.array([[pt1[0]], [pt1[1]], [1]]))
    [[pt3[0]], [pt3[1]]] = np.dot(matRotation, np.array([[pt3[0]], [pt3[1]], [1]]))
    ydim, xdim = imgRotation.shape[:2]
    imgOut = imgRotation[max(1, int(pt1[1])): min(ydim - 1, int(pt3[1])),
             max(1, int(pt1[0])): min(xdim - 1, int(pt3[0]))]

    return imgOut 
Example #9
Source File: lpr.py    From lpr with Apache License 2.0 5 votes vote down vote up
def rotate(image, degree):
    (h, w) = image.shape[:2]
    center = (w / 2, h / 2)
    # 将图像旋转180度
    M = cv2.getRotationMatrix2D(center, degree, 1.0)
    rotated = cv2.warpAffine(image, M, (w, h))
    return rotated

# Process inputs 
Example #10
Source File: transforms.py    From remote_sensing_object_detection_2019 with MIT License 5 votes vote down vote up
def rotate_img(self, image, angle):
        # convert to cv2 image
        image = np.array(image)
        (h, w) = image.shape[:2]
        scale = 1.0
        # set the rotation center
        center = (w / 2, h / 2)
        # anti-clockwise angle in the function
        M = cv2.getRotationMatrix2D(center, angle, scale)
        image = cv2.warpAffine(image, M, (w, h))
        # back to PIL image
        image = Image.fromarray(image)
        return image 
Example #11
Source File: .demo.py    From dual-fisheye-video-stitching with MIT License 5 votes vote down vote up
def rotate(img, theta):
    M = cv2.getRotationMatrix2D((640, 640), theta, 1)
    result = cv2.warpAffine(img, M, (1280, 1280))
    return result 
Example #12
Source File: dataset.py    From AugmentedAutoencoder with MIT License 5 votes vote down vote up
def batch(self, batch_size):

        # batch_x = np.empty( (batch_size,) + self.shape, dtype=np.uint8 )
        # batch_y = np.empty( (batch_size,) + self.shape, dtype=np.uint8 )

        rand_idcs = np.random.choice(self.noof_training_imgs, batch_size, replace=False)

        assert self.noof_bg_imgs > 0

        rand_idcs_bg = np.random.choice(self.noof_bg_imgs, batch_size, replace=False)

        batch_x, masks, batch_y = self.train_x[rand_idcs], self.mask_x[rand_idcs], self.train_y[rand_idcs]
        rand_vocs = self.bg_imgs[rand_idcs_bg]

        if eval(self._kw['realistic_occlusion']):
            masks = self.augment_occlusion_mask(masks.copy(),max_occl=np.float(self._kw['realistic_occlusion']))

        if eval(self._kw['square_occlusion']):
            masks = self.augment_squares(masks.copy(),rand_idcs,max_occl=np.float(self._kw['square_occlusion']))

        batch_x[masks] = rand_vocs[masks]

        # random in-plane rotation, not necessary
        # for i in range(batch_size):
        #   rot_angle= np.random.rand()*360
        #   cent = int(self.shape[0]/2)
        #   M = cv2.getRotationMatrix2D((cent,cent),rot_angle,1)
        #   batch_x[i] = cv2.warpAffine(batch_x[i],M,self.shape[:2])[:,:,np.newaxis]
        #   batch_y[i] = cv2.warpAffine(batch_y[i],M,self.shape[:2])[:,:,np.newaxis]


        #needs uint8
        batch_x = self._aug.augment_images(batch_x)

        #slow...
        batch_x = batch_x / 255.
        batch_y = batch_y / 255.


        return (batch_x, batch_y) 
Example #13
Source File: CutImageClass.py    From water-meter-system-complete with MIT License 5 votes vote down vote up
def RotateImage(self, image):
        h, w, ch = image.shape
        center = (w / 2, h / 2)
        M = cv2.getRotationMatrix2D(center, self.rotateAngle, 1.0)
        image = cv2.warpAffine(image, M, (w, h))
        return image 
Example #14
Source File: img_utils.py    From TreeFilter-Torch with MIT License 5 votes vote down vote up
def random_rotation(img, gt):
    angle = random.random() * 20 - 10
    h, w = img.shape[:2]
    rotation_matrix = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)
    img = cv2.warpAffine(img, rotation_matrix, (w, h), flags=cv2.INTER_LINEAR)
    gt = cv2.warpAffine(gt, rotation_matrix, (w, h), flags=cv2.INTER_NEAREST)

    return img, gt 
Example #15
Source File: augment.py    From luna16 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def augment_with_params(self, Xb, shift_x, shift_y, rotation, random_flip, zoom, hue, saturation, value):


            # Define affine matrix
            # TODO: Should be able to incorporate flips directly instead of through an extra call
            M = cv2.getRotationMatrix2D((self.center_shift[0], self.center_shift[1]), rotation, zoom)
            M[0, 2] += shift_x
            M[1, 2] += shift_y

            augment_partial = partial(augment_image,
                                        M=M,
                                        random_flip=random_flip,
                                        random_hue=hue,
                                        random_saturation=saturation,
                                        random_value=value)

            if self.multiprocess:
                l = self.pool.map(augment_partial, Xb)
                Xbb = np.array(l)
            else:
                Xbb = np.zeros(Xb.shape, dtype=np.float32)
                for i in xrange(Xb.shape[0]):
                    Xbb[i] = augment_partial(Xb[i])


            return Xbb

# Augments a single image, singled out for easier profiling 
Example #16
Source File: utils.py    From mlnd_DeepTesla with GNU General Public License v3.0 5 votes vote down vote up
def rotate_image(image, angle):
    image_center = tuple(np.array(image.shape)/2)[:2]
    rot_mat = cv2.getRotationMatrix2D(image_center,angle,1.0)
    result = cv2.warpAffine(image, rot_mat, image.shape[:2], flags=cv2.INTER_LINEAR)
    return result


#########################################
#### Visualize result
######################################### 
Example #17
Source File: augmentation.py    From face_landmark with Apache License 2.0 5 votes vote down vote up
def Rotate_aug(src,angle,label=None,center=None,scale=1.0):
    '''
    :param src: src image
    :param label: label should be numpy array with [[x1,y1],
                                                    [x2,y2],
                                                    [x3,y3]...]
    :param angle:
    :param center:
    :param scale:
    :return: the rotated image and the points
    '''
    image=src
    (h, w) = image.shape[:2]
    # 若未指定旋转中心,则将图像中心设为旋转中心
    if center is None:
        center = (w / 2, h / 2)
    # 执行旋转
    M = cv2.getRotationMatrix2D(center, angle, scale)
    if label is None:
        for i in range(image.shape[2]):
            image[:,:,i] = cv2.warpAffine(image[:,:,i], M, (w, h),
                                          flags=cv2.INTER_CUBIC,
                                          borderMode=cv2.BORDER_CONSTANT,
                                          borderValue=cfg.DATA.PIXEL_MEAN)
        return image,None
    else:
        label=label.T
        ####make it as a 3x3 RT matrix
        full_M=np.row_stack((M,np.asarray([0,0,1])))
        img_rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC,
                                     borderMode=cv2.BORDER_CONSTANT, borderValue=cfg.DATA.PIXEL_MEAN)
        ###make the label as 3xN matrix
        full_label = np.row_stack((label, np.ones(shape=(1,label.shape[1]))))
        label_rotated=np.dot(full_M,full_label)
        label_rotated=label_rotated[0:2,:]
        #label_rotated = label_rotated.astype(np.int32)
        label_rotated=label_rotated.T
        return img_rotated,label_rotated 
Example #18
Source File: augmentation.py    From TextSnake.pytorch with MIT License 5 votes vote down vote up
def __call__(self, img, polygons=None):
        if np.random.randint(2):
            return img, polygons
        angle = np.random.uniform(-self.up, self.up)  #
        rows, cols = img.shape[0:2]
        M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1.0)
        img = cv2.warpAffine(img, M, (cols, rows), borderValue=[0, 0, 0])
        center = cols / 2.0, rows / 2.0
        if polygons is not None:
            for polygon in polygons:
                x, y = self.rotate(center, polygon.points, angle)
                pts = np.vstack([x, y]).T
                polygon.points = pts
        return img, polygons 
Example #19
Source File: geometry.py    From DDRL with Apache License 2.0 5 votes vote down vote up
def _augment(self, img, deg):
        center = (img.shape[1]*0.5, img.shape[0]*0.5)
        rot_m = cv2.getRotationMatrix2D(center, deg, 1)
        ret = cv2.warpAffine(img, rot_m, img.shape[1::-1],
                flags=self.interp, borderMode=cv2.BORDER_CONSTANT)
        neww, newh = RotationAndCropValid.largest_rotated_rect(ret.shape[1], ret.shape[0], deg)
        neww = min(neww, ret.shape[1])
        newh = min(newh, ret.shape[0])
        newx = center[0] - neww * 0.5
        newy = center[1] - newh * 0.5
        #print(ret.shape, deg, newx, newy, neww, newh)
        return ret[newy:newy+newh,newx:newx+neww] 
Example #20
Source File: geometry.py    From DDRL with Apache License 2.0 5 votes vote down vote up
def _get_augment_params(self, img):
        center = img.shape[1::-1] * self._rand_range(
                self.center_range[0], self.center_range[1], (2,))
        deg = self._rand_range(-self.max_deg, self.max_deg)
        return cv2.getRotationMatrix2D(tuple(center), deg, 1) 
Example #21
Source File: Generator_augmentation.py    From Korean-license-plate-Generator with MIT License 5 votes vote down vote up
def image_augmentation(img, ang_range=6, shear_range=3, trans_range=3):
    # Rotation
    ang_rot = np.random.uniform(ang_range) - ang_range / 2
    rows, cols, ch = img.shape
    Rot_M = cv2.getRotationMatrix2D((cols / 2, rows / 2), ang_rot, 0.9)

    # Translation
    tr_x = trans_range * np.random.uniform() - trans_range / 2
    tr_y = trans_range * np.random.uniform() - trans_range / 2
    Trans_M = np.float32([[1, 0, tr_x], [0, 1, tr_y]])

    # Shear
    pts1 = np.float32([[5, 5], [20, 5], [5, 20]])

    pt1 = 5 + shear_range * np.random.uniform() - shear_range / 2
    pt2 = 20 + shear_range * np.random.uniform() - shear_range / 2
    pts2 = np.float32([[pt1, 5], [pt2, pt1], [5, pt2]])
    shear_M = cv2.getAffineTransform(pts1, pts2)

    img = cv2.warpAffine(img, Rot_M, (cols, rows))
    img = cv2.warpAffine(img, Trans_M, (cols, rows))
    img = cv2.warpAffine(img, shear_M, (cols, rows))

    # Brightness
    img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    img = np.array(img, dtype=np.float64)
    random_bright = .4 + np.random.uniform()
    img[:, :, 2] = img[:, :, 2] * random_bright
    img[:, :, 2][img[:, :, 2] > 255] = 255
    img = np.array(img, dtype=np.uint8)
    img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB)

    # Blur
    blur_value = random.randint(0,5) * 2 + 1
    img = cv2.blur(img,(blur_value, blur_value))

    return img 
Example #22
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 5 votes vote down vote up
def rotation(self, in_img, rect_size, center, angle):
        '''
            rect_size: (h, w)
            rotation an image
        '''
        if len(in_img.shape) == 3:
            in_large = np.zeros((int(in_img.shape[0] * 1.5), int(in_img.shape[1] * 1.5), 3)).astype(in_img.dtype)
        else:
            in_large = np.zeros((int(in_img.shape[0] * 1.5), int(in_img.shape[1] * 1.5))).astype(in_img.dtype)

        x = int(max(in_large.shape[1] / 2 - center[0], 0))
        y = int(max(in_large.shape[0] / 2 - center[1], 0))

        width = int(min(in_img.shape[1], in_large.shape[1] - x))
        height = int(min(in_img.shape[0], in_large.shape[0] - y))

        if width != in_img.shape[1] and height != in_img.shape[0]:
            return in_img, False

        new_center = (in_large.shape[1] / 2, in_large.shape[0] / 2)

        rot_mat = cv2.getRotationMatrix2D(new_center, angle, 1)

        mat_rotated = cv2.warpAffine(in_large, rot_mat, (in_large.shape[1], in_large.shape[0]), cv2.INTER_CUBIC)

        img_crop = cv2.getRectSubPix(mat_rotated, (int(rect_size[0]), int(rect_size[0])), new_center)
        return img_crop, True 
Example #23
Source File: imutils.py    From ALPR-Indonesia with MIT License 5 votes vote down vote up
def rotate(image, angle, center = None, scale = 1.0):
	# Grab the dimensions of the image
	(h, w) = image.shape[:2]

	# If the center is None, initialize it as the center of
	# the image
	if center is None:
		center = (w / 2, h / 2)

	# Perform the rotation
	M = cv2.getRotationMatrix2D(center, angle, scale)
	rotated = cv2.warpAffine(image, M, (w, h))

	# Return the rotated image
	return rotated 
Example #24
Source File: image_preprocess_multi_gpu.py    From R3Det_Tensorflow with MIT License 5 votes vote down vote up
def rotate_img_np(img, gtboxes_and_label, r_theta):
    h, w, c = img.shape
    center = (w // 2, h // 2)

    M = cv2.getRotationMatrix2D(center, r_theta, 1.0)
    cos, sin = np.abs(M[0, 0]), np.abs(M[0, 1])
    nW, nH = int(h*sin + w*cos), int(h*cos + w*sin)  # new W and new H
    M[0, 2] += (nW/2) - center[0]
    M[1, 2] += (nH/2) - center[1]
    rotated_img = cv2.warpAffine(img, M, (nW, nH))
    # -------

    new_points_list = []
    obj_num = len(gtboxes_and_label)
    for st in range(0, 7, 2):
        points = gtboxes_and_label[:, st:st+2]
        expand_points = np.concatenate((points, np.ones(shape=(obj_num, 1))), axis=1)
        new_points = np.dot(M, expand_points.T)
        new_points = new_points.T
        new_points_list.append(new_points)
    gtboxes = np.concatenate(new_points_list, axis=1)
    gtboxes_and_label = np.concatenate((gtboxes, gtboxes_and_label[:, -1].reshape(-1, 1)), axis=1)
    gtboxes_and_label = np.asarray(gtboxes_and_label, dtype=np.int32)

    return rotated_img, gtboxes_and_label 
Example #25
Source File: utils.py    From keras-face-recognition with MIT License 5 votes vote down vote up
def Alignment_1(img,landmark):

    if landmark.shape[0]==68:
        x = landmark[36,0] - landmark[45,0]
        y = landmark[36,1] - landmark[45,1]
    elif landmark.shape[0]==5:
        x = landmark[0,0] - landmark[1,0]
        y = landmark[0,1] - landmark[1,1]

    if x==0:
        angle = 0
    else: 
        angle = math.atan(y/x)*180/math.pi

    center = (img.shape[1]//2, img.shape[0]//2)

    RotationMatrix = cv2.getRotationMatrix2D(center, angle, 1)
    new_img = cv2.warpAffine(img,RotationMatrix,(img.shape[1],img.shape[0])) 

    RotationMatrix = np.array(RotationMatrix)
    new_landmark = []
    for i in range(landmark.shape[0]):
        pts = []    
        pts.append(RotationMatrix[0,0]*landmark[i,0]+RotationMatrix[0,1]*landmark[i,1]+RotationMatrix[0,2])
        pts.append(RotationMatrix[1,0]*landmark[i,0]+RotationMatrix[1,1]*landmark[i,1]+RotationMatrix[1,2])
        new_landmark.append(pts)

    new_landmark = np.array(new_landmark)

    return new_img, new_landmark 
Example #26
Source File: transforms.py    From VS-ReID with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def rotation(img, degrees, interpolation=cv2.INTER_LINEAR, value=0):
    if isinstance(degrees, list):
        if len(degrees) == 2:
            degree = random.uniform(degrees[0], degrees[1])
        else:
            degree = random.choice(degrees)
    else:
        degree = degrees

    h, w = img.shape[0:2]
    center = (w / 2, h / 2)
    map_matrix = cv2.getRotationMatrix2D(center, degree, 1.0)

    img = cv2.warpAffine(
        img,
        map_matrix, (w, h),
        flags=interpolation,
        borderMode=cv2.BORDER_CONSTANT,
        borderValue=value)

    return img 
Example #27
Source File: preprocessing.py    From DeepResearch with MIT License 5 votes vote down vote up
def image_rotate(img, angle):
    """
    Image rotation at certain angle. It is used for data augmentation
    """
    rows, cols, _ = img.shape
    M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
    dst = cv2.warpAffine(img, M, (cols, rows))
    return np.expand_dims(dst, 0) 
Example #28
Source File: landmark_augment.py    From face_landmark_dnn with MIT License 5 votes vote down vote up
def __rotate(self, image, landmarks, max_angle):
        """
        Do image rotate
        Args:
            image: a numpy type
            landmarks: face landmarks with format [(x1, y1), ...]. range is 0-w or h in int
            max_angle: random to rotate in [-max_angle, max_angle]. range is 0-180.
        Return:
            an image and landmarks will be returned
        Raises:
            No
        """
        c_x = (min(landmarks[:, 0]) + max(landmarks[:, 0])) / 2
        c_y = (min(landmarks[:, 1]) + max(landmarks[:, 1])) / 2
        h, w = image.shape[:2]
        angle = np.random.randint(-max_angle, max_angle)
        M = cv2.getRotationMatrix2D((c_x, c_y), angle, 1)
        image = cv2.warpAffine(image, M, (w, h))
        b = np.ones((landmarks.shape[0], 1))
        d = np.concatenate((landmarks, b), axis=1)
        landmarks = np.dot(d, np.transpose(M))
        return image, landmarks 
Example #29
Source File: data_inspect_utils.py    From centerpose with MIT License 5 votes vote down vote up
def rotate_bound(image, angle):
    # grab the dimensions of the image and then determine the
    # centre
    (h, w) = image.shape[:2]
    (cX, cY) = (w // 2, h // 2)

    # grab the rotation matrix (applying the negative of the
    # angle to rotate clockwise), then grab the sine and cosine
    # (i.e., the rotation components of the matrix)
    M = cv2.getRotationMatrix2D((cX, cY), angle, 1.0)
    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((h * sin) + (w * cos))
    nH = int((h * cos) + (w * sin))

    # adjust the rotation matrix to take into account translation
    M[0, 2] += (nW / 2) - cX
    M[1, 2] += (nH / 2) - cY

    # perform the actual rotation and return the image
    return cv2.warpAffine(image, M, (nW, nH)) 
Example #30
Source File: transforms.py    From vedaseg with Apache License 2.0 5 votes vote down vote up
def __call__(self, image, mask):
        if random.random() < self.p:
            h, w, c = image.shape

            angle = random.uniform(*self.degrees)
            matrix = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)

            image = cv2.warpAffine(image, M=matrix, dsize=(w, h), flags=self.mode, borderMode=self.border_mode,
                                   borderValue=self.image_value)
            mask = cv2.warpAffine(mask, M=matrix, dsize=(w, h), flags=cv2.INTER_NEAREST, borderMode=self.border_mode,
                                  borderValue=self.mask_value)

        return image, mask