script.cpp 29.4 KB
Newer Older
1
2
3
4
5
6
7
/*
    Questo script esegue l'analisi di un video fornito per rilevare le discontinuità
    che vengono trovate.

    Tutte le informazioni necessarie all'agoritmo si possono individuare nei file XML
    all'interno della cartella config.

Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
8
9
10
    @author Nadir Dalla Pozza
    @version 3.0
    @date 29-06-2022
11
12
*/
#include <filesystem>
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
13
#include <fstream>
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
#include <iostream>
#include <sys/timeb.h>

#include <boost/uuid/uuid.hpp>            // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <boost/uuid/uuid_io.hpp>         // streaming operators etc.
#include <boost/lexical_cast.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

#include <nlohmann/json.hpp>

#include "utility.h"
#include "forAudioAnalyser.h"

namespace fs = std::__fs::filesystem;
using namespace cv;
using namespace std;
using json = nlohmann::json;



/*
------------------------------------------------------------------------------
VARIABLES
------------------------------------------------------------------------------
*/

Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
45
bool savingPinchRoller = false, pinchRollerRect = false;
46
47
48
49
bool savingBrand = false;
cv::Mat myFrame;
float mediaPrevFrame = 0;
bool firstBrand = true;	// The first frame containing brands on tape must be saved
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
50
float firstInstant = 0;
51
52
53
54
55
56
57

// config.json parameters
bool brands;
std::string irregularityFileInputPath;
std::string outputPath;
std::string videoPath;
float speed;
58
59
float tapeThresholdPercentual;
float capstanThresholdPercentual;
60
61
62
63
64
65
// JSON files
json configurationFile;
json irregularityFileInput;
json irregularityFileOutput1;
json irregularityFileOutput2;
// RotatedRect identifying the processing area
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
66
RotatedRect rect, rectTape, rectCapstan;
67
68
69
70
71



