簡體   English   中英

使用OpenCV通過Python和C ++計算基本矩陣的結果不同

[英]Different result in computing fundamental matrix by Python and C++ using OpenCV

我正在使用OpenCV計算Python和C ++中視頻里程計的基本矩陣。 我試圖保持兩種實現中的代碼完全相同。 但是,我在兩者中得到了不同的結果。 在Python中,它可以正常工作,而在C ++中它顯示完全不正確的結果。 下面是他們的代碼和輸出的部分示例(第一個在Python中,第二個在C ++中)

Python版本代碼:

import os
import sys
import cv2
import numpy as np
import math

# Main Function
if __name__ == '__main__':
    K = np.matrix([[522.4825, 0,        300.9989], 
                   [0,        522.5723, 258.1389], 
                   [0.0,      0.0,      1.0]])
img1 = cv2.imread(sys.argv[1] + ".jpg")
img2 = cv2.imread(sys.argv[2] + ".jpg")

# sift = cv2.SURF()

detector = cv2.FeatureDetector_create("SURF")    # SURF, FAST, SIFT
descriptor = cv2.DescriptorExtractor_create("SURF") # SURF, SIFT

# kp1, des1 = sift.detectAndCompute(img1,None)
# kp2, des2 = sift.detectAndCompute(img2,None)

kp1 = detector.detect(img1)
kp2 = detector.detect(img2) 

k1, des1 = descriptor.compute(img1,kp1)
k2, des2 = descriptor.compute(img2,kp2)

# BFMatcher with default params
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2, k=2)

good = []

# Apply ratio test
for m,n in matches:
    if m.distance < 0.7*n.distance:
            good.append(m)

MIN_MATCH_COUNT = 10
if len(good)>MIN_MATCH_COUNT:
    src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
    dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
    F, mask = cv2.findFundamentalMat(src_pts, dst_pts, cv2.RANSAC, 5.0)
    matchesMask = mask.ravel().tolist()
else:
    print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
    matchesMask = None

print F

它的輸出:

[[ -3.22706105e-07   1.12585581e-04  -2.86938406e-02]
[ -1.16307090e-04  -5.04244159e-07   5.60714444e-02]
[  2.98839742e-02  -5.99974406e-02   1.00000000e+00]]

這里的C ++版本:

#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/nonfree/features2d.hpp>
#include <opencv2/legacy/legacy.hpp>

using namespace std;

int main(int argc,char *argv[]) {
    //Define intrinsic matrix
    cv::Mat intrinsic = (cv::Mat_<double>(3,3) << 522.4825, 0, 300.9989,
            0, 522.5723, 258.1389,
            0, 0, 1);

    // Read input images
    string jpg1 = argv[1];
    jpg1.append(".jpg");
    string jpg2 = argv[2];
    jpg2.append(".jpg");
    cv::Mat image1 = cv::imread(jpg1,0);
    cv::Mat image2 = cv::imread(jpg2,0);
    if (!image1.data || !image2.data)
        return 0;

    // Display the images
    // cv::namedWindow("Image 1");
    // cv::imshow("Image 1",image1);
    // cv::namedWindow("Image 2");
    // cv::imshow("Image 2",image2);

    // pointer to the feature point detector object
    cv::Ptr<cv::FeatureDetector> detector = new cv::SurfFeatureDetector();
    // pointer to the feature descriptor extractor object
    cv::Ptr<cv::DescriptorExtractor> extractor = new cv::SurfDescriptorExtractor();

    // Detection of the SURF features
    vector<cv::KeyPoint> keypoints1, keypoints2;
    detector->detect(image1,keypoints1);
    detector->detect(image2,keypoints2);

    // Extraction of the SURF descriptors
    cv::Mat descriptors1, descriptors2;
    extractor->compute(image1,keypoints1,descriptors1);
    extractor->compute(image2,keypoints2,descriptors2);

    // Construction of the matcher
    cv::BruteForceMatcher<cv::L2<float> > matcher;

    vector<vector<cv::DMatch> > matches;
    vector<cv::DMatch> good_matches;
    matcher.knnMatch(descriptors1, descriptors2, matches, 2);

    for (vector<vector<cv::DMatch> >::iterator matchIterator= matches.begin();
         matchIterator!= matches.end(); ++matchIterator) {
        if ((*matchIterator)[0].distance < 0.7f * (*matchIterator)[1].distance) {
            good_matches.push_back((*matchIterator)[0]);
        }
    }

    // Convert keypoints into Point2f
    vector<cv::Point2f> src_pts, dst_pts;
    for (vector<cv::DMatch>::iterator it= good_matches.begin();
         it!= good_matches.end(); ++it)
    {
        // Get the position of left keypoints
        float x= keypoints1[it->queryIdx].pt.x;
        float y= keypoints1[it->queryIdx].pt.y;
        src_pts.push_back(cv::Point2f(x,y));
        // Get the position of right keypoints
        x= keypoints2[it->trainIdx].pt.x;
        y= keypoints2[it->trainIdx].pt.y;
        dst_pts.push_back(cv::Point2f(x,y));
    }
    // Compute F matrix using RANSAC
    cv::Mat fundemental = cv::findFundamentalMat(
            cv::Mat(src_pts),cv::Mat(dst_pts), // matching points
            CV_FM_RANSAC,  // RANSAC method
            5.0); // distance
    cout <<  fundemental << endl;

    return 0;
}

它的輸出:

[-4.310057787788129e-06, 0.0002459670522815174, -0.0413520716270485;
-0.0002531048911221476, -8.423657757958228e-08, 0.0974897887347238;
0.04566865455090797, -0.1062956485414729, 1]

這是兩個測試圖像: 圖像1 圖像2

我找不到原因。 誰能告訴我為什么?

既然沒有人回答我會分享我的想法。 你只檢查F中的數字,或者你以某種方式應用它並觀察不正確的結果? 正如@ brandon-white已經注意到的那樣,浮點精度可能是其中一個原因。 但實際上它更復雜。

首先想到的是C ++ OpenCV中的AFAIK使用它自己的例程來進行矩陣和其他數學運算,而在python中盡可能使用numpy。 也許在引擎蓋下他們使用類似的算法/實現,但是你仍然可以得到數字上不同的結果,特別是在處理模糊性(特征向量分解,SVD等)的情況下。

此外,您正在使用RANSAC來估計F.為了處理(理論上)任何數量的異常值,RANSAC從所有關鍵點獲取一個小的隨機樣本,並嘗試找到滿足某些約束的對。 它多次執行此操作,然后獲取最佳樣本以計算最終模型。 因此,如果您適當地為偽隨機生成例程播種,那么基本上您將最終得到不同的點來估計每次運行的F. 但是,通常單應性和基本矩陣估計器使用更智能的方法,並且在找到最滿足約束的樣本之后 - 滿足該模型的所有點用於再次重新計算矩陣。 這樣,您應該獲得更一致的結果,理想情況下,如果RANSAC參數正常。 我不確定它是否在OpenCV中使用,但我想是的。

最后,有退化的情況 ,其中F無法完全估計 - 平面運動的情況,當你的所有關鍵點都在一個平面上(在3D世界中),以及純粹的旋轉相機運動。 既然你說你的代碼在Python中工作,那可能不是這樣,但仍然需要考慮。

因此,如果您還沒有這樣做 - 嘗試檢查F矩陣,您獲得一些數據,以確保您得到的結果真的不同。 在那種情況下 - 某處應該有錯誤(誠然,我還沒有仔細檢查過您的代碼)。

此外,顯示用於F計算的匹配可能對調試很有用,因為這會縮小場所的范圍,您的代碼可能表現不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM