Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 78 additions & 1 deletion src/phg/matching/descriptor_matcher.cpp
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
#include "descriptor_matcher.h"

#include <algorithm>
#include <vector>

#include <opencv2/flann/miniflann.hpp>
#include "flann_factory.h"

void phg::DescriptorMatcher::filterMatchesRatioTest(const std::vector<std::vector<cv::DMatch>> &matches,
std::vector<cv::DMatch> &filtered_matches)
{
filtered_matches.clear();
filtered_matches.reserve(matches.size());

const float ratio = 0.75f;

for (const std::vector<cv::DMatch>& knn_matches : matches) {
if (knn_matches.size() < 2) {
continue;
}

throw std::runtime_error("not implemented yet");
const cv::DMatch& best = knn_matches[0];
const cv::DMatch& second_best = knn_matches[1];

if (best.distance < ratio * second_best.distance) {
filtered_matches.push_back(best);
}
}
}


Expand All @@ -35,6 +52,7 @@ void phg::DescriptorMatcher::filterMatchesClusters(const std::vector<cv::DMatch>
points_query.at<cv::Point2f>(i) = keypoints_query[matches[i].queryIdx].pt;
points_train.at<cv::Point2f>(i) = keypoints_train[matches[i].trainIdx].pt;
}

//
// // размерность всего 2, так что точное KD-дерево
// std::shared_ptr<cv::flann::IndexParams> index_params = flannKdTreeIndexParams(TODO);
Expand Down Expand Up @@ -73,4 +91,63 @@ void phg::DescriptorMatcher::filterMatchesClusters(const std::vector<cv::DMatch>
//
// метч остается, если левое и правое множества первых total_neighbors соседей в радиусах поиска(radius2_query, radius2_train) имеют как минимум consistent_matches общих элементов
// // TODO заполнить filtered_matches

std::shared_ptr<cv::flann::IndexParams> index_params = flannKdTreeIndexParams(1);
std::shared_ptr<cv::flann::SearchParams> search_params = flannKsTreeSearchParams(64);

std::shared_ptr<cv::flann::Index> index_query = flannKdTreeIndex(points_query, index_params);
std::shared_ptr<cv::flann::Index> index_train = flannKdTreeIndex(points_train, index_params);

cv::Mat indices_query(n_matches, total_neighbours, CV_32SC1);
cv::Mat distances2_query(n_matches, total_neighbours, CV_32FC1);
cv::Mat indices_train(n_matches, total_neighbours, CV_32SC1);
cv::Mat distances2_train(n_matches, total_neighbours, CV_32FC1);

index_query->knnSearch(points_query, indices_query, distances2_query, (int)total_neighbours, *search_params);
index_train->knnSearch(points_train, indices_train, distances2_train, (int)total_neighbours, *search_params);

float radius2_query, radius2_train;
{
std::vector<double> max_dists2_query(n_matches);
std::vector<double> max_dists2_train(n_matches);
for (int i = 0; i < n_matches; ++i) {
max_dists2_query[i] = distances2_query.at<float>(i, (int)total_neighbours - 1);
max_dists2_train[i] = distances2_train.at<float>(i, (int)total_neighbours - 1);
}

int median_pos = n_matches / 2;
std::nth_element(max_dists2_query.begin(), max_dists2_query.begin() + median_pos, max_dists2_query.end());
std::nth_element(max_dists2_train.begin(), max_dists2_train.begin() + median_pos, max_dists2_train.end());

radius2_query = max_dists2_query[median_pos] * radius_limit_scale * radius_limit_scale;
radius2_train = max_dists2_train[median_pos] * radius_limit_scale * radius_limit_scale;
}

filtered_matches.reserve(matches.size());

std::vector<char> neighbour_in_query(n_matches, 0);
for (int i = 0; i < n_matches; ++i) {
std::fill(neighbour_in_query.begin(), neighbour_in_query.end(), 0);

for (size_t j = 0; j < total_neighbours; ++j) {
int idx = indices_query.at<int>(i, (int)j);
float dist2 = distances2_query.at<float>(i, (int)j);
if (idx >= 0 && dist2 <= radius2_query) {
neighbour_in_query[idx] = 1;
}
}

int consistent_count = 0;
for (size_t j = 0; j < total_neighbours; ++j) {
int idx = indices_train.at<int>(i, (int)j);
float dist2 = distances2_train.at<float>(i, (int)j);
if (idx >= 0 && dist2 <= radius2_train && neighbour_in_query[idx]) {
++consistent_count;
}
}

if (consistent_count >= (int)consistent_matches) {
filtered_matches.push_back(matches[i]);
}
}
}
39 changes: 36 additions & 3 deletions src/phg/matching/flann_matcher.cpp
Original file line number Diff line number Diff line change
@@ -1,21 +1,54 @@
#include <iostream>
#include <cmath>
#include "flann_matcher.h"
#include "flann_factory.h"


