opencvを始めたばかりで他のサイトのコードを真似て作りました。
問題は画像Aと画像N(あるフォルダ内の画像A以外の画像)の一致度(率)を求めるコードです。
一般的にはC++のほうが早いと思いますがなぜかpythonに実行速度で劣ってしまっています。(C++:0.2秒程度,python 0.01~0.02秒程度)
detectAndCompute()
とDescriptorMatcher::match()
関数がその原因ということが今のところ分かっています。
できる限り高速化をしてみたものの、依然として遅い状況です。
また、以下のC++のコード(にデバッグ用のコードと一致度を求めるコードを入れたやつ)を実行すると0x00007FF80D73D759 で例外がスローされました (opencvtest.exe 内): Microsoft C++ の例外: 'anonymous namespace'::ExifParsingError (メモリの場所 0x000000467D3CE470)。
というエラーが出てきます。(実行に支障はないのですが気になるのでこれもわかる方はお願いします。)
なぜでしょうか。どなたかご回答お願いします。<(_ _)>
C++
1#pragma comment(lib,"opencv_world411d.lib") 2//#pragma comment(lib,"opencv_world411.lib") 3 4#include <opencv2/opencv.hpp> 5#include <iostream> 6#include <filesystem> 7#include <string> 8#include <vector> 9#include <map> 10const std::string TARGET_DIR = "C:\Users\"; 11 12#define TARGET_FILE "hoge.png" 13 14cv::BFMatcher bf(cv::NORM_HAMMING); 15int main() 16{ 17 cv::Mat targetimg = cv::imread(TARGET_DIR + TARGET_FILE, cv::IMREAD_GRAYSCALE); 18 cv::resize(targetimg, targetimg, cv::Size(200, 200)); 19 cv::Ptr<cv::Feature2D> detector = cv::AKAZE::create(); 20 std::vector<cv::KeyPoint> kp; 21 cv::Mat des; 22 detector->detectAndCompute(targetimg, cv::noArray(), kp, des);//特徴点の抽出 23 24 25 26 std::filesystem::directory_iterator files = std::filesystem::directory_iterator(TARGET_DIR); 27 std::vector<cv::KeyPoint> ckp; 28 cv::Mat cdes; 29 cv::Mat nowImg; 30 std::vector<cv::DMatch> matches; 31 std::size_t tmpsize; 32 33 auto nA = cv::noArray(); 34 for (auto file : files) { 35 36 if (file.path().filename() == TARGET_FILE || file.is_directory()) continue; 37 38 nowImg = cv::imread(file.path().string(), cv::IMREAD_GRAYSCALE); 39 cv::resize(nowImg, nowImg, cv::Size(200, 200)); 40 41 //ここから 42 detector->detectAndCompute(nowImg, nA, ckp, cdes); 43 44 bf.match(des, cdes, matches); 45 //ここまでが問題のコード 46 47 //一致度を求めるコード 48 49 } 50 return 0; 51}
python
1import cv2 2import smart_open.s3 3mydict={} 4 5TARGET_FILE = 'hoge.png' 6IMG_DIR = os.path.abspath("C:\Users\") 7IMG_SIZE = (200, 200) 8 9target_img_path = IMG_DIR +"\"+ TARGET_FILE 10target_img = imread(target_img_path, cv2.IMREAD_GRAYSCALE) 11target_img = cv2.resize(target_img, IMG_SIZE) 12 13bf = cv2.BFMatcher(cv2.NORM_HAMMING) 14# detector = cv2.ORB_create() 15detector = cv2.AKAZE_create() 16(target_kp, target_des) = detector.detectAndCompute(target_img, None) 17 18 19files = os.listdir(IMG_DIR) 20f=t.perf_counter() 21for file in files: 22 if file == '.DS_Store' or file == TARGET_FILE: 23 continue 24 25 comparing_img_path = IMG_DIR +"\"+ file 26 comparing_img = imread(comparing_img_path, cv2.IMREAD_GRAYSCALE) 27 comparing_img = cv2.resize(comparing_img, IMG_SIZE) 28 29 #ここから 30 (comparing_kp, comparing_des) = detector.detectAndCompute(comparing_img, None) 31 matches = bf.match(target_des, comparing_des) 32 #ここまでが問題のコード 33 34 #一致度を求めるコード

回答1件
あなたの回答
tips
プレビュー