仿射變換


  仿射變換通過一系列原子變換復合實現,具體包括:平移(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]]

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM