gui.cpp
14.4 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#include <QApplication>
#include <QLabel>
#include <QElapsedTimer>
#include <QWaitCondition>
#include <QMutex>
#include <QMouseEvent>
#include <QPainter>
#include <opencv2/imgproc/imgproc.hpp>
#include "openbr_internal.h"
using namespace cv;
namespace br
{
QImage toQImage(const Mat &mat)
{
// Convert to 8U depth
Mat mat8u;
if (mat.depth() != CV_8U) {
double globalMin = std::numeric_limits<double>::max();
double globalMax = -std::numeric_limits<double>::max();
std::vector<Mat> mv;
split(mat, mv);
for (size_t i=0; i<mv.size(); i++) {
double min, max;
minMaxLoc(mv[i], &min, &max);
globalMin = std::min(globalMin, min);
globalMax = std::max(globalMax, max);
}
assert(globalMax >= globalMin);
double range = globalMax - globalMin;
if (range != 0) {
double scale = 255 / range;
convertScaleAbs(mat, mat8u, scale, -(globalMin * scale));
} else {
// Monochromatic
mat8u = Mat(mat.size(), CV_8UC1, Scalar((globalMin+globalMax)/2));
}
} else {
mat8u = mat;
}
// Convert to 3 channels
Mat mat8uc3;
if (mat8u.channels() == 4) cvtColor(mat8u, mat8uc3, CV_BGRA2RGB);
else if (mat8u.channels() == 3) cvtColor(mat8u, mat8uc3, CV_BGR2RGB);
else if (mat8u.channels() == 1) cvtColor(mat8u, mat8uc3, CV_GRAY2RGB);
return QImage(mat8uc3.data, mat8uc3.cols, mat8uc3.rows, 3*mat8uc3.cols, QImage::Format_RGB888).copy();
}
class DisplayWindow : public QLabel
{
Q_OBJECT
protected:
QMutex lock;
QWaitCondition wait;
QPixmap pixmap;
public:
DisplayWindow(QWidget * parent = NULL) : QLabel(parent)
{
QApplication::instance()->installEventFilter(this);
}
public slots:
void showImage(const QPixmap & input)
{
pixmap = input;
show();
setPixmap(pixmap);
setFixedSize(input.size());
}
bool eventFilter(QObject * obj, QEvent * event)
{
if (event->type() == QEvent::KeyPress)
{
event->accept();
wait.wakeAll();
return true;
} else {
return QObject::eventFilter(obj, event);
}
}
virtual QList<QPointF> waitForKey()
{
QMutexLocker locker(&lock);
wait.wait(&lock);
return QList<QPointF>();
}
};
class PointMarkingWindow : public DisplayWindow
{
bool eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress)
{
event->accept();
QMouseEvent *mouseEvent = (QMouseEvent*)event;
if (mouseEvent->button() == Qt::LeftButton) points.append(mouseEvent->pos());
else if (mouseEvent->button() == Qt::RightButton && !points.isEmpty()) points.removeLast();
QPixmap pixmapBuffer = pixmap;
QPainter painter(&pixmapBuffer);
painter.setBrush(Qt::red);
foreach(const QPointF &point, points) painter.drawEllipse(point, 4, 4);
setPixmap(pixmapBuffer);
return true;
} else {
return DisplayWindow::eventFilter(obj, event);
}
}
QList<QPointF> waitForKey()
{
points.clear();
DisplayWindow::waitForKey();
return points;
}
private:
QList<QPointF> points;
};
class PromptWindow : public DisplayWindow
{
bool eventFilter(QObject * obj, QEvent * event)
{
if (event->type() == QEvent::KeyPress)
{
event->accept();
QKeyEvent * key_event = dynamic_cast<QKeyEvent *> (event);
if (key_event == NULL) {
qDebug("failed to donwcast key event");
return true;
}
QString text = key_event->text();
text =text.toLower();
if (text == "y" || text == "n")
{
gotString = key_event->text();
wait.wakeAll();
}
else qDebug("Please answer y/n");
return true;
} else {
return QObject::eventFilter(obj, event);
}
}
public:
QString waitForKeyPress()
{
QMutexLocker locker(&lock);
wait.wait(&lock);
return gotString;
}
private:
QString gotString;
};
// I want a template class that doesn't look like a template class
class NominalCreation
{
public:
virtual ~NominalCreation() {}
virtual void creation()=0;
};
// Putting the template on a subclass means we can maintain a pointer that
// doesn't include T in its type.
template<typename T>
class ActualCreation : public NominalCreation
{
public:
T * basis;
void creation()
{
basis = new T();
}
};
// We want to create a QLabel subclass on the main thread, but are running in another thread.
// We cannot move QWidget subclasses to a different thread (obviously that would be crazy), but
// we can create one of these, and move it to the main thread, and then use it to create the object
// we want.
// Additional fact: QObject subclasses cannot be template classes.
class MainThreadCreator : public QObject
{
Q_OBJECT
public:
MainThreadCreator()
{
this->moveToThread(QApplication::instance()->thread());
connect(this, SIGNAL(needCreation()), this, SLOT(createThing()), Qt::BlockingQueuedConnection);
}
// While this cannot be a template class, it can still have a template method.
template<typename T>
T * getItem()
{
if (QThread::currentThread() == QApplication::instance()->thread())
return new T();
ActualCreation<T> * actualWorker;
actualWorker = new ActualCreation<T> ();
worker = actualWorker;
emit needCreation();
T * output = actualWorker->basis;
delete actualWorker;
return output;
}
NominalCreation * worker;
signals:
void needCreation();
public slots:
void createThing()
{
worker->creation();
}
};
/*!
* \ingroup transforms
* \brief Displays templates in a GUI pop-up window using QT.
* \author Charles Otto \cite caotto
* Can be used with parallelism enabled, although it is considered TimeVarying.
*/
class ShowTransform : public TimeVaryingTransform
{
Q_OBJECT
public:
Q_PROPERTY(bool waitInput READ get_waitInput WRITE set_waitInput RESET reset_waitInput STORED false)
BR_PROPERTY(bool, waitInput, true)
Q_PROPERTY(QStringList keys READ get_keys WRITE set_keys RESET reset_keys STORED false)
BR_PROPERTY(QStringList, keys, QStringList())
ShowTransform() : TimeVaryingTransform(false, false)
{
displayBuffer = NULL;
window = NULL;
}
~ShowTransform()
{
delete displayBuffer;
delete window;
}
void train(const TemplateList &data) { (void) data; }
void project(const TemplateList &src, TemplateList &dst) const
{
Transform * non_const = (ShowTransform *) this;
non_const->projectUpdate(src,dst);
}
void projectUpdate(const TemplateList &src, TemplateList &dst)
{
dst = src;
if (src.empty() || !Globals->useGui)
return;
foreach (const Template & t, src) {
// build label
QString newTitle;
foreach (const QString & s, keys) {
if (s.compare("name", Qt::CaseInsensitive) == 0) {
newTitle = newTitle + s + ": " + t.file.fileName() + " ";
} else if (t.file.contains(s)) {
QString out = t.file.get<QString>(s);
newTitle = newTitle + s + ": " + out + " ";
}
}
emit this->changeTitle(newTitle);
foreach(const cv::Mat & m, t) {
qImageBuffer = toQImage(m);
displayBuffer->convertFromImage(qImageBuffer);
// Emit an explicit copy of our pixmap so that the pixmap used
// by the main thread isn't damaged when we update displayBuffer
// later.
emit updateImage(displayBuffer->copy(displayBuffer->rect()));
// Blocking wait for a key-press
if (this->waitInput)
window->waitForKey();
}
}
}
void finalize(TemplateList & output)
{
(void) output;
emit hideWindow();
}
void init()
{
initActual<DisplayWindow>();
}
template<typename WindowType>
void initActual()
{
if (!Globals->useGui)
return;
if (displayBuffer)
delete displayBuffer;
displayBuffer = new QPixmap();
if (window)
delete window;
window = creator.getItem<WindowType>();
// Connect our signals to the window's slots
connect(this, SIGNAL(updateImage(QPixmap)), window,SLOT(showImage(QPixmap)));
connect(this, SIGNAL(changeTitle(QString)), window, SLOT(setWindowTitle(QString)));
connect(this, SIGNAL(hideWindow()), window, SLOT(hide()));
}
protected:
MainThreadCreator creator;
DisplayWindow * window;
QImage qImageBuffer;
QPixmap * displayBuffer;
signals:
void updateImage(const QPixmap & input);
void changeTitle(const QString & input);
void hideWindow();
};
BR_REGISTER(Transform, ShowTransform)
/*!
* \ingroup transforms
* \brief Manual selection of landmark locations
* \author Scott Klum \cite sklum
*/
class ManualTransform : public ShowTransform
{
Q_OBJECT
public:
void projectUpdate(const TemplateList &src, TemplateList &dst)
{
if (Globals->parallelism > 1)
qFatal("ManualTransform cannot execute in parallel.");
dst = src;
if (src.empty())
return;
for (int i = 0; i < dst.size(); i++) {
foreach(const cv::Mat &m, dst[i]) {
qImageBuffer = toQImage(m);
displayBuffer->convertFromImage(qImageBuffer);
emit updateImage(displayBuffer->copy(displayBuffer->rect()));
// Blocking wait for a key-press
if (this->waitInput) {
QList<QPointF> points = window->waitForKey();
if (keys.isEmpty()) dst[i].file.appendPoints(points);
else {
if (keys.size() == points.size())
for (int j = 0; j < keys.size(); j++) dst[i].file.set(keys[j], points[j]);
else qWarning("Incorrect number of points specified for %s", qPrintable(dst[i].file.name));
}
}
}
}
}
void init()
{
initActual<PointMarkingWindow>();
}
};
BR_REGISTER(Transform, ManualTransform)
/*!
* \ingroup transforms
* \brief Display an image, and asks a yes/no question about it
* \author Charles Otto \cite caotto
*/
class SurveyTransform : public ShowTransform
{
Q_OBJECT
public:
Q_PROPERTY(QString question READ get_question WRITE set_question RESET reset_question STORED false)
BR_PROPERTY(QString, question, "Yes/No")
Q_PROPERTY(QString propertyName READ get_propertyName WRITE set_propertyName RESET reset_propertyName STORED false)
BR_PROPERTY(QString, propertyName, "answer")
void projectUpdate(const TemplateList &src, TemplateList &dst)
{
if (Globals->parallelism > 1)
qFatal("SurveyTransform cannot execute in parallel.");
dst = src;
if (src.empty())
return;
for (int i = 0; i < dst.size(); i++) {
foreach(const cv::Mat &m, dst[i]) {
qImageBuffer = toQImage(m);
displayBuffer->convertFromImage(qImageBuffer);
emit updateImage(displayBuffer->copy(displayBuffer->rect()));
// Blocking wait for a key-press
if (this->waitInput) {
QString answer = p_window->waitForKeyPress();
dst[i].file.set(this->propertyName, answer);
}
}
}
}
PromptWindow * p_window;
void init()
{
if (!Globals->useGui)
return;
initActual<PromptWindow>();
p_window = (PromptWindow *) window;
emit changeTitle(this->question);
}
};
BR_REGISTER(Transform, SurveyTransform)
class FPSLimit : public TimeVaryingTransform
{
Q_OBJECT
Q_PROPERTY(int targetFPS READ get_targetFPS WRITE set_targetFPS RESET reset_targetFPS STORED false)
BR_PROPERTY(int, targetFPS, 30)
public:
FPSLimit() : TimeVaryingTransform(false, false) {}
~FPSLimit() {}
void train(const TemplateList &data) { (void) data; }
void projectUpdate(const TemplateList &src, TemplateList &dst)
{
dst = src;
qint64 current_time = timer.elapsed();
qint64 target_time = last_time + target_wait;
qint64 wait_time = target_time - current_time;
last_time = current_time;
if (wait_time < 0) {
return;
}
QThread::msleep(wait_time);
last_time = timer.elapsed();
}
void finalize(TemplateList & output)
{
(void) output;
}
void init()
{
target_wait = 1000.0 / targetFPS;
timer.start();
last_time = timer.elapsed();
}
protected:
QElapsedTimer timer;
qint64 target_wait;
qint64 last_time;
};
BR_REGISTER(Transform, FPSLimit)
class FPSCalc : public TimeVaryingTransform
{
Q_OBJECT
Q_PROPERTY(int targetFPS READ get_targetFPS WRITE set_targetFPS RESET reset_targetFPS)
BR_PROPERTY(int, targetFPS, 30)
public:
FPSCalc() : TimeVaryingTransform(false, false) { initialized = false; }
~FPSCalc() {}
void train(const TemplateList &data) { (void) data; }
void projectUpdate(const TemplateList &src, TemplateList &dst)
{
dst = src;
if (!initialized) {
initialized = true;
timer.start();
}
framesSeen++;
if (dst.empty())
return;
qint64 elapsed = timer.elapsed();
if (elapsed > 1000) {
double fps = 1000 * framesSeen / elapsed;
dst.first().file.set("AvgFPS", fps);
}
}
void finalize(TemplateList & output)
{
(void) output;
}
void init()
{
initialized = false;
framesSeen = 0;
}
protected:
bool initialized;
QElapsedTimer timer;
qint64 framesSeen;
};
BR_REGISTER(Transform, FPSCalc)
} // namespace br
#include "gui.moc"