OpenCV 之 平面單應性


    上篇 OpenCV 之 圖像幾何變換 介紹了等距、相似和仿射變換,本篇側重投影變換的平面單應性、OpenCV相關函數、應用實例等。

1  投影變換

    投影變換 (Projective Transformation),是仿射變換的一般化,二者區別如下:   

        

1.1  平面單應性

    假定平面 $P^{2}$ 與 $Q^{2}$ 之間,存在映射,使得 $P^{2}$ 內任意點 $(x_p, y_q)$,滿足下式:

    $\quad \begin{bmatrix} x_q \\ y_q \\  1 \end{bmatrix} = \begin{bmatrix} h_{11} & h_{12} & h_{13} \\ h_{21} & h_{22} & h_{23} \\ h_{31} & h_{32} & h_{33} \end{bmatrix} \begin{bmatrix} x_p \\ y_p \\  1 \end{bmatrix} $

    當 $H_{3 \times 3}$ 非奇異時,$P^{2}$ 與 $Q^{2}$ 之間的映射即為 2D 投影變換,也稱 平面單應性, $H_{3 \times 3}$ 則為 單應性矩陣

    例如:在相機標定中,如果選用 平面標定板,則 物平面 和 像平面 之間,就是一種典型的 平面單應性 映射

      

1.2  單應性矩陣

    $H_{3 \times 3}$ 有 9 個未知數,但實際只有 8 個自由度 (DoF),其歸一化有兩種方法:

    法一,令 $h_{33}=1$;法二,加單位向量限制  $h_{11}^2+h_{12}^2+h_{13}^2+h_{21}^2+h_{22}^2+h_{23}^2+h_{31}^2+h_{32}^2+h_{33}^2=1$

    下面接着法一,繼續推導公式:

    $\quad x' = \dfrac{h_{11}x + h_{12}y + h_{13}}{h_{31}x + h_{32}y + 1} $

    $\quad y' = \dfrac{h_{21}x + h_{22}y + h_{23}}{h_{31}x + h_{32}y + 1} $

   整理得:

    $\quad x \cdot h_{11} + y \cdot h_{12} + h_{13} - xx' \cdot h_{31} - yx' \cdot h_{32} = x' $

    $\quad x \cdot h_{21} + y \cdot h_{22} + h_{23} - xy' \cdot h_{31} - yy' \cdot h_{32} = y' $

   一組對應特征點 $(x, y) $ -> $ (x', y')$ 可構造 2 個方程,要求解 8 個未知數 (歸一化后的),則需要 8 個方程,4 組對應特征點

    $\quad \begin{bmatrix} x_{1} & y_{1} & 1 &0 &0&0 & -x_{1}x'_{1} & -y_{1}x'_{1} \\ 0&0&0& x_{1} & y_{1} &1& -x_{1}y'_{1} & -y_{1}y'_{1}  \\ x_{2} & y_{2} & 1 &0 &0&0 & -x_{2}x'_{2} & -y_{2}x'_{2} \\ 0&0&0& x_{2} & y_{2} &1& -x_{2}y'_{2} & -y_{2}y'_{2} \\ x_{3} & y_{3} & 1 &0 &0&0 & -x_{3}x'_{3} & -y_{3}x'_{3} \\ 0&0&0& x_{3} & y_{3} &1& -x_{3}y'_{3} & -y_{3}y'_{3}  \\ x_{4} & y_{4} & 1 &0 &0&0 & -x_{4}x'_{4} & -y_{4}x'_{4} \\ 0&0&0& x_{4} & y_{4} &1& -x_{4}y'_{4} & -y_{4}y'_{4} \end{bmatrix} \begin{bmatrix} h_{11} \\ h_{12}\\h_{13}\\h_{21}\\h_{22}\\h_{23}\\h_{31}\\h_{32} \end{bmatrix} = \begin{bmatrix} x'_{1}\\y'_{1}\\x'_{2}\\y'_{2}\\x'_{3}\\y'_{3}\\x'_{4}\\y'_{4}  \end{bmatrix} $

   因此,求 $H$ 可轉化為求解 $Ax=b$,參見 OpenCV 中 getPerspectiveTransform() 的源碼實現

 

2  OpenCV 函數

2.1  投影變換矩陣

    a)  四組對應特征點:已知四組對應特征點坐標,帶入 getPerspectiveTransform() 函數中,可求解 src 投影到 dst 的單應性矩陣 $H_{3 \times 3}$

  Mat getPerspectiveTransform (
      const Point2f     src[],    // 原圖像的四角頂點坐標
      const Point2f     dst[],    // 目標圖像的四角頂點坐標
      int solveMethod = DECOMP_LU // solve() 的解法
  )  

    該函數的源代碼實現如下:構造8組方程,轉化為 $Ax=b$ 的問題,調用 solve() 函數來求解

Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod)
{
    Mat M(3, 3, CV_64F), X(8, 1, CV_64F, M.ptr());
    double a[8][8], b[8];
    Mat A(8, 8, CV_64F, a), B(8, 1, CV_64F, b);

    for( int i = 0; i < 4; ++i )
    {
        a[i][0] = a[i+4][3] = src[i].x;
        a[i][1] = a[i+4][4] = src[i].y;
        a[i][2] = a[i+4][5] = 1;
        a[i][3] = a[i][4] = a[i][5] =
        a[i+4][0] = a[i+4][1] = a[i+4][2] = 0;
        a[i][6] = -src[i].x*dst[i].x;
        a[i][7] = -src[i].y*dst[i].x;
        a[i+4][6] = -src[i].x*dst[i].y;
        a[i+4][7] = -src[i].y*dst[i].y;
        b[i] = dst[i].x;
        b[i+4] = dst[i].y;
    }

    solve(A, B, X, solveMethod);
    M.ptr<double>()[8] = 1.;

    return M;
}  

    b)  多組對應特征點:對於兩個平面之間的投影變換,求得對應的多組特征點后,帶入 findHomography() 函數,便可得到 srcPoints 投影到 dstPoints 的 $H_{3 \times 3}$

 Mat findHomography (
      InputArray      srcPoints,   // 原始平面特征點坐標,類型是 CV_32FC2 或 vector<Point2f> 
      InputArray      dstPoints,   // 目標平面特征點坐標,類型是 CV_32FC2 或 vector<Point2f> 
      int method = 0,              // 0--最小二乘法; RANSAC--基於ransac的方法
      double ransacReprojThreshold = 3, // 最大允許反投影誤差
      OutputArray mask = noArray(),     // 
      const int maxIters = 2000,        // 最多迭代次數
      const double confidence = 0.995   // 置信水平
  )  

 2.2  投影變換圖像

     已知單應性矩陣 $H_{3 \times 3}$,將任意圖像代入 warpPerspective() 中,便可得到經過 2D投影變換 的目標圖像

  void warpPerspective (
      InputArray      src,  // 輸入圖像
      OutputArray     dst,  // 輸出圖象(大小 dsize,類型同 src)
      InputArray        M,  // 3x3 單應性矩陣
      Size          dsize,  // 輸出圖像的大小
      int     flags = INTER_LINEAR,         // 插值方法 
      int     borderMode = BORDER_CONSTANT, //
      const Scalar& borderValue = Scalar()  // 
  )     

 

3  代碼示例

3.1  透視校正

    像平面 image1 和 image2 是相機在不同位置對同一物平面所成的像,這三個平面任選兩個都互有 平面單應性

            

    以相機標定為例,當人拿着棋盤格旋轉不同角度時,可利用任意兩個棋盤格間的單應性,將旋轉不同角度的棋盤格,轉換為統一角度

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"

using namespace cv;

Size kPatternSize = Size(9, 6);

