-
Notifications
You must be signed in to change notification settings - Fork 0
/
coins_toolbox.cpp
347 lines (298 loc) · 11 KB
/
coins_toolbox.cpp
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//
// Copyright (c) 2019, Nicolò Bargellesi
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
#include <stdio.h>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/ccalib.hpp>
#include "coins_toolbox.hpp"
using namespace std;
using namespace cv;
// unknown value constructor
Coin::Coin(Mat coin_img) {
coin_image = coin_img;
}
// known value constructor
Coin::Coin(Mat coin_img, float coin_val) {
coin_image = coin_img;
coin_value = coin_val;
}
// get/set methods
cv::Mat Coin::getImage(){
return coin_image;
}
float Coin::getValue(){
return coin_value;
}
cv::Mat Coin::getDescriptor(){
return descriptor;
}
vector<KeyPoint> Coin::getKeypoints(){
return keypoints;
}
void Coin::setValue(float val){
coin_value = val;
}
// detects 1 and 2 Euro coins via HSV Saturation color matching
bool Coin::colorMatchEuro(Coin reference, int colorThreshold){
Mat color, colorChannels[3], ref_color, ref_colorChannels[3];
cvtColor(this->coin_image, color, COLOR_BGR2HSV); // color conversion
cvtColor(reference.getImage(), ref_color, COLOR_BGR2HSV); // color conversion
split(color, colorChannels); // channels division
split(ref_color, ref_colorChannels); // channels division
// Match sizes
resize(ref_colorChannels[1], ref_colorChannels[1], Size(color.size().width, color.size().height));
// binary threshold the Saturation channel
threshold(colorChannels[1], colorChannels[1], 0, 255, THRESH_OTSU); // THRESH_BINARY (40)
threshold(ref_colorChannels[1], ref_colorChannels[1], 0, 255, THRESH_OTSU); // THRESH_BINARY (50)
/*
namedWindow("test");
imshow("test", ref_colorChannels[1]);
cv::waitKey(0);
*/
// XOR
Mat sub;
bitwise_xor(colorChannels[1], ref_colorChannels[1], sub);
/*
cout << "\n" << mean(sub)[0];
namedWindow("test");
imshow("test", sub);
cv::waitKey(0);
*/
if (mean(sub)[0] < colorThreshold)
return 1; // match
else
return 0; // NO match
}
// detects copper coins via Lab a-component color matching
bool Coin::colorMatchCent(int colorThreshold){
Mat color, colorChannels[3], ref_color, ref_colorChannels[3];
cvtColor(this->coin_image, color, COLOR_BGR2Lab); // color conversion
split(color, colorChannels); // channels division
/*
namedWindow("test");
imshow("test", colorChannels[1]);
cv::waitKey(0);
*/
// binary threshold the a-component channel
threshold(colorChannels[1], colorChannels[1], 135, 255, THRESH_BINARY);
/*
cout << "\n" << mean(colorChannels[1])[0];
namedWindow("test");
imshow("test", colorChannels[1]);
cv::waitKey(0);
*/
if (mean(colorChannels[1])[0] > colorThreshold)
return 1;
else
return 0;
}
// extracts ORB features from coin image
void Coin::ORBfeatures(FParams feat_params) {
// extract desired parameters
int nfeatures = feat_params.nfeatures;
float scaleFactor = feat_params.scaleFactor;
int nlevels = feat_params.nlevels;
int edgeThreshold = feat_params.edgeThreshold;
int firstLevel = feat_params.firstLevel;
int WTA_K = feat_params.WTA_K;
int patchSize = feat_params.patchSize;
int fastThreshold = feat_params.fastThreshold;
vector<KeyPoint> keys;
Mat desc;
Mat detect_region = coin_image;
Ptr<ORB> detector = ORB::create(nfeatures, scaleFactor, nlevels, edgeThreshold, firstLevel, WTA_K, ORB::HARRIS_SCORE, patchSize, fastThreshold);
// mask the center (70% radius)
Mat mask = Mat::zeros(coin_image.size(), CV_8U);
int c = (coin_image.cols/2);
int r = (coin_image.cols/2)*70/100;
circle(mask, Point(c,c), r, Scalar(255), -1);
detector->detectAndCompute(detect_region, mask, keys, desc, false);
// Show detected features
/*
Mat output_img;
drawKeypoints(coin_image, keys, output_img, cv::Scalar::all(-1),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imshow("orb_mwe", output_img);
waitKey(0);
*/
//
keypoints = keys;
descriptor = desc;
}
// extracts SIFT features from coin image
void Coin::SIFTfeatures(FParams feat_params) {
// extract desired parameters
int nfeatures = feat_params.nfeatures;
int nOctaveLayers = feat_params.nOctaveLayers;
double contrastThreshold = feat_params.contrastThreshold;
double edgeThreshold = feat_params.edgeThreshold;
double sigma = feat_params.sigma;
vector<KeyPoint> keys;
Mat desc;
Mat detect_region = coin_image;
Ptr<cv::xfeatures2d::SIFT> detector = cv::xfeatures2d::SIFT::create(nfeatures,nOctaveLayers,contrastThreshold,edgeThreshold,sigma);
// mask the center (70% radius)
Mat mask = Mat::zeros(coin_image.size(), CV_8U);
int c = (coin_image.cols/2);
int r = (coin_image.cols/2)*70/100;
circle(mask, Point(c,c), r, Scalar(255), -1);
detector->detectAndCompute(detect_region, mask, keys, desc, false);
// Show detected features
/*
Mat output_img;
drawKeypoints(coin_image, keys, output_img, cv::Scalar::all(-1),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imshow("orb_mwe", output_img);
waitKey(0);
*/
//
keypoints = keys;
descriptor = desc;
}
// extracts SURF features from coin image
void Coin::SURFfeatures(FParams feat_params) {
// extract desired parameters
double hessianThreshold = feat_params.hessianThreshold;
int nOctaves = feat_params.nOctaves;
int nOctaveLayers = feat_params.nOctaveLayers;
bool extended = feat_params.extended;
bool upright = feat_params.upright;
vector<KeyPoint> keys;
Mat desc;
Mat detect_region = coin_image;
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create(hessianThreshold,nOctaves,nOctaveLayers,extended,upright);
// mask the center (70% radius)
Mat mask = Mat::zeros(coin_image.size(), CV_8U);
int c = (coin_image.cols/2);
int r = (coin_image.cols/2)*70/100;
circle(mask, Point(c,c), r, Scalar(255), -1);
detector->detectAndCompute(detect_region, mask, keys, desc, false);
// Show detected features
/*
Mat output_img;
drawKeypoints(coin_image, keys, output_img, cv::Scalar::all(-1),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imshow("orb_mwe", output_img);
waitKey(0);
*/
//
keypoints = keys;
descriptor = desc;
}
// computes matches between the features extracted from the coin and a reference coin
long Coin::patternMatch(Coin reference, int max_distance, int RANSAC_th, string feat_type) {
vector<DMatch> matches, ref_matches, final_matches;
Ptr<BFMatcher> matcher;
// select the correct distance
if(feat_type.compare("ORB")==0){
matcher = BFMatcher::create(NORM_HAMMING, true);
}
else {
matcher = BFMatcher::create(NORM_L2, true);
}
// find and refine matches
matcher->match(reference.getDescriptor(), this->descriptor, matches);
for (int j=0; j < matches.size(); j++) {
if (abs(matches[j].distance) <= max_distance){
ref_matches.push_back(matches[j]);
}
}
// Show detected matches
/*
Mat img_matches;
drawMatches(reference.getImage(), reference.getKeypoints(), this->coin_image, this->keypoints,
ref_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>()); //DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS
imshow( "Matches", img_matches );
waitKey(0);
*/
//
if(ref_matches.size()>0) { // if matches are detected
// Localize the objects
vector<Point2f> obj, scene;
Mat mask;
for(int i = 0; i < ref_matches.size(); i++ )
{
// Get the keypoints from the matches
obj.push_back(reference.getKeypoints()[ref_matches[i].queryIdx].pt);
scene.push_back(keypoints[ref_matches[i].trainIdx].pt);
}
// Refine the matches through RANSAC
Mat H = findHomography(obj, scene, RANSAC, RANSAC_th, mask);
for(int i = 0; i < ref_matches.size(); i++ )
{
if((unsigned int)mask.at<uchar>(i)) {
final_matches.push_back(ref_matches[i]);
}
}
// Show detected matches
/*
//cout << "\n" << ref_matches.size() << " - " << ref_obj.size();
drawMatches(reference.getImage(), reference.getKeypoints(), this->coin_image, this->keypoints,
final_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>()); //DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS
imshow( "Matches", img_matches );
waitKey(0);
*/
//
// Return # of matches
return final_matches.size(); // # of matches
}
else {
return 0;
}
}
// guesses the value of the coin
float Coin::guessValue(vector<Coin> dataset, int max_distance, int RANSAC_th, long uncertainty_th, int color_threshold, FParams feat_params) {
// COLOR MATCH (for 1 and 2 Euros)
for(int i=0; i<2; i++){
if(this->colorMatchEuro(dataset[i], color_threshold)){
return dataset[i].getValue();
}
}
// PATTERN MATCH (for others)
string feat_type = feat_params.type;
if(feat_type.compare("ORB")==0) {
// Update to match dataset images size
feat_params.edgeThreshold = this->coin_image.rows*feat_params.edgeThreshold/600;
feat_params.patchSize = this->coin_image.rows*feat_params.patchSize/600;
this->ORBfeatures(feat_params);
} else if (feat_type.compare("SIFT")==0) {
this->SIFTfeatures(feat_params);
} else if (feat_type.compare("SURF")==0) {
this->SURFfeatures(feat_params);
} else {
std::cerr << feat_type << " feature type NOT FOUND (it should be ORB / SIFT / SURF). \n";
throw runtime_error("Error extracting features");
}
// COLOR MATCH (for cents)
long max_score = 0;
float guess = -1;
if(this->colorMatchCent(color_threshold)){ // if copper
// Only 1,2,5 cents check
for(int i=5; i<dataset.size(); i++){
long res = this->patternMatch(dataset[i], max_distance, RANSAC_th, feat_type);
if( res > max_score && res > uncertainty_th) {
max_score = res;
guess = dataset[i].getValue();
}
}
return guess;
}
else {
// Only 10,20,50 cents check
for(int i=2; i<5; i++){
long res = this->patternMatch(dataset[i], max_distance, RANSAC_th, feat_type);
if( res > max_score && res > uncertainty_th) {
max_score = res;
guess = dataset[i].getValue();
}
}
return guess;
}
}