bool frameDifference(cv::Mat prevFrame, cv::Mat currentFrame, int msToEnd) {

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
	/********************************** Capstan analysis *****************************************/

	// In the last minute of the video, check for pinchRoller position for endTape event
	if (msToEnd < 60000) {

		// Capstan area
		int capstanAreaPixels = rectCapstan.size.width * rectCapstan.size.height;
		float capstanDifferentPixelsThreshold = capstanAreaPixels * capstanThresholdPercentual / 100;
		
		// CODE FROM https://answers.opencv.org/question/497/extract-a-rotatedrect-area/

		// matrices we'll use
		Mat M, rotatedPrevFrame, croppedPrevFrame, rotatedCurrentFrame, croppedCurrentFrame;
		// get angle and size from the bounding box
		float angle = rectCapstan.angle;
		Size rect_size = rectCapstan.size;
		// thanks to http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
		if (rectCapstan.angle < -45.) {
			angle += 90.0;
			swap(rect_size.width, rect_size.height);
		}
		// get the rotation matrix
		M = getRotationMatrix2D(rectCapstan.center, angle, 1.0);
		// perform the affine transformation
		warpAffine(prevFrame, rotatedPrevFrame, M, prevFrame.size(), INTER_CUBIC);
		warpAffine(currentFrame, rotatedCurrentFrame, M, currentFrame.size(), INTER_CUBIC);
		// crop the resulting image
		getRectSubPix(rotatedPrevFrame, rect_size, rectCapstan.center, croppedPrevFrame);
		getRectSubPix(rotatedCurrentFrame, rect_size, rectCapstan.center, croppedCurrentFrame);

		// imshow("Current frame", currentFrame);
		// imshow("Cropped Current Frame", croppedCurrentFrame);
		// waitKey();

		// END CODE FROM https://answers.opencv.org/question/497/extract-a-rotatedrect-area/

		cv::Mat differenceFrame = difference(croppedPrevFrame, croppedCurrentFrame);

		int blackPixelsCapstan = 0;

		for (int i = 0; i < croppedCurrentFrame.rows; i++) {
			for (int j = 0; j < croppedCurrentFrame.cols; j++) {
				if (differenceFrame.at<cv::Vec3b>(i, j)[0] == 0) {
					// There is a black pixel, then there is a difference between previous and current frames
					blackPixelsCapstan++;
				}
			}
		}

		if (blackPixelsCapstan > capstanDifferentPixelsThreshold) {
			savingPinchRoller = true;
			return true;
		} else {
			savingPinchRoller = false;
		}
	}
	
	/************************************ Tape analysis ******************************************/

	// Tape area
    int tapeAreaPixels = rectTape.size.width * rectTape.size.height;
	float tapeDifferentPixelsThreshold = tapeAreaPixels * tapeThresholdPercentual / 100;
134
135

	/***************** Extract matrices corresponding to the processing area *********************/
136
137

	// Tape area
138
139
140
141
142
	// CODE FROM https://answers.opencv.org/question/497/extract-a-rotatedrect-area/

	// matrices we'll use
	Mat M, rotatedPrevFrame, croppedPrevFrame, rotatedCurrentFrame, croppedCurrentFrame;
	// get angle and size from the bounding box
143
144
	float angle = rectTape.angle;
	Size rect_size = rectTape.size;
145
	// thanks to http://felix.abecassis.me/2011/10/opencv-rotation-deskewing/
146
	if (rectTape.angle < -45.) {
147
148
149
150
		angle += 90.0;
		swap(rect_size.width, rect_size.height);
	}
	// get the rotation matrix
151
	M = getRotationMatrix2D(rectTape.center, angle, 1.0);
152
153
154
155
	// perform the affine transformation
	warpAffine(prevFrame, rotatedPrevFrame, M, prevFrame.size(), INTER_CUBIC);
	warpAffine(currentFrame, rotatedCurrentFrame, M, currentFrame.size(), INTER_CUBIC);
	// crop the resulting image
156
157
	getRectSubPix(rotatedPrevFrame, rect_size, rectTape.center, croppedPrevFrame);
	getRectSubPix(rotatedCurrentFrame, rect_size, rectTape.center, croppedCurrentFrame);
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

	// imshow("Current frame", currentFrame);
	// imshow("Cropped Current Frame", croppedCurrentFrame);
	// waitKey();

	// END CODE FROM https://answers.opencv.org/question/497/extract-a-rotatedrect-area/

	cv::Mat differenceFrame = difference(croppedPrevFrame, croppedCurrentFrame);

	int decEnd = (msToEnd % 1000) / 100;
	int secEnd = (msToEnd - (msToEnd % 1000)) / 1000;
	int minEnd = secEnd / 60;
	secEnd = secEnd % 60;


	/****************************** Segment analysis ****************************************/
			
  	int blackPixels = 0;
	float mediaCurrFrame;
	int totColoreCF = 0;

	for (int i = 0; i < croppedCurrentFrame.rows; i++) {
		for (int j = 0; j < croppedCurrentFrame.cols; j++) {
			totColoreCF += croppedCurrentFrame.at<cv::Vec3b>(i, j)[0] + croppedCurrentFrame.at<cv::Vec3b>(i, j)[1] + croppedCurrentFrame.at<cv::Vec3b>(i, j)[2];
			if (differenceFrame.at<cv::Vec3b>(i, j)[0] == 0) {
				blackPixels++;
			}
		}
	}
187
	mediaCurrFrame = totColoreCF/tapeAreaPixels;
188

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
189
190
	/************************************* Decision stage ****************************************/

191
	if (blackPixels > tapeDifferentPixelsThreshold) {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
192

193
		if (brands) {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
194
195

			/***** AVERAGE_COLOR-BASED DECISION *****/
196
197
198
199
200
201
202
			if (mediaPrevFrame > (mediaCurrFrame + 10) || mediaPrevFrame < (mediaCurrFrame - 10)) { // They are not similar for color average
				// Update mediaPrevFrame
				mediaPrevFrame = mediaCurrFrame;
				return true;
			}
			// If the above condition is not verified, update anyway mediaPrevFrame
			mediaPrevFrame = mediaCurrFrame;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
203
204

			/***** BRANDS MANAGEMENT *****/
205
206
			// At the beginning of the video, wait at least 1 second before the next Irregularity to consider it as a brand.
			// It is not guaranteed that it will be the first brand, but it is generally a safe approach to have a correct image
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
207
			if (firstBrand && (firstInstant - msToEnd > 1000)) {
208
209
210
211
				firstBrand = false;
				savingBrand = true;
				return true;
			}
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
212
213
214
215
			// In the following iterations reset savingBrand, since we are no longer interested in brands.
			if (savingBrand)
				savingBrand = false;

216
		} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
217
			// With no brands, overcoming the threshold is sufficient
218
219
			return true;
		}
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
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
	}
	
	return false;
}


