旅行好きなソフトエンジニアの備忘録

プログラミングや技術関連のメモを始めました

【OpenCV】 特徴点検出を行う

OpenCVの復習が必要になったのでメモしておきます。

// グレースケールで画像を読み込む
UMat source1;
imread("lenna.jpg", CV_LOAD_IMAGE_GRAYSCALE).copyTo(source1);
if (source1.empty())
{
    throw runtime_error("Failed to open image");
}
    
// 画像をコピーして回転させる
UMat source2 = source1.clone();
// 回転の中心
Point2f center = Point2f(static_cast<float>(source2.cols / 2),
                         static_cast<float>(source2.rows / 2));
// 回転角度
double angle_deg = 30.0;
// スケーリング係数
double scale = 1.0;
// アフィン変換行列の取得
UMat affine;
getRotationMatrix2D(center, angle_deg, scale).copyTo(affine);
// 内挿方法
int interpolationFlag = INTER_CUBIC;
// 画像の回転を行う
UMat rotated;
warpAffine(source2, rotated, affine, source2.size(), interpolationFlag);
source2 = rotated.clone();

// 特徴点検出器の作成
vector<KeyPoint> keyPoint1, keyPoint2;
Ptr<FeatureDetector> keyPointDetector = AKAZE::create();

// 特徴点を検出する
keyPointDetector->detect(source1, keyPoint1);
keyPointDetector->detect(source2, keyPoint2);

// 特徴量記述子の作成
Mat descriptor1, descriptor2; // ここをUMATで宣言するとextractor->computeでエラーとなった
Ptr<DescriptorExtractor> extractor = AKAZE::create();

// 特徴量の記述
extractor->compute(source1, keyPoint1, descriptor1);
extractor->compute(source2, keyPoint2, descriptor2);

// 特徴量のマッチングを行う(クロスチェック)
Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce");
vector<DMatch> forwardMatches;
matcher->match(descriptor1, descriptor2, forwardMatches);
vector<DMatch> backwardMatches;
matcher->match(descriptor2, descriptor1, backwardMatches);
vector<DMatch> matches;
for (int i = 0; i < forwardMatches.size(); ++i)
{
    DMatch forward = forwardMatches[i];
    DMatch backward = backwardMatches[forward.trainIdx];
    if (backward.trainIdx == forward.queryIdx)
    {
        matches.push_back(forward);
    }
}

// 結果を描画する
UMat destination;
drawMatches(source1, keyPoint1, source2, keyPoint2, matches, destination);

imshow("source1", source1);
imshow("source2", source2);
imshow("destination", destination);

f:id:ni4muraano:20170115145041j:plain:w150 f:id:ni4muraano:20170117180130j:plain:w150 f:id:ni4muraano:20170117180136j:plain:w300

さらに進化した画像処理ライブラリの定番 OpenCV 3基本プログラミング

さらに進化した画像処理ライブラリの定番 OpenCV 3基本プログラミング