Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

OpenCV 實作:三對點計算仿射變換與旋轉矩陣

仿射變換只需要三對點就能定下來。這支程式示範兩件事:先用三對點求出變形矩陣做仿射變換,再用 cv2DRotationMatrix 產生「繞中心旋轉+縮放」的矩陣。

// 仿射變換.cpp : 定義控制台應用程序的入口點。
//
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <windows.h>

#define affine
#ifdef affine
int main(int argc, char** argv)
{
    CvPoint2D32f srcTri[3], dstTri[3];
    CvMat* rot_mat = cvCreateMat(2,3,CV_32FC1);
    CvMat* warp_mat = cvCreateMat(2,3,CV_32FC1);
    IplImage *src, *dst;
    if( argc == 1 && ((src = cvLoadImage("lenagray.jpg",1)) != 0 )//原文中是argc == 2,錯誤
    {
        dst = cvCloneImage(src);
        dst->origin = src->origin;
        cvZero(dst);

        //COMPUTE WARP MATRIX
        srcTri[0].x = 0;              //src Top left
        srcTri[0].y = 0;
        srcTri[1].x = src->width - 1; //src Top right
        srcTri[1].y = 0;
        srcTri[2].x = 0;              //src Bottom left
        srcTri[2].y = src->height - 1;
        //- - - - - - - - - - - - - - -//
        dstTri[0].x = src->width*0.0; //dst Top left
        dstTri[0].y = src->height*0.33;
        dstTri[1].x = src->width*0.85;//dst Top right
        dstTri[1].y = src->height*0.25;
        dstTri[2].x = src->width*0.15;//dst Bottom left
        dstTri[2].y = src->height*0.7;
        cvGetAffineTransform(srcTri,dstTri,warp_mat);//由三對點計算仿射變換
        cvWarpAffine(src,dst,warp_mat);
        cvCopy(dst,src);

        //COMPUTE ROTATION MATRIX
        CvPoint2D32f center = cvPoint2D32f(src->width/2,
                                            src->height/2);
        double angle = -50.0;
        double scale = 0.6;
        cv2DRotationMatrix(center,angle,scale,rot_mat);
        cvWarpAffine(src,dst,rot_mat);

        //DO THE TRANSFORM:
        cvNamedWindow( "Affine_Transform", 1 );
        cvShowImage( "Affine_Transform", dst );
        cvWaitKey();
    }
    cvReleaseImage(&dst);
    cvReleaseMat(&rot_mat);
    cvReleaseMat(&warp_mat);
    system("pause");
    return 0;
}
#endif

兩個函式的分工

cvGetAffineTransform 接收三對 srcTri / dstTri,算出 2×3 的仿射矩陣,再交給 cvWarpAffine 實際映射像素;想讓影像繞某個中心旋轉並縮放時,改用 cv2DRotationMatrix,把中心點、角度與縮放比例傳進去即可產生對應矩陣,同樣用 cvWarpAffine 套用。注意原書範例把 argc 判斷寫成 2,實際上應該是 1,這裡已經修正。

Copyright © Linux教程網 All Rights Reserved