int processing(cv::VideoCapture videoCapture, std::string fileName) {

	// Video duration
	int frameNumbers_v = videoCapture.get(CAP_PROP_FRAME_COUNT);
	float fps_v = videoCapture.get(CAP_PROP_FPS); // FPS can be non-integers!!!
	float videoLength = (float) frameNumbers_v / fps_v; // [s]
	int videoLength_ms = videoLength * 1000;
	
    int savedFrames = 0, unsavedFrames = 0;
	float lastSaved = -160;
	int savingRate = 0; // [ms]
	// Whenever we find an Irregularity, we want to skip a lenght equal to the reading head (3 cm = 1.18 inches)
	if (speed == 7.5)
		savingRate = 157; // Time taken to cross 3 cm at 7.5 ips
	else if (speed == 15)
		savingRate = 79; // Time taken to cross 3 cm at 15 ips

	// The first frame of the video won't be processed
    cv::Mat prevFrame;
	videoCapture >> prevFrame;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
247
	firstInstant = videoLength_ms - videoCapture.get(CAP_PROP_POS_MSEC);
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

    while (videoCapture.isOpened()) {

		cv::Mat frame;
        videoCapture >> frame;

        if (!frame.empty()) {

			int ms = videoCapture.get(CAP_PROP_POS_MSEC);
			int msToEnd = videoLength_ms - ms;
			if (ms == 0) // With OpenCV library, this happens at the last few frames of the video before realising that "frame" is empty.
				break;
			int secToEnd = msToEnd / 1000;
			int minToEnd = (secToEnd / 60) % 60;
			secToEnd = secToEnd % 60;

			std::string secStrToEnd = std::to_string(secToEnd), minStrToEnd = std::to_string(minToEnd);
			if (minToEnd < 10)
				minStrToEnd = "0" + minStrToEnd;
			if (secToEnd < 10)
				secStrToEnd = "0" + secStrToEnd;

			std::cout << "\rIrregularities: " << savedFrames << ".   ";
			std::cout << "Remaining video time [mm:ss]: " << minStrToEnd << ":" << secStrToEnd << std::flush;

			if ((ms - lastSaved > savingRate) && frameDifference(prevFrame, frame, msToEnd)) {
				
				// An Irregularity is found!

				// De-interlacing frame
				cv::Mat oddFrame(frame.rows/2, frame.cols, CV_8UC3);
				cv::Mat evenFrame(frame.rows/2, frame.cols, CV_8UC3);
				separateFrame(frame, oddFrame, evenFrame);

				// Finding an image containing the whole tape
				Point2f pts[4];
284
285
286
287
288
				if (savingPinchRoller)
					rectCapstan.points(pts);
				else
					rectTape.points(pts);
				cv::Mat subImage(frame, cv::Rect(100, min(pts[1].y, pts[2].y), frame.cols - 100, static_cast<int>(rectTape.size.height)));
289
290

				// De-interlacing the image with the whole tape
291
292
293
				cv::Mat oddSubImage(subImage.rows/2, subImage.cols, CV_8UC3);
				int evenSubImageRows = subImage.rows/2;
				if (subImage.rows % 2 != 0) // If the found rectangle is of odd height, we must increase evenSubImage height by 1, otherwise we have segmentation_fault!!!
294
					evenSubImageRows += 1;
295
296
				cv::Mat evenSubImage(evenSubImageRows, subImage.cols, CV_8UC3);
				separateFrame(subImage, oddSubImage, evenSubImage);
297
298
299
300

				std::string timeLabel = getTimeLabel(ms);
				std::string safeTimeLabel = getSafeTimeLabel(ms);

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
301
				saveIrregularityImage(safeTimeLabel, fileName, oddFrame, oddSubImage, savingPinchRoller, savingBrand);
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

				// Append Irregularity information to JSON
				boost::uuids::uuid uuid = boost::uuids::random_generator()();
				irregularityFileOutput1["Irregularities"] += {{
						"IrregularityID", boost::lexical_cast<std::string>(uuid)
					}, {
						"Source", "v"
					}, {
						"TimeLabel", timeLabel
					}
				};
				irregularityFileOutput2["Irregularities"] += {{
						"IrregularityID", boost::lexical_cast<std::string>(uuid)
					}, {
						"Source", "v"
					}, {
						"TimeLabel", timeLabel
					}, {
						"ImageURI", pathTape224 + "/"+ fileName + "_" + safeTimeLabel + ".jpg"
					}
				};

				lastSaved = ms;
				savedFrames++;

			} else {
				unsavedFrames++;
			}

			prevFrame = frame;

	    } else {
			std::cout << "\nEmpty frame!" << std::endl;
	    	videoCapture.release();
	    	break;
	    }
	}

	ofstream myFile;
	myFile.open("log.txt", ios::app);
	myFile << "Saved frames are: " << savedFrames << std::endl;
	myFile.close();

    return 0;

}


Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
350
351
352
bool findProcessingAreas(json configurationFile) {

	/******************************************* JSON PARAMETERS *******************************************/
353
354

	// Read parameters from JSON
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
355
	int minDist, angleThresh, scaleThresh, posThresh, minDistTape, angleThreshTape, scaleThreshTape, posThreshTape, minDistCapstan, angleThreshCapstan, scaleThreshCapstan, posThreshCapstan;
356
357
358
359
360
361
362
363
364
	try {
		minDist = configurationFile["MinDist"];
		angleThresh = configurationFile["AngleThresh"];
		scaleThresh = configurationFile["ScaleThresh"];
		posThresh = configurationFile["PosThresh"];
		minDistTape = configurationFile["MinDistTape"];
		angleThreshTape = configurationFile["AngleThreshTape"];
		scaleThreshTape = configurationFile["ScaleThreshTape"];
		posThreshTape = configurationFile["PosThreshTape"];
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
365
366
367
368
		minDistCapstan = configurationFile["MinDistCapstan"];
		angleThreshCapstan = configurationFile["AngleThreshCapstan"];
		scaleThreshCapstan = configurationFile["ScaleThreshCapstan"];
		posThreshCapstan = configurationFile["PosThreshCapstan"];
369
370
371
372
	} catch (nlohmann::detail::type_error e) {
		std::cerr << "\033[1;31mconfig.json error!\033[0;31m\n" << e.what() << std::endl;
		return -1;
	}
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
373
374
	
	/******************************************* READING HEAD DETECTION *******************************************/
375
376
377
378

	// Obtain grayscale version of myFrame
	Mat myFrameGrayscale;
	cvtColor(myFrame, myFrameGrayscale, COLOR_BGR2GRAY);
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
379
	// Downsample myFrameGrayscale in half pixels for performance reasons
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
	Mat myFrameGrayscaleHalf;
	pyrDown(myFrameGrayscale, myFrameGrayscaleHalf, Size(myFrame.cols/2, myFrame.rows/2));

	// Get input shape in grayscale
	Mat templateImage = imread("../input/readingHead.png", IMREAD_GRAYSCALE);
	// Downsample tapeShape in half pixels
	Mat templateImageHalf;
	pyrDown(templateImage, templateImageHalf, Size(templateImage.cols/2, templateImage.rows/2));

	// Select the image to process
	Mat processingImage = myFrameGrayscaleHalf;
	// Select the template to be detected
	Mat templateShape = templateImageHalf;

	// Algorithm and parameters
	Ptr<GeneralizedHoughGuil> alg = createGeneralizedHoughGuil();

	alg -> setMinDist(minDist);
	alg -> setLevels(360);
	alg -> setDp(2);
	alg -> setMaxBufferSize(1000);

	alg -> setAngleStep(1);
	alg -> setAngleThresh(angleThresh);
	
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
405
406
	alg -> setMinScale(0.9);
	alg -> setMaxScale(1.1);
407
408
409
410
411
412
413
414
415
416
	alg -> setScaleStep(0.1);
	alg -> setScaleThresh(scaleThresh);

	alg -> setPosThresh(posThresh);

	alg -> setCannyLowThresh(100);
	alg -> setCannyHighThresh(300);

	alg -> setTemplate(templateShape);

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
417
418
	vector<Vec4f> positionsPos, positionsNeg;
	Mat votesPos, votesNeg;
419
420
421
    TickMeter tm;
	int oldPosThresh = posThresh;

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
422
	std::cout << "\033[1;36mReading head\033[0m" << endl;
423
	tm.start();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
424
	detectShape(alg, templateShape, posThresh, positionsPos, votesPos, positionsNeg, votesNeg, myFrameGrayscaleHalf);
425
426
	tm.stop();
    std::cout << "Reading head detection time : " << tm.getTimeMilli() << " ms" << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
427
428
	RotatedRect rectPos = drawShapes(myFrame, positionsPos, Scalar(0, 0, 255), templateImageHalf.cols, templateImageHalf.rows, 0, 0, 2);
	RotatedRect rectNeg = drawShapes(myFrame, positionsNeg, Scalar(128, 128, 255), templateImageHalf.cols, templateImageHalf.rows, 0, 0, 2);
429

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
430
431
432
	ofstream myFile;
	myFile.open("log.txt", ios::app);

433
	Point2f pts[4];
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
434
435
436
	if (rectPos.size.width > 0)
		if (rectNeg.size.width > 0)
			if (votesPos.at<int>(0) > votesNeg.at<int>(0)) {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
437
438
				cout << "Positive is best." << endl;
				myFile << "READING HEAD: Positive is best." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
439
440
				rect = rectPos;
			} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
441
442
				cout << "Negative is best." << endl;
				myFile << "READING HEAD: Negative is best." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
443
444
445
446
				rect = rectNeg;
			}
		else {
			cout << "Positive is the only choice." << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
447
			myFile << "READING HEAD: Positive is the only choice." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
448
449
450
451
			rect = rectPos;
		}
	else if (rectNeg.size.width > 0) {
		cout << "Negative is the only choice." << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
452
		myFile << "READING HEAD: Negative is the only choice." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
453
454
		rect = rectNeg;
	} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
