opencv提取surf特徵點出現的錯誤
阿新 • • 發佈:2018-12-29
opencv實現surf特徵的提取,本來是一個很簡單的程式碼,結果我執行時卻出現了各種錯誤,下面來談談我出現的錯誤及問題的解決過程。
首先,我把提取surf特徵的過程整合成了一個函式,我單獨建立一個工程讀取兩張圖片,然後呼叫這個surf提取的函式時時無論是debug還是release模式下都是沒有問題的,當我把這個函式新增到我現在已有的工程程式碼裡面的時候出現了各種奇葩錯誤。下面是我surf特徵提取的函式
void surfdetect(IplImage *image1,IplImage *image2) { using namespace std; //IplImage *image1,*image2; //image1 = cvLoadImage("lena1.jpg"); //image2= cvLoadImage("lena2.jpg"); cv::SurfFeatureDetector detector; cv::SurfDescriptorExtractor descriptor_extractor; cv::BruteForceMatcher<cv::L2<float> > descriptor_matcher; //提取特徵點 std::vector<cv::KeyPoint> keypoints1,keypoints2; detector.detect( image1, keypoints1 );//檢測img1中的Surf特徵點,儲存到keypoints1中 detector.detect( image2, keypoints2 ); cout<<"影象1特徵點個數:"<<keypoints1.size()<<endl; cout<<"影象2特徵點個數:"<<keypoints2.size()<<endl; //根據特徵點計算特徵描述子矩陣,即特徵向量矩陣 cv::Mat descriptors1,descriptors2; descriptor_extractor.compute( image1, keypoints1, descriptors1 ); descriptor_extractor.compute( image2, keypoints2, descriptors2 ); cv::Mat img_keypoints1,img_keypoints2; drawKeypoints(image1,keypoints1,img_keypoints1); drawKeypoints(image2,keypoints2,img_keypoints2); //imshow("Src1",img_keypoints1); //cv::waitKey(6000); //imshow("Src2",img_keypoints2); //cv::waitKey(6000); std::vector<cv::DMatch> matches;//匹配結果 descriptor_matcher.match( descriptors1, descriptors2, matches );//匹配兩個影象的特徵矩陣 cout<<"Match個數:"<<matches.size()<<endl; cv::Mat img_matches1,img_matches2; cv::drawMatches(image1,keypoints1,image2,keypoints2,matches,img_matches1); imshow("粗匹配",img_matches1); cv::waitKey(0); double max_dist = 0; double min_dist = 100; for(int i=0; i<matches.size(); i++) { double dist = matches[i].distance; if(dist < min_dist) min_dist = dist; if(dist > max_dist) max_dist = dist; } cout<<"最大距離:"<<max_dist<<endl; cout<<"最小距離:"<<min_dist<<endl; //篩選出較好的匹配點 std::vector<cv::DMatch> goodMatches; for(int i=0; i<matches.size(); i++) { if(matches[i].distance < 0.05 * max_dist) { goodMatches.push_back(matches[i]); } } cout<<"goodMatch個數:"<<goodMatches.size()<<endl; cv::drawMatches(image1,keypoints1,image2,keypoints2,goodMatches,img_matches2); imshow("精匹配",img_matches2); cv::waitKey(00); }
SURF特徵提取的整個程式碼都在上面了,可當我把這個函式在我已有的工程中呼叫的時候,出現了一下錯誤
經百度說出現這種錯誤是記憶體問題,要麼就是記憶體木有釋放,要麼就是兩個指標指向同一個記憶體,一個指標把它釋放掉了等等,於是我在程式碼裡面找了很久,改了許多遍 也沒有解決,最後我發現我把程式碼中的vector
std::vector<cv::KeyPoint> keypoints1,keypoints2; cv::Mat descriptors1,descriptors2; std::vector<cv::DMatch> matches;//匹配結果 std::vector<cv::DMatch> goodMatches;
從函式中拿出來,作為全域性變數,問題盡然解決了,其實我都沒想明白這是什麼原因。vector裡面的記憶體不是不需要手動釋放的嗎,話說當其在函式裡面作為區域性變數的時候我也嘗試過釋放它,先是clear,後來發現clear不能釋放其記憶體,於是我按照網上說的用swap來手動釋放,可是最終還是沒用。最後誤打誤撞的,把它作為全域性變數,問題才得以解決,不過解決了就好。
在debug底下程式已經可以運行了,全都通過了,可接下來,我在release底下又遇到錯誤了,錯誤型別如下:
網上說這種我是新增opencv庫的時候新增錯了,我仔細看了我的additional dependencies的新增,在release底下我確實沒帶d啊,可怎麼就是出現了這種錯誤呢,要是是程式有問題,那怎麼debug底下可以執行呢,我很納悶,嘗試了很多方法。最後抱著試試的態度,乾脆把release和debug底下都添加了帶d的庫檔案,奇葩的是問題盡然結局了。對於這我只能表示相當無語啊!