MovieAnalyzer.cpp
26.7 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
#include <QProgressDialog>
#include <QLabel>
#include <QGridLayout>
#include <QFile>
#include <QFileDialog>
#include <QRegularExpression>
#include <QProcess>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <QDebug>
#include <iostream>
#include <cstdlib>
#include "MovieAnalyzer.h"
#include "ProjectModel.h"
using namespace cv;
using namespace std;
MovieAnalyzer::MovieAnalyzer(QWidget *parent)
: QWidget(parent)
{
m_processor = new VideoFrameProcessor;
}
MovieAnalyzer::~MovieAnalyzer()
{
}
bool MovieAnalyzer::extractVideoFrames(const QString &fName)
{
int id;
m_cap.release();
m_cap.open(fName.toStdString());
QProgressDialog progress(tr("Extracting frames..."), tr("Cancel"), 0, m_cap.get(CV_CAP_PROP_FRAME_COUNT), this);
progress.setWindowModality(Qt::WindowModal);
emit setResolution(QSize(m_cap.get(CV_CAP_PROP_FRAME_WIDTH), m_cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
emit setFps(m_cap.get(CV_CAP_PROP_FPS));
while (m_cap.grab()) {
id = m_cap.get(CV_CAP_PROP_POS_FRAMES);
progress.setValue(id);
if (progress.wasCanceled())
return false;
emit appendVideoFrame(id, m_cap.get(CV_CAP_PROP_POS_MSEC));
}
return true;
}
bool MovieAnalyzer::extractShots(const QString &fName, int histoType, int nVBins, int nHBins, int nSBins, int metrics, qreal threshold1, qreal threshold2, int nVBlock, int nHBlock, bool viewProgress)
{
m_cap.release();
m_cap.open(fName.toStdString());
// current frame
Mat frame;
// subimages of current frame
QVector<Mat> blocks(nVBlock * nHBlock);
// corresponding local histograms
QVector<Mat> locHisto(nVBlock * nHBlock);
// distances between current and previous local histograms
QVector<qreal> distance(nVBlock * nHBlock);
// distance between current and past frame
qreal dist;
// frames considered to detect cut
QList<qreal> window;
// current frame position and index
qint64 position(0);
int n(0);
// previous frame position
qint64 prevPosition(0);
// indicates that no more frame is available in video capture
bool open(true);
// normalized local copies of thresholds
qreal thresh1(threshold1 / 100.0);
qreal thresh2(threshold2 / 100.0);
// activate appropriate metrics
switch (metrics) {
case 4:
m_processor->activL1();
break;
case 5:
m_processor->activL2();
break;
case CV_COMP_CORREL:
m_processor->activCorrel();
break;
case CV_COMP_CHISQR:
m_processor->activChiSqr();
break;
case CV_COMP_INTERSECT:
m_processor->activIntersect();
break;
case CV_COMP_HELLINGER:
m_processor->activHellinger();
break;
}
// progress bar
QProgressDialog progress(tr("Extracting shots..."), tr("Cancel"), 0, m_cap.get(CV_CAP_PROP_FRAME_COUNT), this);
if (viewProgress) {
progress.setWindowModality(Qt::WindowModal);
}
while (open) {
// retrieve frame position
n = m_cap.get(CV_CAP_PROP_POS_FRAMES);
position = m_cap.get(CV_CAP_PROP_POS_MSEC);
open = m_cap.read(frame);
if (open) {
// retrieving previous shot frame blocks
blocks = splitImage(frame, nVBlock, nHBlock);
// looping over frame blocks
for (int i(0); i < blocks.size(); i++) {
// compute V/HS/HSV histogram for each frame block
switch (histoType) {
case 0:
locHisto[i] = m_processor->genVHisto(blocks[i], nVBins);
break;
case 1:
locHisto[i] = m_processor->genHsHisto(blocks[i], nHBins, nSBins);
break;
case 2:
locHisto[i] = m_processor->genHsvHisto(blocks[i], nHBins, nSBins, nVBins);
break;
}
// compute distance from previous frame for each block
if (!m_prevLocHisto.isEmpty())
distance[i] = m_processor->distanceFromPrev(locHisto[i], m_prevLocHisto[i]);
}
dist = meanDistance(distance);
/*** for displaying purpose ***/
/* imshow("test1", frame);
waitKey(0);
qDebug();
for (int i(0); i < nHBlock; i++) {
for (int j(0); j < nVBlock; j++) {
printf("%4.4f\t", 1 - distance[i * nVBlock + j]);
}
cout << endl;
}
qDebug();
qDebug() << (1 - dist); */
// append current distance to the window
window.push_back(dist);
if (window.size() > 3)
window.pop_front();
// insert shot at current position
if (window[0] <= thresh2 && window[1] >= thresh1 && window[2] <= thresh2) {
emit insertShot(prevPosition, Segment::Automatic);
}
// updating previous local histograms to current ones
m_prevLocHisto.resize(blocks.size());
m_prevLocHisto = locHisto;
// updating previous position to current
prevPosition = position;
}
// update progress bar
if (viewProgress) {
progress.setValue(n);
if (progress.wasCanceled())
return false;
}
}
return true;
}
bool MovieAnalyzer::labelSimilarShots(QString fName, int histoType, int nVBins, int nHBins, int nSBins, int metrics, qreal maxDist, int windowSize, const QList<qint64> &shotPositions, int nVBlock, int nHBlock, bool viewProgress)
{
m_cap.release();
m_cap.open(fName.toStdString());
// distance matrix between shots
Mat dist(shotPositions.size(), shotPositions.size(), CV_32FC1, Scalar(-1.0));
// previous and current shot frame
Mat prevShotFrame;
Mat currShotFrame;
// subimages of current and past frames
QVector<Mat> prevBlocks;
QVector<Mat> currBlocks;
// local histogram of each frame block
QVector<Mat> locHisto(nVBlock * nHBlock);
// accumulator of previous lists of local histograms
QList<QVector<Mat>> locHistoBuffer;
// distance between first frame of current shot and last frame of past shot
QVector<qreal> distance(nVBlock * nHBlock);
/*** for displaying purpose ***/
QList<Mat> frameBuffer;
// frame duration
// doesn't work anymore after updating Ubuntu
// int frameDur = 1 / m_cap.get(CV_CAP_PROP_FPS) * 1000;
int frameDur = 1 / 25.0 * 1000;
// distance between local histograms
qreal locDistance;
// minimum distance from current frame observed so far
qreal minDistance;
// corresponding index
int jMin;
// current camera label
int nCamera(0);
// camera label for each shot
QVector<int> shotCamera(shotPositions.size());
// activate appropriate metrics
switch (metrics) {
case 4:
m_processor->activL1();
break;
case 5:
m_processor->activL2();
break;
case CV_COMP_CORREL:
m_processor->activCorrel();
break;
case CV_COMP_CHISQR:
m_processor->activChiSqr();
break;
case CV_COMP_INTERSECT:
m_processor->activIntersect();
break;
case CV_COMP_HELLINGER:
m_processor->activHellinger();
break;
}
// progress bar
QProgressDialog progress(tr("Retrieving similar shots..."), tr("Cancel"), 0, shotPositions.size(), this);
if (viewProgress)
progress.setWindowModality(Qt::WindowModal);
// normalizing max distance required to link two shots
maxDist /= 100.0;
// looping over shot positions
shotCamera[0] = nCamera;
for (int i(1); i < shotPositions.size(); i++) {
/****************************/
/* processing previous shot */
/****************************/
m_cap.set(CV_CAP_PROP_POS_MSEC, shotPositions[i] - frameDur);
m_cap >> prevShotFrame;
// retrieving previous shot frame blocks
prevBlocks = splitImage(prevShotFrame, nVBlock, nHBlock);
// resizing local histograms vector if necessary
if (prevBlocks.size() != nVBlock * nHBlock)
locHisto.resize(prevBlocks.size());
// looping over previous shot frame blocks
for (int j(0); j < prevBlocks.size(); j++)
// compute V/HS/HSV histogram for each block of previous shot last frame
switch (histoType) {
case 0:
locHisto[j] = m_processor->genVHisto(prevBlocks[j], nVBins);
break;
case 1:
locHisto[j] = m_processor->genHsHisto(prevBlocks[j], nHBins, nSBins);
break;
case 2:
locHisto[j] = m_processor->genHsvHisto(prevBlocks[j], nHBins, nSBins, nVBins);
break;
}
/*** for displaying purpose ***/
/* Mat frameCopy;
prevShotFrame.copyTo(frameCopy);
frameBuffer.push_front(frameCopy);
if (frameBuffer.size() == windowSize + 1)
frameBuffer.pop_back(); */
// saving list of corresponding histograms
locHistoBuffer.push_front(locHisto);
// update buffer boundaries
if (locHistoBuffer.size() == windowSize + 1)
locHistoBuffer.pop_back();
/***************************/
/* processing current shot */
/***************************/
m_cap >> currShotFrame;
/*** for displaying purpose ***/
// imshow("present", currShotFrame);
// retrieving current shot frame blocks
currBlocks = splitImage(currShotFrame, nVBlock, nHBlock);
// resizing local histograms vector if necessary
if (currBlocks.size() != nVBlock * nHBlock) {
locHisto.resize(currBlocks.size());
distance.resize(currBlocks.size());
}
// looping over current shot frame blocks
for (int j(0); j < currBlocks.size(); j++)
// compute V/HS/HSV histogram for each block of current shot last frame
switch (histoType) {
case 0:
locHisto[j] = m_processor->genVHisto(currBlocks[j], nVBins);
break;
case 1:
locHisto[j] = m_processor->genHsHisto(currBlocks[j], nHBins, nSBins);
break;
case 2:
locHisto[j] = m_processor->genHsvHisto(currBlocks[j], nHBins, nSBins, nVBins);
break;
}
// compute distance between current and past frame local histograms
minDistance = 1.0;
jMin = 0;
for (int j(0); j < locHistoBuffer.size(); j++) {
// retrieving past list of local histograms
QVector<Mat> prevLocHisto = locHistoBuffer[j];
// looping over list of local histograms and computing local distances
for (int k(0); k < prevLocHisto.size(); k++)
distance[k] = m_processor->distanceFromPrev(locHisto[k], prevLocHisto[k]);
// averaging local distances
locDistance = meanDistance(distance);
/*** for displaying purpose ***/
/* qDebug();
for (int k(0); k < nHBlock; k++) {
for (int l(0); l < nVBlock; l++) {
printf("%4.4f\t", 1 - distance[k * nVBlock + l]);
}
cout << endl;
}
qDebug();
qDebug() << (1 - locDistance);
imshow("past", frameBuffer[j]);
waitKey(0); */
if (locDistance < minDistance) {
minDistance = locDistance;
jMin = j;
}
// updating distance matrix
dist.at<float>(i, i-j-1) = locDistance;
}
// similar shot retrieved among previous shots
if (minDistance <= maxDist) {
int iSim = i - (jMin + 1);
shotCamera[i] = shotCamera[iSim];
emit labelSimShot(shotPositions[iSim], shotCamera[iSim], Segment::Automatic);
emit labelSimShot(shotPositions[i], shotCamera[i], Segment::Automatic);
}
// no similar shot retrieved: new camera label
else
shotCamera[i] = nCamera++;
// updating progress bar
if (viewProgress) {
progress.setValue(i);
if (progress.wasCanceled())
return false;
}
}
return true;
}
bool MovieAnalyzer::localSpkDiar(QList<QPair<qint64, qint64>> subBound, QMap<QString, QList<QPair<int, qreal>>> shotPatterns, QMap<QString, QList<QPair<qint64, qint64>>> strictShotPattBound, UtteranceTree::DistType dist, bool norm, UtteranceTree::AgrCrit agr, UtteranceTree::PartMeth partMeth, bool weight, bool sigma, const QString &baseName)
{
QMap<QString, QList<QPair<int, qreal>>>::const_iterator it = shotPatterns.begin();
QMap<QString, QString> uttLabels; // speaker label assigned to each utterance
QString pattLabel; // pattern label
int uttIdx; // utterance index
qreal uttStart; // utterance beginning in s
qreal uttEnd; // utterance ending in s
UtteranceTree tree; // dendogram corresponding to local clustering
QList<QList<int>> partition; // optimal partition of the tree
qreal beginning, end; // boundaries of movie subpart considered
QString workPath("spkDiarization/");
QProcess process;
QString program;
QStringList arguments;
QString args;
int out;
m_baseName = baseName;
qDebug() << "Local agglomerative clustering...";
// initializing boundaries
beginning = subBound[subBound.size() - 1].second / 1000.0;
end = subBound[0].first / 1000.0;
// output file
QString fName = workPath + "lblLocalSegmentation/" + m_baseName + ".lbl";
QFile lblFile(fName);
if (!lblFile.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream lblOut(&lblFile);
// parameterizing tree
tree.setDist(dist);
tree.setAgr(agr);
tree.setPartMeth(partMeth);
// setting covariance matrix
if (sigma)
CovInv = pinv(Sigma);
else
CovInv = pinv(CovW);
// normalize E if necessary
if (norm)
normalize(dist);
// looping over shot patterns
while (it != shotPatterns.end()) {
// current pattern label
pattLabel = it.key();
// pattern boundaries
QList<QPair<qint64, qint64>> shotPattBound = strictShotPattBound[pattLabel];
// utterances covered by current pattern
QList<QPair<int, qreal>> utter = it.value();
// indices of utterances in current pattern
arma::umat V(1, utter.size());
for (int i(0); i < utter.size(); i++)
V(0, i) = utter[i].first;
// matrix containing utterance i-vectors for current pattern
arma::mat S = E.rows(V);
// weighting utterances
arma::mat W(1, utter.size(), arma::fill::ones);
if (weight)
for (int i(0); i < utter.size(); i++)
W(0, i) = utter[i].second;
else
W.ones(1, utter.size());
W /= arma::accu(W);
// setting tree
tree.setTree(S, W, CovInv);
// retrieving optimal partition
partition = tree.getPartition();
// looping over partition for labeling purpose
for (int i(0); i < partition.size(); i++) {
for (int j(0); j < partition[i].size(); j++) {
// index of current utterance
uttIdx = utter[partition[i][j]].first;
// adjusting utterance boundaries to shot pattern ones
QPair<qint64, qint64> pair = adjustSubBoundaries(subBound[uttIdx].first, subBound[uttIdx].second, shotPattBound);
uttStart = static_cast<qreal>(pair.first) / 1000.0;
uttEnd = static_cast<qreal>(pair.second) / 1000.0;
// labelling current utterance
QString currSpk = pattLabel + "_S" + QString::number(i);
lblOut << uttStart << " " << uttEnd << " " << currSpk << endl;
emit setSpeaker(static_cast<qint64>(uttStart * 1000),
static_cast<qint64>(uttEnd * 1000),
currSpk,
VideoFrame::Hyp1);
// updating boundaries of speech segments
if (uttStart < beginning)
beginning = uttStart;
if (uttEnd > end)
end = uttEnd;
}
}
it++;
}
qDebug() << "Done.";
// converting hypotheses .lbl file into .rttm one
program = "perl";
arguments << workPath + "scripts/SpkMoulinette.pl" << workPath + "lblLocalSegmentation/" + m_baseName + ".lbl" << workPath + "rttmTmp/" + m_baseName + ".rttm";
process.start(program, arguments);
process.waitForFinished();
arguments.clear();
// evaluating hypotheses
program = "perl ";
args = workPath + "scripts/md-eval-v21.pl" + " -af -m -1 -c 0.25 -r " + workPath + "data/ref/seg/" + m_baseName + ".rttm" + " -s " + workPath + "rttmTmp/" + m_baseName + ".rttm" + " -u " + workPath + "data/ref/local/" + m_baseName + ".uem > " + workPath + "score/local/" + m_baseName + ".nistres";
out = std::system(qPrintable(program + args));
return true;
}
bool MovieAnalyzer::globalSpkDiar(const QString &baseName)
{
UtteranceTree tree; // dendogram corresponding to global clustering
QList<QList<int>> partition; // selected partition of the tree
QList<QPair<int, qreal>> spkFeatures; // speakers references and weights
qreal weight;
QMap<QString, qreal> spkWeight;
QString speaker;
m_baseName = baseName;
// weighting speakers
QMap<QString, QList<QPair<qreal, qreal>>>::const_iterator it = m_utterances.begin();
while (it != m_utterances.end()) {
speaker = it.key();
QList<QPair<qreal, qreal>> utterances = it.value();
spkWeight[speaker] = 0.0;
for (int i(0); i < utterances.size(); i++)
spkWeight[speaker] += utterances[i].second - utterances[i].first;
it++;
}
// setting features
it = m_utterances.begin();
spkFeatures.clear();
while (it != m_utterances.end()) {
speaker = it.key();
weight = spkWeight[speaker];
spkFeatures.push_back(QPair<int, qreal>(m_speakers.indexOf(speaker), weight));
it++;
}
// sending parameters to tree monitor
m_treeMonitor = new SpkDiarMonitor(900, 300, true);
m_treeMonitor->setDiarData(E, Sigma, CovW);
m_treeMonitor->setSpeakers(m_speakers, spkWeight);
m_treeMonitor->getCurrentPattern(spkFeatures);
m_treeMonitor->show();
// receiving playing signal from dendogram widget
connect(m_treeMonitor, SIGNAL(playSub(QList<int>)), this, SLOT(playSpeakers(QList<int>)));
// get partition for default parameters
connect(m_treeMonitor, SIGNAL(setSpeakerPartition(QList<QList<int>>)), this, SLOT(setSpeakerPartition(QList<QList<int>>)));
// sending scores obtained to diarization monitor
connect(this, SIGNAL(setLocalDer(const QString &)), m_treeMonitor, SLOT(setLocalDer(const QString &)));
connect(this, SIGNAL(setGlobalDer(const QString &)), m_treeMonitor, SLOT(setGlobalDer(const QString &)));
m_treeMonitor->exportResults();
return true;
}
bool MovieAnalyzer::localSpkDiarBaseline(QMap<QString, QList<QPair<int, qreal>>> shotPatterns, QList<QPair<qint64, qint64>> subBound, QMap<QString, QList<QPair<int, qreal>>> shotUtterances, QMap<QString, QList<QPair<qint64, qint64>>> strictShotPattBound, const QString &baseName)
{
QMap<QString, QList<QPair<int, qreal>>>::const_iterator it = shotPatterns.begin();
QString patternLabel;
QString currSpk;
QStringList labelList;
QString firstLabel;
QString secondLabel;
qreal uttStart;
qreal uttEnd;
QPair<QStringList, QStringList> patternShots;
QString workPath("spkDiarization/");
QProcess process;
QString program;
QStringList arguments;
QString args;
int out;
m_baseName = baseName;
// output file
QString fName = workPath + "lblLocalSegmentation/" + m_baseName + ".lbl";
QFile lblFile(fName);
if (!lblFile.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream lblOut(&lblFile);
// looping over shot patterns
while (it != shotPatterns.end()) {
// current pattern label
patternLabel = it.key();
// pattern boundaries
QList<QPair<qint64, qint64>> shotPattBound = strictShotPattBound[patternLabel];
// retrieving each pattern part
labelList = patternLabel.split("_");
firstLabel = labelList[0];
secondLabel = labelList[1];
// remove additional characters
QRegularExpression openPar(QRegularExpression::escape("("));
QRegularExpression closePar(QRegularExpression::escape(")"));
firstLabel.replace(openPar, "");
firstLabel.replace(closePar, "");
secondLabel.replace(openPar, "");
secondLabel.replace(closePar, "");
// equivalent shots in each pattern part
patternShots.first = firstLabel.split("|");
patternShots.second = secondLabel.split("|");
// looping over pattern utterances
QList<QPair<int, qreal>> utterances = it.value();
for (int i(0); i < utterances.size(); i++) {
int uttIdx = utterances[i].first;
// adjusting utterance boundaries to shot pattern ones
QPair<qint64, qint64> pair = adjustSubBoundaries(subBound[uttIdx].first, subBound[uttIdx].second, shotPattBound);
uttStart = static_cast<qreal>(pair.first) / 1000.0;
uttEnd = static_cast<qreal>(pair.second) / 1000.0;
// labelling current utterance according to the corresponding shot
bool found(false);
int j(0);
while (j < patternShots.first.size() && !found) {
if (shotUtterances[patternShots.first[j]].contains(utterances[i])) {
currSpk = patternLabel + "_S0";
found = true;
}
j++;
}
j = 0;
while (j < patternShots.second.size() && !found) {
if (shotUtterances[patternShots.second[j]].contains(utterances[i])) {
currSpk = patternLabel + "_S1";
found = true;
}
j++;
}
lblOut << uttStart << " " << uttEnd << " " << currSpk << endl;
emit setSpeaker(static_cast<qint64>(uttStart * 1000),
static_cast<qint64>(uttEnd * 1000),
currSpk,
VideoFrame::Hyp1);
}
it++;
}
// converting hypotheses .lbl file into .rttm one
program = "perl";
arguments << workPath + "scripts/SpkMoulinette.pl" << workPath + "lblLocalSegmentation/" + m_baseName + ".lbl" << workPath + "rttmTmp/" + m_baseName + ".rttm";
process.start(program, arguments);
process.waitForFinished();
arguments.clear();
// evaluating hypotheses
program = "perl ";
args = workPath + "scripts/md-eval-v21.pl" + " -af -m -1 -c 0.25 -r " + workPath + "data/ref/seg/" + m_baseName + ".rttm" + " -s " + workPath + "rttmTmp/" + m_baseName + ".rttm" + " -u " + workPath + "data/ref/local/" + m_baseName + ".uem > " + workPath + "score/local/" + m_baseName + ".nistres";
out = std::system(qPrintable(program + args));
return true;
}
QVector<cv::Mat> MovieAnalyzer::splitImage(const Mat &frame, int nVBlock, int nHBlock)
{
QVector<Mat> blocks;
int blockVSize(frame.rows / nVBlock);
int blockHSize(frame.cols / nHBlock);
int width(0);
int height(0);
for (int i(0); i < frame.rows; i += blockVSize) {
height = (i + blockVSize > frame.rows) ? (frame.rows - i) : blockVSize;
for (int j(0); j < frame.cols; j += blockHSize) {
width = (j + blockHSize > frame.cols) ? (frame.cols - j) : blockHSize;
blocks.push_back(frame(Rect(j, i, width, height)));
}
}
return blocks;
}
qreal MovieAnalyzer::meanDistance(const QVector<qreal> &distance)
{
qreal sum(0.0);
for (int i(0); i < distance.size(); i++)
sum += abs(1 - distance[i]);
return 1 - sum / distance.size();
}
///////////////////////
// auxiliary methods //
///////////////////////
void MovieAnalyzer::setDiarData(const arma::mat &E, const arma::mat &Sigma, const arma::mat &W)
{
this->E = E;
this->Sigma = Sigma;
this->CovW = W;
}
void MovieAnalyzer::setDiarData(const arma::mat &E, const arma::mat &Sigma, const arma::mat &W, QMap<QString, QList<QPair<qreal, qreal>>> speakers)
{
setDiarData(E, Sigma, W);
m_utterances = speakers;
QMap<QString, QList<QPair<qreal, qreal>>>::const_iterator it = m_utterances.begin();
m_speakers.clear();
while (it != m_utterances.end()) {
m_speakers.push_back(it.key());
it++;
}
}
void MovieAnalyzer::normalize(UtteranceTree::DistType dist)
{
qreal normFac;
for (arma::uword i(0); i < E.n_rows; i++) {
switch (dist) {
case UtteranceTree::L2:
normFac = arma::as_scalar(E.row(i) * E.row(i).t());
break;
case UtteranceTree::Mahal:
normFac = arma::as_scalar(E.row(i) * CovInv * E.row(i).t());
break;
}
E.row(i) = E.row(i) / normFac;
}
}
QPair<qint64, qint64> MovieAnalyzer::adjustSubBoundaries(qint64 subStart, qint64 subEnd, QList<QPair<qint64, qint64>> shotPattBound)
{
bool found(false);
int i(0);
while (i < shotPattBound.size() && !found) {
// truncate utterance at the beginning
if (subStart < shotPattBound[i].first && subEnd > shotPattBound[i].first) {
subStart = shotPattBound[i].first;
found = true;
}
// utterance included in shot
else if (subStart >= shotPattBound[i].first && subEnd <= shotPattBound[i].second)
found = true;
// truncate utterance at the end
else if (subStart < shotPattBound[i].second && subEnd > shotPattBound[i].second) {
subEnd = shotPattBound[i].second;
found = true;
}
i++;
}
return QPair<qint64, qint64>(subStart, subEnd);
}
///////////
// slots //
///////////
void MovieAnalyzer::setSpeakerPartition(QList<QList<int>> partition)
{
QString speaker;
QList<QPair<qreal, qreal>> utterances;
QString workPath("spkDiarization/");
QProcess process;
QString program;
QStringList arguments;
QString args;
int out;
QString fName = workPath + "lblGlobalSegmentation/" + m_baseName;
QFile lblFile(fName + ".lbl");
if (!lblFile.open(QIODevice::WriteOnly | QIODevice::Text))
return;
QTextStream lblOut(&lblFile);
// looping over the partition elements
for (int i(0); i < partition.size(); i++) {
QList<int> part = partition[i];
// looping over each part
for (int j(0); j < part.size(); j++) {
speaker = m_speakers[part[j]];
utterances = m_utterances[speaker];
// looping over the utterances of each speaker
for (int k(0); k < utterances.size(); k++) {
lblOut << utterances[k].first << " " << utterances[k].second << " " << ("S" + QString::number(i)) << endl;
emit setSpeaker(static_cast<qint64>(utterances[k].first * 1000),
static_cast<qint64>(utterances[k].second * 1000),
"S" + QString::number(i),
VideoFrame::Hyp1);
}
}
}
// converting hypotheses .lbl file into .rttm one
program = "perl";
arguments << workPath + "scripts/SpkMoulinette.pl" << workPath + "lblGlobalSegmentation/" + m_baseName + ".lbl" << workPath + "rttmTmp/" + m_baseName + ".rttm";
process.start(program, arguments);
process.waitForFinished();
arguments.clear();
// evaluating hypotheses
program = "perl ";
args = workPath + "scripts/md-eval-v21.pl" + " -af -m -1 -c 0.25 -r " + workPath + "data/ref/local/" + m_baseName + ".rttm" + " -s " + workPath + "rttmTmp/" + m_baseName + ".rttm" + " -u " + workPath + "data/ref/local/" + m_baseName + ".uem > " + workPath + "score/global/" + m_baseName + ".nistres";
out = std::system(qPrintable(program + args));
// retrieving local and global DER
emit setLocalDer(retrieveDer(workPath + "score/local/" + m_baseName + ".nistres"));
emit setGlobalDer(retrieveDer(workPath + "score/global/" + m_baseName + ".nistres"));
// removing files
QFile::remove(workPath + "lblLocalSegmentation/" + m_baseName + ".lbl");
QFile::remove(workPath + "lblGlobalSegmentation/" + m_baseName + ".lbl");
QFile::remove(workPath + "rttmTmp/" + m_baseName + ".rttm");
}
void MovieAnalyzer::playSpeakers(QList<int> speakers)
{
QList<QPair<qreal, qreal>> utterances;
QList<QPair<qint64, qint64>> segments;
QString speaker;
for (int i(0); i < speakers.size(); i++) {
speaker = m_speakers[speakers[i]];
utterances = m_utterances[speaker];
for (int j(0); j < utterances.size(); j++)
segments.push_back(QPair<qint64, qint64>(utterances[j].first * 1000, utterances[j].second * 1000));
}
emit playSegments(segments);
}
QString MovieAnalyzer::retrieveDer(const QString fName)
{
QRegularExpression score("OVERALL SPEAKER DIARIZATION ERROR = (\\d{2}.\\d{2})");
QFile file(fName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return "00.00";
QTextStream in(&file);
// parsing score file
while (!in.atEnd()) {
QString line = in.readLine();
QRegularExpressionMatch match = score.match(line);
if (match.hasMatch())
return match.captured(1);
}
return "00.00";
}