455
		myFile.close();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
456
457
458
		return false;
	}
	cout << endl;
459
460
461

	rect.points(pts);

Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
462
	/******************************************* TAPE AREA DETECTION *******************************************/
463
464
465
466
467
468
469
470
471
472
473
474
475
476
	
	// Defining the processing area for identifying the tape under the reading head.
	//
	// Parameters for extracting a rectangle containing the found rectangle completely (also if it is slightly rotated)
	// and with twice its height (since the tape is immediatley below the found rectangle).
	int tapeProcessingAreaX = min(pts[0].x, pts[1].x);
	int tapeProcessingAreaY = min(pts[1].y, pts[2].y) + (max(pts[0].y, pts[3].y) - min(pts[1].y, pts[2].y)) * 2/3; // Shift down the area
	int tapeProcessingAreaWidth = max(pts[3].x-pts[1].x, pts[2].x-pts[0].x);
	int tapeProcessingAreaHeight = max(pts[3].y-pts[1].y, pts[0].y-pts[2].y);

	Rect tapeProcessingAreaRect(tapeProcessingAreaX, tapeProcessingAreaY, tapeProcessingAreaWidth, tapeProcessingAreaHeight);
	// Obtain grayscale version of tapeProcessingArea
	Mat tapeProcessingAreaGrayscale = myFrameGrayscale(tapeProcessingAreaRect);
	// Read template image - it is smaller than before, therefore there is no need to downsample
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
477
	templateShape = imread("../input/tapeArea.png", IMREAD_GRAYSCALE);
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

	// Reset algorithm and set parameters
	alg = createGeneralizedHoughGuil();

	alg -> setMinDist(minDistTape);
	alg -> setLevels(360);
	alg -> setDp(2);
	alg -> setMaxBufferSize(1000);

	alg -> setAngleStep(1);
	alg -> setAngleThresh(angleThreshTape);

	alg -> setMinScale(0.9);
	alg -> setMaxScale(1.1);
	alg -> setScaleStep(0.05);
	alg -> setScaleThresh(scaleThreshTape);

	alg -> setPosThresh(posThreshTape);

	alg -> setCannyLowThresh(100);
	alg -> setCannyHighThresh(300);

Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
500
	alg -> setTemplate(templateShape);
