summaryrefslogtreecommitdiff
path: root/mv_image/image/src/Features/FeatureMatcher.cpp
blob: fce7716a73cc43ded7d1a873ef07fbab0da74c54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
/**
 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Features/FeatureMatcher.h"

#include "ImageMathUtil.h"

#include <opencv2/calib3d/calib3d_c.h>
#include <opencv2/core.hpp>

namespace MediaVision
{
namespace Image
{
// LCOV_EXCL_START
namespace
{
float computeLinearSupportElement(const std::vector<cv::DMatch> &examples, int requiredNumber, int leftLimit,
								  int rightLimit)
{
	int sizeOfExamples = rightLimit - leftLimit + 1;

	if (sizeOfExamples <= 1)
		return examples[leftLimit].distance;

	float minValue = examples[leftLimit].distance;
	float maxValue = examples[leftLimit].distance;

	/* Finding the maximum and minimum values */
	for (int i = leftLimit + 1; i <= rightLimit; ++i) {
		if (minValue > examples[i].distance)
			minValue = examples[i].distance;
		else if (maxValue < examples[i].distance)
			maxValue = examples[i].distance;
	}

	/* Linear approximation. f(x) = k*x + b */
	/* f(sizeOfExamples) = maxValue; f(1) = minValue; */
	const float b = (maxValue - minValue * sizeOfExamples) / (1 - sizeOfExamples);
	const float k = minValue - b;

	/* Calculation of the support element */
	return k * requiredNumber + b;
}

size_t matchesSelection(std::vector<cv::DMatch> &examples, size_t filterAmount, size_t allowableError)
{
	size_t sizeOfExamples = examples.size();

	if ((filterAmount + allowableError) > sizeOfExamples)
		return sizeOfExamples;

	int startLeftLimit = 0;
	int startRightLimit = sizeOfExamples - 1;

	int leftLimit = startLeftLimit;
	int rightLimit = startRightLimit;

	int requiredNumber = filterAmount;

	float supportElement = 0.f;

	while (true) {
		if (leftLimit >= rightLimit) {
			if (leftLimit < (requiredNumber - static_cast<int>(allowableError)))
				leftLimit = requiredNumber + static_cast<int>(allowableError);

			break;
		}

		supportElement = computeLinearSupportElement(examples, requiredNumber, leftLimit, rightLimit);

		/* Iteration similar quicksort */
		while (true) {
			/* Search the leftmost element which have
			 * bigger confidence than support element */
			while (examples[leftLimit].distance <= supportElement && leftLimit < startRightLimit)
				++leftLimit;

			/* Search the rightmost element which have smaller
			 * confidence than support element */
			while (examples[rightLimit].distance >= supportElement && rightLimit >= startLeftLimit)
				--rightLimit;

			if (leftLimit >= rightLimit)
				break;

			/* Swap */
			std::swap(examples[leftLimit], examples[rightLimit]);
		}
		if (std::abs(static_cast<int>(filterAmount - leftLimit)) <= static_cast<int>(allowableError))
			break;
		if (static_cast<int>(filterAmount) > leftLimit) {
			requiredNumber -= leftLimit - startLeftLimit;

			rightLimit = startRightLimit;
			startLeftLimit = leftLimit;
		} else {
			leftLimit = startLeftLimit;
			startRightLimit = rightLimit;
		}
	}

	return (size_t) leftLimit;
}

} /* anonymous namespace */

FeatureMatcher::FeatureMatcher(float affectingPart, float tolerantError, size_t minimumMatchesNumber)
{
	setAffectingPart(affectingPart);
	setTolerantError(tolerantError);
	setMinimumMatchesNumber(minimumMatchesNumber);
}

FeatureMatcher::MatchError FeatureMatcher::match(const FeaturePack &from, const FeaturePack &to,
												 cv::Mat &homophraphyMatrix) const
{
	if (MinimumNumberOfFeatures > from.__objectKeypoints.size())
		return InvalidFeaturePackFrom;

	if (MinimumNumberOfFeatures > to.__objectKeypoints.size())
		return InvalidFeaturePackTo;

	if (from.__descriptorsType != to.__descriptorsType)
		return DisparateTypes;

	std::vector<cv::DMatch> matches;

	__matcher.match(from.__objectDescriptors, to.__objectDescriptors, matches);

	size_t matchesNumber = matches.size();

	if (MinimumNumberOfFeatures > matchesNumber)
		return MatchesNotFound;

	size_t requiredMatchesNumber = __affectingPart * matchesNumber;
	size_t allowableMatchesNumberError = __tolerantError * requiredMatchesNumber;

	if (matchesNumber - allowableMatchesNumberError > MinimumNumberOfFeatures &&
		requiredMatchesNumber + allowableMatchesNumberError < matchesNumber) {
		if (requiredMatchesNumber - allowableMatchesNumberError < __minimumMatchesNumber) {
			if (requiredMatchesNumber + allowableMatchesNumberError > __minimumMatchesNumber) {
				requiredMatchesNumber =
						(requiredMatchesNumber + __minimumMatchesNumber + allowableMatchesNumberError) / 2;

				allowableMatchesNumberError =
						requiredMatchesNumber - __minimumMatchesNumber + allowableMatchesNumberError;
			} else {
				const size_t minimalAllowableMatchesNumberError = 2u;

				requiredMatchesNumber = minimalAllowableMatchesNumberError + __minimumMatchesNumber;

				allowableMatchesNumberError = minimalAllowableMatchesNumberError;
			}
		}

		const size_t filterAmount = matchesSelection(matches, requiredMatchesNumber, allowableMatchesNumberError);

		if (filterAmount >= MinimumNumberOfFeatures)
			matches.resize(filterAmount);

		matchesNumber = matches.size();
	}

	std::vector<cv::Point2f> objectPoints(matchesNumber);
	std::vector<cv::Point2f> scenePoints(matchesNumber);

	for (size_t matchIdx = 0; matchIdx < matchesNumber; ++matchIdx) {
		objectPoints[matchIdx] = from.__objectKeypoints[matches[matchIdx].queryIdx].pt;

		scenePoints[matchIdx] = to.__objectKeypoints[matches[matchIdx].trainIdx].pt;
	}

	homophraphyMatrix = cv::findHomography(objectPoints, scenePoints, CV_RANSAC);

	return Success;
}

float FeatureMatcher::getAffectingPart() const
{
	return __affectingPart;
}

void FeatureMatcher::setAffectingPart(float affectingPart)
{
	__affectingPart = std::max(0.f, std::min(1.f, affectingPart));
}

float FeatureMatcher::getTolerantError() const
{
	return __tolerantError;
}

void FeatureMatcher::setTolerantError(float tolerantError)
{
	__tolerantError = std::max(0.f, std::min(1.f, tolerantError));
}

size_t FeatureMatcher::getMinimumMatchesNumber() const
{
	return __minimumMatchesNumber;
}

void FeatureMatcher::setMinimumMatchesNumber(size_t minimumMatchesNumber)
{
	__minimumMatchesNumber = minimumMatchesNumber;
}
// LCOV_EXCL_STOP
} /* Image */
} /* MediaVision */