int main()
{
    // 1) read image
    Mat src = imread("chessboard1.jpg");
    Mat dst = imread("chessboard2.jpg");
    if (src.empty() || dst.empty())
        return -1;

    // 2) find chessboard corners
    std::vector<Point2f> corners1, corners2;
    bool found1 = findChessboardCorners(src, kPatternSize, corners1);
    bool found2 = findChessboardCorners(dst, kPatternSize, corners2);
    if (!found1 || !found2)
        return -1;

    // 3) estimate H matrix
    Mat H = findHomography(corners1, corners2, RANSAC);
    // 4) 
    Mat src_warp;
    warpPerspective(src, src_warp, H, src.size());

    // 5) 
    imshow("src", src);
    imshow("dst", dst);
    imshow("src_warp", src_warp);
    waitKey();
}  

   結果如下:

      

                棋盤格傾斜                                        棋盤格正對                                     傾斜校正為正對

3.2  圖像拼接

    當相機圍繞其投影軸,只做旋轉運動時,所有的像素點可等效視為在一個無窮遠的平面上,則單應性矩陣可由旋轉變換 $R$ 和 相機標定矩陣 $K$ 來表示

    $\quad \normalsize s \begin{bmatrix} x' \\ y' \\1 \end{bmatrix} = \normalsize K \cdot \normalsize R \cdot \normalsize K^{-1} \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}$

    因此,如果已知相機的標定矩陣,以及旋轉變換前后的位姿,可利用平面單應性,將旋轉變換前后的兩幅圖像拼接起來

    

    用 Blender 軟件,獲取相機只做旋轉變換時的視圖1和視圖2,在已知相機標定矩陣和旋轉矩陣的情況下,可計算出兩個視圖之間的單應性矩陣,從而完成拼接。

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/calib3d.hpp"

using namespace cv;

int main()
{
    // 1) read image
    Mat img1 = imread("view1.jpg");
    Mat img2 = imread("view2.jpg");
    if (img1.empty() || img2.empty())
        return -1;

    // 2) camera pose from Blender at location 1
    Mat c1Mo = (Mat_<double>(4, 4) << 0.9659258723258972, 0.2588190734386444, 0.0, 1.5529145002365112,
                                      0.08852133899927139, -0.3303661346435547, -0.9396926164627075, -0.10281121730804443,
                                      -0.24321036040782928, 0.9076734185218811, -0.342020183801651, 6.130080699920654,
                                      0, 0, 0, 1);
    // camera pose from Blender at location 2
    Mat c2Mo = (Mat_<double>(4, 4) << 0.9659258723258972, -0.2588190734386444, 0.0, -1.5529145002365112,
                                      -0.08852133899927139, -0.3303661346435547, -0.9396926164627075, -0.10281121730804443,
                                      0.24321036040782928, 0.9076734185218811, -0.342020183801651, 6.130080699920654,
                                      0, 0, 0, 1);
    // 3) camera intrinsic parameters
    Mat cameraMatrix = (Mat_<double>(3, 3) << 700.0, 0.0, 320.0,
                                              0.0, 700.0, 240.0,
                                              0, 0, 1);
    // 4) extract rotation
    Mat R1 = c1Mo(Range(0, 3), Range(0, 3));
    Mat R2 = c2Mo(Range(0, 3), Range(0, 3));

    // 5) compute rotation displacement: c1Mo * oMc2
    Mat R_2to1 = R1 * R2.t();

    // 6) homography
    Mat H = cameraMatrix * R_2to1 * cameraMatrix.inv();
    H /= H.at<double>(2, 2);

    // 7) warp 
    Mat img_stitch;
    warpPerspective(img2, img_stitch, H, Size(img2.cols * 2, img2.rows));

    // 8) stitch
    Mat half = img_stitch(Rect(0, 0, img1.cols, img1.rows));
    img1.copyTo(half);
    imshow("Panorama stitching", img_stitch);
    waitKey();
}  

   輸出結果如下:

        

                       視圖1                                           視圖2                                                                  拼接后的視圖

   

參考資料:

    OpenCV Tutorials / feature2d module / Basic concepts of the homography explained with code

    Lecture 16: Planar Homographies, Robert Collins

    Affine and Projective Transformations

 


免責聲明!

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



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