501
502
503

	oldPosThresh = posThreshTape;

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
504
505
506
507
	vector<Vec4f> positionsTapePos, positionsTapeNeg;
	Mat votesTapePos, votesTapeNeg;

	std::cout << "\033[1;36mTape\033[0m" << endl;
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
508
	tm.reset();
509
	tm.start();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
510
	detectShape(alg, templateShape, posThreshTape, positionsTapePos, votesTapePos, positionsTapeNeg, votesTapeNeg, tapeProcessingAreaGrayscale);
511
512
	tm.stop();
    std::cout << "Tape detection time : " << tm.getTimeMilli() << " ms" << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
513
	RotatedRect rectTapePos = drawShapes(myFrame, positionsTapePos, Scalar(0, 255, 0), templateShape.cols, templateShape.rows, tapeProcessingAreaX, tapeProcessingAreaY, 1);
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
514
515
	RotatedRect rectTapeNeg = drawShapes(myFrame, positionsTapeNeg, Scalar(192, 255, 192), templateShape.cols, templateShape.rows, tapeProcessingAreaX, tapeProcessingAreaY, 1);

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
516
517
518
	if (rectTapePos.size.width > 0)
		if (rectTapeNeg.size.width > 0)
			if (votesTapePos.at<int>(0) > votesTapeNeg.at<int>(0)) {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
519
520
				cout << "Positive is best." << endl;
				myFile << "TAPE: Positive is best." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
521
522
				rectTape = rectTapePos;
			} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
523
524
				cout << "Negative is best." << endl;
				myFile << "TAPE: Negative is best." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
525
526
527
528
				rectTape = rectTapeNeg;
			}
		else {
			cout << "Positive is the only choice." << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
529
			myFile << "TAPE: Positive is the only choice." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
530
531
532
533
			rectTape = rectTapePos;
		}
	else if (rectTapeNeg.size.width > 0) {
		cout << "Negative is the only choice." << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
534
		myFile << "TAPE: Negative is the only choice." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
535
536
		rectTape = rectTapeNeg;
	} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
