Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/cpp/detect_mser.cpp
16337 views
1
#include <opencv2/core.hpp>
2
#include <opencv2/imgproc.hpp>
3
#include <opencv2/highgui.hpp>
4
#include <opencv2/features2d.hpp>
5
#include "opencv2/core/opengl.hpp"
6
7
#include <vector>
8
#include <map>
9
#include <iostream>
10
#include <iomanip>
11
#include <limits>
12
#include <stdint.h>
13
#ifdef HAVE_OPENGL
14
#ifdef _WIN32
15
#define WIN32_LEAN_AND_MEAN 1
16
#define NOMINMAX 1
17
#include <windows.h>
18
#endif
19
#if defined(_WIN64)
20
#include <windows.h>
21
#endif
22
23
#if defined(__APPLE__)
24
#include <OpenGL/gl.h>
25
#include <OpenGL/glu.h>
26
#else
27
#include <GL/gl.h>
28
#include <GL/glu.h>
29
#endif
30
#endif
31
32
33
using namespace std;
34
using namespace cv;
35
36
37
static void help()
38
{
39
cout << "\n This program demonstrates how to use MSER to detect extremal regions \n"
40
"Usage: \n"
41
" ./detect_mser <image1(without parameter a syntehtic image is used as default)>\n"
42
"Press esc key when image window is active to change descriptor parameter\n"
43
"Press 2, 8, 4, 6, +,- or 5 keys in openGL windows to change view or use mouse\n";
44
}
45
46
struct MSERParams
47
{
48
MSERParams(int _delta = 5, int _min_area = 60, int _max_area = 14400,
49
double _max_variation = 0.25, double _min_diversity = .2,
50
int _max_evolution = 200, double _area_threshold = 1.01,
51
double _min_margin = 0.003, int _edge_blur_size = 5)
52
{
53
delta = _delta;
54
minArea = _min_area;
55
maxArea = _max_area;
56
maxVariation = _max_variation;
57
minDiversity = _min_diversity;
58
maxEvolution = _max_evolution;
59
areaThreshold = _area_threshold;
60
minMargin = _min_margin;
61
edgeBlurSize = _edge_blur_size;
62
pass2Only = false;
63
}
64
65
int delta;
66
int minArea;
67
int maxArea;
68
double maxVariation;
69
double minDiversity;
70
bool pass2Only;
71
72
int maxEvolution;
73
double areaThreshold;
74
double minMargin;
75
int edgeBlurSize;
76
};
77
78
static String Legende(const MSERParams &pAct)
79
{
80
ostringstream ss;
81
ss << "Area[" << pAct.minArea << "," << pAct.maxArea << "] ";
82
ss << "del. [" << pAct.delta << "] ";
83
ss << "var. [" << pAct.maxVariation << "] ";
84
ss << "div. [" << (int)pAct.minDiversity << "] ";
85
ss << "pas. [" << (int)pAct.pass2Only << "] ";
86
ss << "RGb->evo. [" << pAct.maxEvolution << "] ";
87
ss << "are. [" << (int)pAct.areaThreshold << "] ";
88
ss << "mar. [" << (int)pAct.minMargin << "] ";
89
ss << "siz. [" << pAct.edgeBlurSize << "]";
90
91
return ss.str();
92
}
93
94
95
#ifdef HAVE_OPENGL
96
const int win_width = 800;
97
const int win_height = 640;
98
#endif
99
bool rotateEnable=true;
100
bool keyPressed=false;
101
102
Vec4f rotAxis(1,0,1,0);
103
Vec3f zoom(1,0,0);
104
105
float obsX = 0.f;
106
float obsY = 0.f;
107
float obsZ = -10.f;
108
float tx = 0.f;
109
float ty = 0.f;
110
111
float thetaObs = -1.570f;
112
float phiObs = 1.570f;
113
float rObs = 10.f;
114
115
int prevX = -1;
116
int prevY = -1;
117
int prevTheta = -1000;
118
int prevPhi = -1000;
119
120
#ifdef HAVE_OPENGL
121
struct DrawData
122
{
123
ogl::Arrays arr;
124
ogl::Texture2D tex;
125
ogl::Buffer indices;
126
};
127
128
129
static void draw(void* userdata)
130
{
131
DrawData* data = static_cast<DrawData*>(userdata);
132
glMatrixMode(GL_MODELVIEW);
133
glLoadIdentity();
134
gluLookAt(obsX, obsY, obsZ, 0, 0, .0, .0, 10.0, 0.0);
135
glTranslatef(tx,ty,0);
136
keyPressed = false;
137
ogl::render(data->arr, data->indices, ogl::TRIANGLES);
138
}
139
140
static void onMouse(int event, int x, int y, int flags, void*)
141
{
142
if (event == EVENT_RBUTTONDOWN)
143
{
144
prevX = x;
145
prevY = y;
146
}
147
if (event == EVENT_RBUTTONUP)
148
{
149
prevX = -1;
150
prevY = -1;
151
}
152
if (prevX != -1)
153
{
154
tx += float((x - prevX) / 100.0);
155
ty -= float((y - prevY) / 100.0);
156
prevX = x;
157
prevY = y;
158
}
159
if (event == EVENT_LBUTTONDOWN)
160
{
161
prevTheta = x;
162
prevPhi = y;
163
}
164
if (event == EVENT_LBUTTONUP)
165
{
166
prevTheta = -1000;
167
prevPhi = -1000;
168
}
169
if (prevTheta != -1000)
170
{
171
if (x - prevTheta<0)
172
{
173
thetaObs += 0.02f;
174
}
175
else if (x - prevTheta>0)
176
{
177
thetaObs -= 0.02f;
178
}
179
if (y - prevPhi<0)
180
{
181
phiObs -= 0.02f;
182
}
183
else if (y - prevPhi>0)
184
{
185
phiObs += 0.02f;
186
}
187
prevTheta = x;
188
prevPhi = y;
189
}
190
if (event==EVENT_MOUSEWHEEL)
191
{
192
if (getMouseWheelDelta(flags)>0)
193
rObs += 0.1f;
194
else
195
rObs -= 0.1f;
196
}
197
float pi = static_cast<float>(CV_PI);
198
if (thetaObs>pi)
199
{
200
thetaObs = -2 * pi + thetaObs;
201
}
202
if (thetaObs<-pi)
203
{
204
thetaObs = 2 * pi + thetaObs;
205
}
206
if (phiObs>pi / 2)
207
{
208
phiObs = pi / 2 - 0.0001f;
209
}
210
if (phiObs<-pi / 2)
211
{
212
phiObs = -pi / 2 + 0.00001f;
213
}
214
if (rObs<0)
215
{
216
rObs = 0;
217
}
218
219
}
220
#endif
221
222
#ifdef HAVE_OPENGL
223
static void DrawOpenGLMSER(Mat img, Mat result)
224
{
225
Mat imgGray;
226
if (img.type() != CV_8UC1)
227
cvtColor(img, imgGray, COLOR_BGR2GRAY);
228
else
229
imgGray = img;
230
231
namedWindow("OpenGL", WINDOW_OPENGL);
232
setMouseCallback("OpenGL", onMouse, NULL);
233
234
Mat_<Vec3f> vertex(1, img.cols*img.rows);
235
Mat_<Vec2f> texCoords(1, img.cols*img.rows);
236
for (int i = 0, nbPix = 0; i<img.rows; i++)
237
{
238
for (int j = 0; j<img.cols; j++, nbPix++)
239
{
240
float x = (j) / (float)img.cols;
241
float y = (i) / (float)img.rows;
242
vertex.at< Vec3f >(0, nbPix) = Vec3f(float(2 * (x - 0.5)), float(2 * (0.5 - y)), float(imgGray.at<uchar>(i, j) / 512.0));
243
texCoords.at< Vec2f>(0, nbPix) = Vec2f(x, y);
244
}
245
}
246
247
Mat_<int> indices(1, (img.rows - 1)*(6 * img.cols));
248
for (int i = 1, nbPix = 0; i<img.rows; i++)
249
{
250
for (int j = 1; j<img.cols; j++)
251
{
252
int c = i*img.cols + j;
253
indices.at<int>(0, nbPix++) = c;
254
indices.at<int>(0, nbPix++) = c - 1;
255
indices.at<int>(0, nbPix++) = c - img.cols - 1;
256
indices.at<int>(0, nbPix++) = c - img.cols - 1;
257
indices.at<int>(0, nbPix++) = c - img.cols;
258
indices.at<int>(0, nbPix++) = c;
259
}
260
}
261
262
DrawData *data = new DrawData;
263
264
data->arr.setVertexArray(vertex);
265
data->arr.setTexCoordArray(texCoords);
266
data->indices.copyFrom(indices);
267
data->tex.copyFrom(result);
268
269
glMatrixMode(GL_PROJECTION);
270
glLoadIdentity();
271
gluPerspective(45.0, (double)win_width / win_height, 0.0, 1000.0);
272
273
glMatrixMode(GL_MODELVIEW);
274
glLoadIdentity();
275
276
glEnable(GL_TEXTURE_2D);
277
data->tex.bind();
278
279
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
280
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
281
282
glDisable(GL_CULL_FACE);
283
setOpenGlDrawCallback("OpenGL", draw, data);
284
285
for (;;)
286
{
287
updateWindow("OpenGL");
288
char key = (char)waitKey(40);
289
if (key == 27)
290
break;
291
if (key == 0x20)
292
rotateEnable = !rotateEnable;
293
float pi = static_cast<float>(CV_PI);
294
295
switch (key) {
296
case '5':
297
obsX = 0, obsY = 0, obsZ = -10;
298
thetaObs = -pi/2, phiObs = pi/2, rObs = 10;
299
tx=0; ty=0;
300
break;
301
case '4':
302
thetaObs += 0.1f;
303
break;
304
case '6':
305
thetaObs -= 0.1f;
306
break;
307
case '2':
308
phiObs -= 0.1f;
309
break;
310
case '8':
311
phiObs += 0.1f;
312
break;
313
case '+':
314
rObs -= 0.1f;
315
break;
316
case '-':
317
rObs += 0.1f;
318
break;
319
}
320
321
if (thetaObs>pi)
322
{
323
thetaObs = -2 * pi + thetaObs;
324
}
325
if (thetaObs<-pi)
326
thetaObs = 2 * pi + thetaObs;
327
if (phiObs>pi / 2)
328
phiObs = pi / 2 - 0.0001f;
329
if (phiObs<-pi / 2)
330
phiObs = -pi / 2 + 0.00001f;
331
if (rObs<0)
332
rObs = 0;
333
obsX = rObs*cos(thetaObs)*cos(phiObs);
334
obsY = rObs*sin(thetaObs)*cos(phiObs);
335
obsZ = rObs*sin(phiObs);
336
}
337
setOpenGlDrawCallback("OpenGL", 0, 0);
338
destroyAllWindows();
339
}
340
#endif
341
342
// Add nested rectangles of different widths and colors to an image
343
static void addNestedRectangles(Mat &img, Point p0, int* width, int *color, int n) {
344
for (int i = 0; i<n; i++)
345
{
346
rectangle(img, Rect(p0, Size(width[i], width[i])), Scalar(color[i]), 1);
347
p0 += Point((width[i] - width[i + 1]) / 2, (width[i] - width[i + 1]) / 2);
348
floodFill(img, p0, Scalar(color[i]));
349
}
350
}
351
352
// Add nested circles of different widths and colors to an image
353
static void addNestedCircles(Mat &img, Point p0, int *width, int *color, int n) {
354
for (int i = 0; i<n; i++)
355
{
356
circle(img, p0, width[i] / 2, Scalar(color[i]), 1);
357
floodFill(img, p0, Scalar(color[i]));
358
}
359
}
360
361
static Mat MakeSyntheticImage()
362
{
363
const int fond = 0;
364
365
Mat img(800, 800, CV_8UC1);
366
img = Scalar(fond);
367
368
int width[] = { 390, 380, 300, 290, 280, 270, 260, 250, 210, 190, 150, 100, 80, 70 };
369
370
int color1[] = { 80, 180, 160, 140, 120, 100, 90, 110, 170, 150, 140, 100, 220 };
371
int color2[] = { 81, 181, 161, 141, 121, 101, 91, 111, 171, 151, 141, 101, 221 };
372
int color3[] = { 175, 75, 95, 115, 135, 155, 165, 145, 85, 105, 115, 155, 35 };
373
int color4[] = { 173, 73, 93, 113, 133, 153, 163, 143, 83, 103, 113, 153, 33 };
374
375
addNestedRectangles(img, Point(10, 10), width, color1, 13);
376
addNestedCircles(img, Point(200, 600), width, color2, 13);
377
378
addNestedRectangles(img, Point(410, 10), width, color3, 13);
379
addNestedCircles(img, Point(600, 600), width, color4, 13);
380
381
int histSize = 256;
382
float range[] = { 0, 256 };
383
const float* histRange[] = { range };
384
Mat hist;
385
386
// we compute the histogram
387
calcHist(&img, 1, 0, Mat(), hist, 1, &histSize, histRange, true, false);
388
389
cout << "****************Maximal region************************\n";
390
for (int i = 0; i < hist.rows; i++)
391
{
392
if (hist.at<float>(i, 0)!=0)
393
{
394
cout << "h" << setw(3) << left << i << "\t=\t" << hist.at<float>(i, 0) << "\n";
395
}
396
}
397
398
return img;
399
}
400
401
int main(int argc, char *argv[])
402
{
403
Mat imgOrig, img;
404
Size blurSize(5, 5);
405
cv::CommandLineParser parser(argc, argv, "{ help h | | }{ @input | | }");
406
if (parser.has("help"))
407
{
408
help();
409
return 0;
410
}
411
412
string input = parser.get<string>("@input");
413
if (!input.empty())
414
{
415
imgOrig = imread(input, IMREAD_GRAYSCALE);
416
blur(imgOrig, img, blurSize);
417
}
418
else
419
{
420
imgOrig = MakeSyntheticImage();
421
img = imgOrig;
422
}
423
424
// Descriptor array MSER
425
vector<String> typeDesc;
426
// Param array for MSER
427
vector<MSERParams> pMSER;
428
429
// Color palette
430
vector<Vec3b> palette;
431
for (int i = 0; i<=numeric_limits<uint16_t>::max(); i++)
432
palette.push_back(Vec3b((uchar)rand(), (uchar)rand(), (uchar)rand()));
433
434
help();
435
436
MSERParams params;
437
438
params.delta = 10;
439
params.minArea = 100;
440
params.maxArea = 5000;
441
params.maxVariation = 2;
442
params.minDiversity = 0;
443
params.pass2Only = true;
444
445
typeDesc.push_back("MSER");
446
pMSER.push_back(params);
447
448
params.pass2Only = false;
449
typeDesc.push_back("MSER");
450
pMSER.push_back(params);
451
452
params.delta = 100;
453
typeDesc.push_back("MSER");
454
pMSER.push_back(params);
455
456
vector<MSERParams>::iterator itMSER = pMSER.begin();
457
Ptr<Feature2D> b;
458
String label;
459
// Descriptor loop
460
vector<String>::iterator itDesc;
461
Mat result(img.rows, img.cols, CV_8UC3);
462
for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); ++itDesc)
463
{
464
vector<KeyPoint> keyImg1;
465
if (*itDesc == "MSER")
466
{
467
if (img.type() == CV_8UC3)
468
{
469
b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity, itMSER->maxEvolution,
470
itMSER->areaThreshold, itMSER->minMargin, itMSER->edgeBlurSize);
471
label = Legende(*itMSER);
472
++itMSER;
473
}
474
else
475
{
476
b = MSER::create(itMSER->delta, itMSER->minArea, itMSER->maxArea, itMSER->maxVariation, itMSER->minDiversity);
477
b.dynamicCast<MSER>()->setPass2Only(itMSER->pass2Only);
478
label = Legende(*itMSER);
479
++itMSER;
480
}
481
}
482
483
if (img.type()==CV_8UC3)
484
{
485
img.copyTo(result);
486
}
487
else
488
{
489
vector<Mat> plan;
490
plan.push_back(img);
491
plan.push_back(img);
492
plan.push_back(img);
493
merge(plan,result);
494
}
495
try
496
{
497
// We can detect regions using detectRegions method
498
vector<KeyPoint> keyImg;
499
vector<Rect> zone;
500
vector<vector <Point> > region;
501
Mat desc;
502
503
if (b.dynamicCast<MSER>().get())
504
{
505
Ptr<MSER> sbd = b.dynamicCast<MSER>();
506
sbd->detectRegions(img, region, zone);
507
//result = Scalar(0, 0, 0);
508
int nbPixelInMSER=0;
509
for (vector<vector <Point> >::iterator itr = region.begin(); itr != region.end(); ++itr)
510
{
511
for (vector <Point>::iterator itp = itr->begin(); itp != itr->end(); ++itp)
512
{
513
// all pixels belonging to region become blue
514
result.at<Vec3b>(itp->y, itp->x) = Vec3b(128, 0, 0);
515
nbPixelInMSER++;
516
}
517
}
518
cout << "Number of MSER region: " << region.size() << "; Number of pixels in all MSER region: " << nbPixelInMSER << "\n";
519
}
520
521
const string winName = *itDesc + label;
522
namedWindow(winName, WINDOW_AUTOSIZE);
523
imshow(winName, result);
524
imshow("Original", img);
525
}
526
catch (Exception& e)
527
{
528
cout << "Feature: " << *itDesc << "\n";
529
cout << e.msg << endl;
530
}
531
#ifdef HAVE_OPENGL
532
DrawOpenGLMSER(img, result);
533
#endif
534
waitKey();
535
}
536
return 0;
537
}
538
539