仿射变换

  仿射变换通过一系列原子变换复合实现,具体包括:平移(Translation)、缩放(Scale)、旋转(Rotation)、翻转(Flip)和错切(Shear)。

 
平移:
 
缩放:
旋转:
翻转:
错切:

示例

from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse


src = cv.imread('D:/lena.jpg')
if src is None:
    print('Could not open or find the image:', args.input)
    exit(0)
## [Load the image]

## [Set your 3 points to calculate the  Affine Transform]
srcTri = np.array( [[0, 0], [src.shape[1] - 1, 0], [0, src.shape[0] - 1]] ).astype(np.float32)
dstTri = np.array( [[0, src.shape[1]*0.33], [src.shape[1]*0.85, src.shape[0]*0.25], [src.shape[1]*0.15, src.shape[0]*0.7]] ).astype(np.float32)
## [Set your 3 points to calculate the  Affine Transform]

## [Get the Affine Transform]
warp_mat = cv.getAffineTransform(srcTri, dstTri)
print("warp_mat: \n",warp_mat)
## [Get the Affine Transform]

## [Apply the Affine Transform just found to the src image]
warp_dst = cv.warpAffine(src, warp_mat, (src.shape[1], src.shape[0]))
## [Apply the Affine Transform just found to the src image]

# Rotating the image after Warp

## [Compute a rotation matrix with respect to the center of the image]
center = (warp_dst.shape[1]//2, warp_dst.shape[0]//2)
angle = -50
scale = 0.6
## [Compute a rotation matrix with respect to the center of the image]

## [Get the rotation matrix with the specifications above]
rot_mat = cv.getRotationMatrix2D( center, angle, scale )
print("rot_mat: \n",rot_mat)
## [Get the rotation matrix with the specifications above]

## [Rotate the warped image]
warp_rotate_dst = cv.warpAffine(warp_dst, rot_mat, (warp_dst.shape[1], warp_dst.shape[0]))
## [Rotate the warped image]

## [Show what you got]
cv.imshow('Source image', src)
cv.imshow('Warp', warp_dst)
cv.imshow('Warp + Rotate', warp_rotate_dst)
## [Show what you got]

## [Wait until user exits the program]
cv.waitKey()
## [Wait until user exits the program]

输出结果——分别为仿射矩阵和旋转矩阵:

warp_mat: 
 [[ 8.51703407e-01  1.51515152e-01  0.00000000e+00]
 [-8.21643287e-02  3.68080833e-01  1.65000000e+02]]
rot_mat: 
 [[  0.38567257  -0.45962667 267.56927168]
 [  0.45962667   0.38567257  37.44653721]]

 

 

 

 

posted @ 2021-02-23 09:03  为红颜  阅读(923)  评论(0编辑  收藏  举报