537
		myFile.close();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
538
		return false;
539
	}
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
540
541
542
543
544
545
546
547
548
549
550
551

	if (rectTape.center.y < (rect.center.y + (rect.size.height + rectTape.size.height) * 0.45)) { // 0.45 is an arbitrary value, meaning that they are overlapping too much
		cout << "Shifting down rectTape!" << endl;
		myFile << "Shifting down rectTape!" << std::endl;
		rectTape.center.y = rect.center.y + (rect.size.height + rectTape.size.height) * 0.45;
		Point2f rrpts[4];
		rectTape.points(rrpts);
		line(myFrame, rrpts[0], rrpts[1], Scalar(255, 255, 255), 2);
		line(myFrame, rrpts[1], rrpts[2], Scalar(255, 255, 255), 2);
		line(myFrame, rrpts[2], rrpts[3], Scalar(255, 255, 255), 2);
		line(myFrame, rrpts[3], rrpts[0], Scalar(255, 255, 255), 2);
	}
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
552
	cout << endl;
553

Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
554
555
	/******************************************* CAPSTAN DETECTION *******************************************/

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
556
	// Process only right portion of the image, wherw the capstain always appears
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
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
	int capstanProcessingAreaRectX = myFrame.cols*3/4;
	int capstanProcessingAreaRectY = myFrame.rows/2;
	int capstanProcessingAreaRectWidth = myFrame.cols/4;
	int capstanProcessingAreaRectHeight = myFrame.rows/2;
	Rect capstanProcessingAreaRect(capstanProcessingAreaRectX, capstanProcessingAreaRectY, capstanProcessingAreaRectWidth, capstanProcessingAreaRectHeight);
	Mat capstanProcessingAreaGrayscale = myFrameGrayscale(capstanProcessingAreaRect);
	// Read template image - it is smaller than before, therefore there is no need to downsample
	templateShape = imread("../input/capstanBERIO058prova.png", IMREAD_GRAYSCALE);

	// Reset algorithm and set parameters
	alg = createGeneralizedHoughGuil();

	alg -> setMinDist(minDistCapstan);
	alg -> setLevels(360);
	alg -> setDp(2);
	alg -> setMaxBufferSize(1000);

	alg -> setAngleStep(1);
	alg -> setAngleThresh(angleThreshCapstan);

	alg -> setMinScale(0.9);
	alg -> setMaxScale(1.1);
	alg -> setScaleStep(0.05);
	alg -> setScaleThresh(scaleThreshCapstan);

	alg -> setPosThresh(posThreshCapstan);

	alg -> setCannyLowThresh(100);
	alg -> setCannyHighThresh(250);

	alg -> setTemplate(templateShape);

	oldPosThresh = posThreshCapstan;

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
591
592
	vector<Vec4f> positionsC1Pos, positionsC1Neg;
	Mat votesC1Pos, votesC1Neg;
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
593

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
594
	std::cout << "\033[1;36mCapstan\033[0m" << endl;
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
595
596
	tm.reset();
	tm.start();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
597
	detectShape(alg, templateShape, posThreshCapstan, positionsC1Pos, votesC1Pos, positionsC1Neg, votesC1Neg, capstanProcessingAreaGrayscale);
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
598
599
	tm.stop();
    std::cout << "Capstan detection time : " << tm.getTimeMilli() << " ms" << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
600
601
602
603
604
605
	RotatedRect rectCapstanPos = drawShapes(myFrame, positionsC1Pos, Scalar(255, 0, 0), templateShape.cols-22, templateShape.rows-92, capstanProcessingAreaRectX+11, capstanProcessingAreaRectY+46, 1);
	RotatedRect rectCapstanNeg = drawShapes(myFrame, positionsC1Neg, Scalar(255, 128, 0), templateShape.cols-22, templateShape.rows-92, capstanProcessingAreaRectX+11, capstanProcessingAreaRectY+46, 1);
	
	if (rectCapstanPos.size.width > 0)
		if (rectCapstanNeg.size.width > 0)
			if (votesC1Pos.at<int>(0) > votesC1Neg.at<int>(0)) {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
606
607
				cout << "Positive is best." << endl;
				myFile << "CAPSTAN: Positive is best." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
608
609
				rectCapstan = rectCapstanPos;
			} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
610
611
				cout << "Negative is best." << endl;
				myFile << "CAPSTAN: Negative is best." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
612
613
614
615
				rectCapstan = rectCapstanNeg;
			}
		else {
			cout << "Positive is the only choice." << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
616
			myFile << "CAPSTAN: Positive is the only choice." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
617
618
619
620
			rectCapstan = rectCapstanPos;
		}
	else if (rectTapeNeg.size.width > 0) {
		cout << "Negative is the only choice." << endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
621
		myFile << "CAPSTAN: Negative is the only choice." << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
622
623
		rectCapstan = rectCapstanNeg;
	} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