phg::FlannMatcher::FlannMatcher()
{
// параметры для приближенного поиска
// index_params = flannKdTreeIndexParams(TODO);
// search_params = flannKsTreeSearchParams(TODO);
index_params = flannKdTreeIndexParams(4);
search_params = flannKsTreeSearchParams(32);
}

void phg::FlannMatcher::train(const cv::Mat &train_desc)
{
index_params = flannKdTreeIndexParams(4);
search_params = flannKsTreeSearchParams(32);

flann_index = flannKdTreeIndex(train_desc, index_params);
}

void phg::FlannMatcher::knnMatch(const cv::Mat &query_desc, std::vector<std::vector<cv::DMatch>> &matches, int k) const
{
throw std::runtime_error("not implemented yet");
matches.clear();
matches.resize(query_desc.rows);

if (query_desc.rows == 0) {
return;
}

cv::Mat indices;
cv::Mat distances;
flann_index->knnSearch(query_desc, indices, distances, k);

for (int qi = 0; qi < query_desc.rows; ++qi) {
std::vector<cv::DMatch>& dst = matches[qi];
dst.clear();
dst.reserve(k);

for (int j = 0; j < k; ++j) {
int train_idx = indices.at<int>(qi, j);
if (train_idx < 0) {
continue;
}

cv::DMatch match;
match.distance = std::sqrt(distances.at<float>(qi, j));
match.imgIdx = 0;
match.queryIdx = qi;
match.trainIdx = train_idx;
dst.push_back(match);
}
}
}
120 changes: 66 additions & 54 deletions src/phg/sfm/homography.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ namespace {
{
std::vector<std::vector<double>> A;
std::vector<double> H;
A.reserve(8);

double xs0[4] = {l0.x, l1.x, l2.x, l3.x};
double xs1[4] = {r0.x, r1.x, r2.x, r3.x};
Expand All @@ -84,8 +85,9 @@ namespace {
double w1 = ws1[i];

// 8 elements of matrix + free term as needed by gauss routine
// A.push_back({TODO});
// A.push_back({TODO});
(void)w1;
A.push_back({x0, y0, w0, 0.0, 0.0, 0.0, -x0 * x1, -y0 * x1, x1 * w0});
A.push_back({0.0, 0.0, 0.0, x0, y0, w0, -x0 * y1, -y0 * y1, y1 * w0});
}

int res = gauss(A, H);
Expand Down Expand Up @@ -168,57 +170,60 @@ namespace {
// * (простое описание для понимания)
// * [3] http://ikrisoft.blogspot.com/2015/01/ransac-with-contrario-approach.html

// const int n_matches = points_lhs.size();
//
// // https://en.wikipedia.org/wiki/Random_sample_consensus#Parameters
// const int n_trials = TODO;
//
// const int n_samples = TODO;
// uint64_t seed = 1;
// const double reprojection_error_threshold_px = 2;
//
// int best_support = 0;
// cv::Mat best_H;
//
// std::vector<int> sample;
// for (int i_trial = 0; i_trial < n_trials; ++i_trial) {
// randomSample(sample, n_matches, n_samples, &seed);
//
// cv::Mat H = estimateHomography4Points(points_lhs[sample[0]], points_lhs[sample[1]], points_lhs[sample[2]], points_lhs[sample[3]],
// points_rhs[sample[0]], points_rhs[sample[1]], points_rhs[sample[2]], points_rhs[sample[3]]);
//
// int support = 0;
// for (int i_point = 0; i_point < n_matches; ++i_point) {
// try {
// cv::Point2d proj = phg::transformPoint(points_lhs[i_point], H);
// if (cv::norm(proj - cv::Point2d(points_rhs[i_point])) < reprojection_error_threshold_px) {
// ++support;
// }
// } catch (const std::exception &e)
// {
// std::cerr << e.what() << std::endl;
// }
// }
//
// if (support > best_support) {
// best_support = support;
// best_H = H;
//
// std::cout << "estimateHomographyRANSAC : support: " << best_support << "/" << n_matches << std::endl;
//
// if (best_support == n_matches) {
// break;
// }
// }
// }
//
// std::cout << "estimateHomographyRANSAC : best support: " << best_support << "/" << n_matches << std::endl;
//
// if (best_support == 0) {
// throw std::runtime_error("estimateHomographyRANSAC : failed to estimate homography");
// }
//
// return best_H;
const int n_matches = points_lhs.size();

// https://en.wikipedia.org/wiki/Random_sample_consensus#Parameters
const int n_trials = 1000;

const int n_samples = 4;
uint64_t seed = 1;
const double reprojection_error_threshold_px = 2.0;

int best_support = 0;
cv::Mat best_H;

std::vector<int> sample;
for (int i_trial = 0; i_trial < n_trials; ++i_trial) {
randomSample(sample, n_matches, n_samples, &seed);

cv::Mat H;
try {
H = estimateHomography4Points(points_lhs[sample[0]], points_lhs[sample[1]], points_lhs[sample[2]], points_lhs[sample[3]],
points_rhs[sample[0]], points_rhs[sample[1]], points_rhs[sample[2]], points_rhs[sample[3]]);
} catch (const std::exception &) {
continue;
}

int support = 0;
for (int i_point = 0; i_point < n_matches; ++i_point) {
try {
cv::Point2d proj = phg::transformPoint(points_lhs[i_point], H);
if (cv::norm(proj - cv::Point2d(points_rhs[i_point])) < reprojection_error_threshold_px) {
++support;
}
} catch (const std::exception &) {
}
}

if (support > best_support) {
best_support = support;
best_H = H;

std::cout << "estimateHomographyRANSAC : support: " << best_support << "/" << n_matches << std::endl;

if (best_support == n_matches) {
break;
}
}
}

std::cout << "estimateHomographyRANSAC : best support: " << best_support << "/" << n_matches << std::endl;

if (best_support == 0) {
throw std::runtime_error("estimateHomographyRANSAC : failed to estimate homography");
}

return best_H;
}

}
Expand All @@ -238,7 +243,14 @@ cv::Mat phg::findHomographyCV(const std::vector<cv::Point2f> &points_lhs, const
// таким преобразованием внутри занимается функции cv::perspectiveTransform и cv::warpPerspective
cv::Point2d phg::transformPoint(const cv::Point2d &pt, const cv::Mat &T)
{
throw std::runtime_error("not implemented yet");
double x = pt.x;
double y = pt.y;

double tx = T.at<double>(0, 0) * x + T.at<double>(0, 1) * y + T.at<double>(0, 2);
double ty = T.at<double>(1, 0) * x + T.at<double>(1, 1) * y + T.at<double>(1, 2);
double tw = T.at<double>(2, 0) * x + T.at<double>(2, 1) * y + T.at<double>(2, 2);

return cv::Point2d(tx / tw, ty / tw);
}

cv::Point2d phg::transformPointCV(const cv::Point2d &pt, const cv::Mat &T) {
Expand Down
40 changes: 39 additions & 1 deletion src/phg/sfm/panorama_stitcher.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include <libutils/bbox2.h>
#include <iostream>
#include <vector>

/*
* imgs - список картинок
Expand All @@ -23,7 +24,44 @@ cv::Mat phg::stitchPanorama(const std::vector<cv::Mat> &imgs,
{
// здесь надо посчитать вектор Hs
// при этом можно обойтись n_images - 1 вызовами функтора homography_builder
throw std::runtime_error("not implemented yet");
std::vector<cv::Mat> edge_H(n_images);
std::vector<char> edge_ready(n_images, 0);
std::vector<char> H_ready(n_images, 0);

for (int i = 0; i < n_images; ++i) {
if (parent[i] == -1) {
Hs[i] = cv::Mat::eye(3, 3, CV_64FC1);
H_ready[i] = 1;
}
}

for (int i = 0; i < n_images; ++i) {
if (H_ready[i]) {
continue;
}

std::vector<int> chain;
int cur = i;
while (!H_ready[cur]) {
chain.push_back(cur);

int p = parent[cur];

if (!edge_ready[cur]) {
edge_H[cur] = homography_builder(imgs[cur], imgs[p]);
edge_ready[cur] = 1;
}

cur = p;
}

for (int k = (int)chain.size() - 1; k >= 0; --k) {
int v = chain[k];
int p = parent[v];
Hs[v] = Hs[p] * edge_H[v];
H_ready[v] = 1;
}
}
}

bbox2<double, cv::Point2d> bbox;
Expand Down
Loading
Loading