624
		myFile.close();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
625
626
		return false;
	}
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
627
	myFile.close();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
628
	cout << endl;
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
629

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
630
	// Show the image
631
632
	// imshow("Tape area(s)", myFrame);
	// waitKey();
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
633
634
	// Save the image containing the detected areas
	cv::imwrite(outputPath + "/tapeAreas.jpg", myFrame);
635

636
	return true;
637
638
639
640
641
642
643
644
645
646
647
648
}


int main(int argc, char** argv) {

	/**************************************** CONFIGURATION FILE ****************************************/

	// Read configuration file
	std::ifstream iConfig("../config/config.json");
	iConfig >> configurationFile;
	// Initialise parameters
	try {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
		if (argc == 1) {
			// Read from JSON file
			videoPath = configurationFile["PreservationAudioVisualFile"];
			speed = configurationFile["Speed"];
			brands = configurationFile["Brands"];
		} else if (argc == 4) {
			// Read from command line
			videoPath = argv[1];
			speed = std::stof(argv[2]);
			if (strcmp(argv[3], "true") == 0)
				brands = true;
			else if (strcmp(argv[3], "false") == 0)
				brands = false;
			else {
				std::cerr << "\033[1;31mArguments error!\033[0;31m\nBrands must be 'true' or 'false'."  << std::endl;
				return -1;
			}
		} else {
			std::cerr << "\033[1;31mArguments error!\033[0;31m\nRun with no arguments to use input JSON, or run with argv[1] = 'path/to/input' and argv[2] = 'speed' arguments."  << std::endl;
			return -1;
		}
670
671
		irregularityFileInputPath = configurationFile["IrregularityFileInput"];
		outputPath = configurationFile["OutputPath"];
672
673
		tapeThresholdPercentual = configurationFile["ThresholdPercentualTape"];
		capstanThresholdPercentual = configurationFile["ThresholdPercentualCapstan"];
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
	} catch (nlohmann::detail::type_error e) {
		std::cerr << "\033[1;31mconfig.json error!\033[0;31m\n" << e.what() << std::endl;
		return -1;
	}
	// Input JSON check
	std::ifstream iJSON(irregularityFileInputPath);
	if (iJSON.fail()) {
		std::cerr << "\033[1;31mconfig.json error!\033[0;31m\nIrregularityFileInput.json cannot be found or opened."  << std::endl;
		return -1;
	}
	std::string fileName, extension;
    if (findFileName(videoPath, fileName, extension) == -1) {
        std::cerr << "\033[1;31mconfig.json error!\033[0;31m\nThe PreservationAudioVisualFile cannot be found or opened." << std::endl;
        return -1;
    }
	if (speed != 7.5 && speed != 15) {
		std::cerr << "\033[1;31mconfig.json error!\033[0;31m\nSpeed parameter must be 7.5 or 15 ips."  << std::endl;
		return -1;
	}
693
	if (tapeThresholdPercentual < 0 || tapeThresholdPercentual > 100) {
694
695
696
		std::cerr << "\033[1;31mconfig.json error!\033[0;31m\nThresholdPercentual parameter must be a percentage value."  << std::endl;
		return -1;
	}
697
	if (capstanThresholdPercentual < 0 || capstanThresholdPercentual > 100) {
698
699
700
701
		std::cerr << "\033[1;31mconfig.json error!\033[0;31m\nThresholdPercentual parameter must be a percentage value."  << std::endl;
		return -1;
	}

702
	// Speed reference = 7.5
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
703
704
705
706
707
708
709
710
711
712
	if (brands) {
		if (speed == 15)
			tapeThresholdPercentual += 6;
	} else
		if (speed == 15)
			tapeThresholdPercentual += 20;
		else
			tapeThresholdPercentual += 21;

    std::cout << "\nParameters:" << std::endl;
713
714
	std::cout << "  Brands: " << brands << std::endl;
	std::cout << "  Speed: " << speed << std::endl;
715
716
    std::cout << "  ThresholdPercentual: " << tapeThresholdPercentual << std::endl;
	std::cout << "  ThresholdPercentualCapstan: " << capstanThresholdPercentual << std::endl;
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
717
	std::cout << std::endl;
718
719
720
721

	// Read input JSON
	iJSON >> irregularityFileInput;

Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
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
	/********************************** MAKE GENERIC DIRECTORY **************************************/

	// Get now time
	std::time_t t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
	struct tm *parts = std::localtime(&t);
	int day = parts->tm_mday, month = parts->tm_mon + 1, year = parts->tm_year + 1900, hours = parts->tm_hour, minutes = parts->tm_min, seconds = parts->tm_sec;
	std::string dayStr = std::to_string(day), monthStr = std::to_string(month), yearStr = std::to_string(year), hoursStr = std::to_string(hours), minutesStr = std::to_string(minutes), secondsStr = std::to_string(seconds);
	if (day < 10)
		dayStr = "0" + dayStr;
	if (month < 10)
		monthStr = "0" + monthStr;
	if (hours < 10)
		hoursStr = "0" + hoursStr;
	if (minutes < 10)
		minutesStr = "0" + minutesStr;
	if (seconds < 10)
		secondsStr = "0" + secondsStr;
	// Make directory with fileName name
	int outputFileNameDirectory = fs::create_directory(outputPath + fileName);
	// Update output path
	outputPath += fileName + "/" + yearStr + "-" + monthStr + "-" + dayStr + "_" + hoursStr + "-" + minutesStr + "-" + secondsStr + "/";
	// Create a new directory named as the current time for multiple runs
	int outputNowDirectory = fs::create_directory(outputPath);

	// Get now time
    std::string ts = std::ctime(&t);
	ofstream myFile;
	myFile.open("log.txt", ios::app);
	myFile << endl << fileName << endl;
	myFile << "tsh: " << tapeThresholdPercentual << "   tshp: " << capstanThresholdPercentual << std::endl;
	myFile << ts; // No endline character for avoiding middle blank line.
	myFile.close();

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
	/******************************************* TAPE AREA DETECTION *******************************************/

	cv::VideoCapture videoCapture(videoPath);
    if (!videoCapture.isOpened()) {
        std::cerr << "\033[31m" << "Video unreadable." << std::endl;
        return -1;
    }

	// Get total number of frames
	int totalFrames = videoCapture.get(CAP_PROP_FRAME_COUNT);
	// Set frame position to half video length
	videoCapture.set(CAP_PROP_POS_FRAMES, totalFrames/2);
	// Get frame and show it
	videoCapture >> myFrame;
	
	// Find the processing area corresponding to the tape area over the reading head
Nadir Dalla Pozza's avatar
Nadir Dalla Pozza committed
771
	bool found = findProcessingAreas(configurationFile);
772
773
774
775
776
777
778
779

	// Reset frame position
	videoCapture.set(CAP_PROP_POS_FRAMES, 0);

	/**************************** WRITE USEFUL INFORMATION TO LOG FILE ***************************/

	myFile.open("log.txt", ios::app);
	if (found) {
780
781
		std::cout << "Processing areas found!" << endl;
		myFile << "Processing areas found!" << endl;
782
783
		myFile.close();
	} else {
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
784
		std::cout << "Processing area not found. Try changing JSON parameters." << endl;
785
786
		myFile << "Processing area not found." << endl;
		myFile.close();
787
		return -1; // Program terminated early
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
	}

	/********************************* MAKE REQUIRED DIRECTORIES *********************************/
	
	makeDirectories(fileName, outputPath, brands);

	/**************************************** PROCESSING *****************************************/

	std::cout << "\n\033[32mStarting processing...\033[0m\n" << std::endl;

	// Processing timer
	time_t startTimer, endTimer;
	startTimer = time(NULL);

	processing(videoCapture, fileName);

	endTimer = time(NULL);
	float min = (endTimer - startTimer) / 60;
	float sec = (endTimer - startTimer) % 60;

	std::string result("Processing elapsed time: " + std::to_string((int)min) + ":" + std::to_string((int)sec));
Nadir Dalla Pozza's avatar
Update.    
Nadir Dalla Pozza committed
809
	std::cout << endl << result << endl;
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832

	myFile.open("log.txt", ios::app);
	myFile << result << std::endl << std::endl;
	myFile.close();

	/**************************************** IRREGULARITY FILES ****************************************/

	std::ofstream outputFile1;
	std::string outputFile1Name = outputPath + "IrregularityFileOutput1.json";
	outputFile1.open(outputFile1Name);
	outputFile1 << irregularityFileOutput1 << std::endl;

	// Irregularities to extract for the AudioAnalyser and to the TapeIrregularityClassifier
	extractIrregularityImagesForAudio(outputPath, videoPath, irregularityFileInput, irregularityFileOutput2);

	std::ofstream outputFile2;
	std::string outputFile2Name = outputPath + "IrregularityFileOutput2.json";
	outputFile2.open(outputFile2Name);
	outputFile2 << irregularityFileOutput2 << std::endl;
	
    return 0;

}