tldDetector.cpp 18.8 KB
Newer Older
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

Vladimir's avatar
Vladimir committed
42 43
#include "tldDetector.hpp"

44 45
#include <opencv2/core/utility.hpp>

Vladimir's avatar
Vladimir committed
46 47 48 49 50 51 52 53 54 55 56 57
namespace cv
{
	namespace tld
	{
		// Calculate offsets for classifiers
		void TLDDetector::prepareClassifiers(int rowstep)
		{
			for (int i = 0; i < (int)classifiers.size(); i++)
				classifiers[i].prepareClassifier(rowstep);
		}

		// Calculate posterior probability, that the patch belongs to the current EC model
Vladimir's avatar
Vladimir committed
58
		double TLDDetector::ensembleClassifierNum(const uchar* data)
Vladimir's avatar
Vladimir committed
59 60 61 62 63 64 65 66 67
		{
			double p = 0;
			for (int k = 0; k < (int)classifiers.size(); k++)
				p += classifiers[k].posteriorProbabilityFast(data);
			p /= classifiers.size();
			return p;
		}

		// Calculate Relative similarity of the patch (NN-Model)
68
		double TLDDetector::Sr(const Mat_<uchar>& patch) const
Vladimir's avatar
Vladimir committed
69
		{
70 71 72 73 74 75 76 77 78 79 80 81
			double splus = 0.0, sminus = 0.0;
			Mat_<uchar> modelSample(STANDARD_PATCH_SIZE, STANDARD_PATCH_SIZE);
			for (int i = 0; i < *posNum; i++)
			{
				modelSample.data = &(posExp->data[i * 225]);
				splus = std::max(splus, 0.5 * (NCC(modelSample, patch) + 1.0));
			}
			for (int i = 0; i < *negNum; i++)
			{
				modelSample.data = &(negExp->data[i * 225]);
				sminus = std::max(sminus, 0.5 * (NCC(modelSample, patch) + 1.0));
			}
82

83 84 85 86 87
			if (splus + sminus == 0.0)
				return 0.0;
			return splus / (sminus + splus);
		}

88
#ifdef HAVE_OPENCL
89 90
		double TLDDetector::ocl_Sr(const Mat_<uchar>& patch)
		{
91 92
			double splus = 0.0, sminus = 0.0;

93 94 95 96 97 98

			UMat devPatch = patch.getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devPositiveSamples = posExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devNegativeSamples = negExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devNCC(1, 2*MAX_EXAMPLES_IN_MODEL, CV_32FC1, ACCESS_RW, USAGE_ALLOCATE_DEVICE_MEMORY);

99

100 101 102
			ocl::Kernel k;
			ocl::ProgramSource src = ocl::tracking::tldDetector_oclsrc;
			String error;
103
			ocl::Program prog(src, String(), error);
104 105 106 107 108 109 110 111
			k.create("NCC", prog);
			if (k.empty())
				printf("Kernel create failed!!!\n");
			k.args(
				ocl::KernelArg::PtrReadOnly(devPatch),
				ocl::KernelArg::PtrReadOnly(devPositiveSamples),
				ocl::KernelArg::PtrReadOnly(devNegativeSamples),
				ocl::KernelArg::PtrWriteOnly(devNCC),
112 113
				*posNum,
				*negNum);
114 115

			size_t globSize = 1000;
116

Vladimir's avatar
Vladimir committed
117
			if (!k.run(1, &globSize, NULL, false))
118 119 120
				printf("Kernel Run Error!!!");

			Mat resNCC = devNCC.getMat(ACCESS_READ);
121

122 123 124 125 126 127
			for (int i = 0; i < *posNum; i++)
				splus = std::max(splus, 0.5 * (resNCC.at<float>(i) + 1.0));

			for (int i = 0; i < *negNum; i++)
				sminus = std::max(sminus, 0.5 * (resNCC.at<float>(i+500) +1.0));

Vladimir's avatar
Vladimir committed
128 129 130 131 132
			if (splus + sminus == 0.0)
				return 0.0;
			return splus / (sminus + splus);
		}

133 134 135 136 137 138 139 140 141 142 143
		void TLDDetector::ocl_batchSrSc(const Mat_<uchar>& patches, double *resultSr, double *resultSc, int numOfPatches)
		{
			UMat devPatches = patches.getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devPositiveSamples = posExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devNegativeSamples = negExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devPosNCC(MAX_EXAMPLES_IN_MODEL, numOfPatches, CV_32FC1, ACCESS_RW, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devNegNCC(MAX_EXAMPLES_IN_MODEL, numOfPatches, CV_32FC1, ACCESS_RW, USAGE_ALLOCATE_DEVICE_MEMORY);

			ocl::Kernel k;
			ocl::ProgramSource src = ocl::tracking::tldDetector_oclsrc;
			String error;
144
			ocl::Program prog(src, String(), error);
145 146 147 148 149 150 151 152 153
			k.create("batchNCC", prog);
			if (k.empty())
				printf("Kernel create failed!!!\n");
			k.args(
				ocl::KernelArg::PtrReadOnly(devPatches),
				ocl::KernelArg::PtrReadOnly(devPositiveSamples),
				ocl::KernelArg::PtrReadOnly(devNegativeSamples),
				ocl::KernelArg::PtrWriteOnly(devPosNCC),
				ocl::KernelArg::PtrWriteOnly(devNegNCC),
154 155
				*posNum,
				*negNum,
156 157 158
				numOfPatches);

			size_t globSize = 2 * numOfPatches*MAX_EXAMPLES_IN_MODEL;
159

160
			if (!k.run(1, &globSize, NULL, true))
161 162 163 164 165 166
				printf("Kernel Run Error!!!");

			Mat posNCC = devPosNCC.getMat(ACCESS_READ);
			Mat negNCC = devNegNCC.getMat(ACCESS_READ);

			//Calculate Srs
Vladimir's avatar
Vladimir committed
167
			for (int id = 0; id < numOfPatches; id++)
168 169 170 171 172
			{
				double spr = 0.0, smr = 0.0, spc = 0.0, smc = 0;
				int med = getMedian((*timeStampsPositive));
				for (int i = 0; i < *posNum; i++)
				{
Vladimir's avatar
Vladimir committed
173
					spr = std::max(spr, 0.5 * (posNCC.at<float>(id * 500 + i) + 1.0));
174
					if ((int)(*timeStampsPositive)[i] <= med)
Vladimir's avatar
Vladimir committed
175
						spc = std::max(spr, 0.5 * (posNCC.at<float>(id * 500 + i) + 1.0));
176 177
				}
				for (int i = 0; i < *negNum; i++)
Vladimir's avatar
Vladimir committed
178
					smc = smr = std::max(smr, 0.5 * (negNCC.at<float>(id * 500 + i) + 1.0));
179 180

				if (spr + smr == 0.0)
Vladimir's avatar
Vladimir committed
181
					resultSr[id] = 0.0;
182
				else
Vladimir's avatar
Vladimir committed
183
					resultSr[id] = spr / (smr + spr);
184 185

				if (spc + smc == 0.0)
Vladimir's avatar
Vladimir committed
186
					resultSc[id] = 0.0;
187
				else
Vladimir's avatar
Vladimir committed
188
					resultSc[id] = spc / (smc + spc);
189 190
			}
		}
191
#endif
192

Vladimir's avatar
Vladimir committed
193
		// Calculate Conservative similarity of the patch (NN-Model)
194
		double TLDDetector::Sc(const Mat_<uchar>& patch) const
Vladimir's avatar
Vladimir committed
195
		{
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
			double splus = 0.0, sminus = 0.0;
			Mat_<uchar> modelSample(STANDARD_PATCH_SIZE, STANDARD_PATCH_SIZE);
			int med = getMedian((*timeStampsPositive));
			for (int i = 0; i < *posNum; i++)
			{
				if ((int)(*timeStampsPositive)[i] <= med)
				{
					modelSample.data = &(posExp->data[i * 225]);
					splus = std::max(splus, 0.5 * (NCC(modelSample, patch) + 1.0));
				}
			}
			for (int i = 0; i < *negNum; i++)
			{
				modelSample.data = &(negExp->data[i * 225]);
				sminus = std::max(sminus, 0.5 * (NCC(modelSample, patch) + 1.0));
			}
212

213 214 215 216 217 218
			if (splus + sminus == 0.0)
				return 0.0;

			return splus / (sminus + splus);
		}

219
#ifdef HAVE_OPENCL
220 221 222 223 224 225 226 227 228 229 230 231 232
		double TLDDetector::ocl_Sc(const Mat_<uchar>& patch)
		{
			double splus = 0.0, sminus = 0.0;

			UMat devPatch = patch.getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devPositiveSamples = posExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devNegativeSamples = negExp->getUMat(ACCESS_READ, USAGE_ALLOCATE_DEVICE_MEMORY);
			UMat devNCC(1, 2 * MAX_EXAMPLES_IN_MODEL, CV_32FC1, ACCESS_RW, USAGE_ALLOCATE_DEVICE_MEMORY);


			ocl::Kernel k;
			ocl::ProgramSource src = ocl::tracking::tldDetector_oclsrc;
			String error;
233
			ocl::Program prog(src, String(), error);
234 235 236 237 238 239 240 241
			k.create("NCC", prog);
			if (k.empty())
				printf("Kernel create failed!!!\n");
			k.args(
				ocl::KernelArg::PtrReadOnly(devPatch),
				ocl::KernelArg::PtrReadOnly(devPositiveSamples),
				ocl::KernelArg::PtrReadOnly(devNegativeSamples),
				ocl::KernelArg::PtrWriteOnly(devNCC),
242 243
				*posNum,
				*negNum);
244 245

			size_t globSize = 1000;
246

Vladimir's avatar
Vladimir committed
247
			if (!k.run(1, &globSize, NULL, false))
248 249 250 251 252 253 254 255 256 257 258 259
				printf("Kernel Run Error!!!");

			Mat resNCC = devNCC.getMat(ACCESS_READ);

			int med = getMedian((*timeStampsPositive));
			for (int i = 0; i < *posNum; i++)
				if ((int)(*timeStampsPositive)[i] <= med)
					splus = std::max(splus, 0.5 * (resNCC.at<float>(i) +1.0));

			for (int i = 0; i < *negNum; i++)
				sminus = std::max(sminus, 0.5 * (resNCC.at<float>(i + 500) + 1.0));

Vladimir's avatar
Vladimir committed
260 261 262 263
			if (splus + sminus == 0.0)
				return 0.0;
			return splus / (sminus + splus);
		}
264
#endif // HAVE_OPENCL
Vladimir's avatar
Vladimir committed
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

		// Generate Search Windows for detector from aspect ratio of initial BBs
		void TLDDetector::generateScanGrid(int rows, int cols, Size initBox, std::vector<Rect2d>& res, bool withScaling)
		{
			res.clear();
			//Scales step: SCALE_STEP; Translation steps: 10% of width & 10% of height; minSize: 20pix
			for (double h = initBox.height, w = initBox.width; h < cols && w < rows;)
			{
				for (double x = 0; (x + w + 1.0) <= cols; x += (0.1 * w))
				{
					for (double y = 0; (y + h + 1.0) <= rows; y += (0.1 * h))
						res.push_back(Rect2d(x, y, w, h));
				}
				if (withScaling)
				{
					if (h <= initBox.height)
					{
						h /= SCALE_STEP; w /= SCALE_STEP;
						if (h < 20 || w < 20)
						{
							h = initBox.height * SCALE_STEP; w = initBox.width * SCALE_STEP;
							CV_Assert(h > initBox.height || w > initBox.width);
						}
					}
					else
					{
						h *= SCALE_STEP; w *= SCALE_STEP;
					}
				}
				else
				{
					break;
				}
			}
		}

		//Detection - returns most probable new target location (Max Sc)
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
		class CalcScSrParallelLoopBody: public cv::ParallelLoopBody
		{
		public:
			explicit CalcScSrParallelLoopBody (TLDDetector * detector, Size initSize):
				detectorF (detector),
				initSizeF (initSize)
			{
			}

			virtual void operator () (const cv::Range & r) const
			{
				for (int ind = r.start; ind < r.end; ++ind)
				{
					resample(detectorF->resized_imgs[detectorF->ensScaleIDs[ind]],
						Rect2d(detectorF->ensBuffer[ind], initSizeF),
						detectorF->standardPatches[ind]);

					detectorF->scValues[ind] = detectorF->Sc (detectorF->standardPatches[ind]);
					detectorF->srValues[ind] = detectorF->Sr (detectorF->standardPatches[ind]);
				}
			}

			TLDDetector * detectorF;
			const Size initSizeF;
		private:
			CalcScSrParallelLoopBody (const CalcScSrParallelLoopBody&);
			CalcScSrParallelLoopBody& operator= (const CalcScSrParallelLoopBody&);
		};

Vladimir's avatar
Vladimir committed
332 333 334
		bool TLDDetector::detect(const Mat& img, const Mat& imgBlurred, Rect2d& res, std::vector<LabeledPatch>& patches, Size initSize)
		{
			patches.clear();
335
			Mat tmp;
Vladimir's avatar
Vladimir committed
336 337 338 339
			int dx = initSize.width / 10, dy = initSize.height / 10;
			Size2d size = img.size();
			double scale = 1.0;
			int npos = 0, nneg = 0;
340
			double maxSc = -5.0;
Vladimir's avatar
Vladimir committed
341
			Rect2d maxScRect;
342
			int scaleID;
343 344 345 346 347 348 349

			resized_imgs.clear ();
			blurred_imgs.clear ();
			varBuffer.clear ();
			ensBuffer.clear ();
			varScaleIDs.clear ();
			ensScaleIDs.clear ();
Vladimir's avatar
Vladimir committed
350

Vladimir's avatar
Vladimir committed
351
			//Detection part
352 353 354 355
			//Generate windows and filter by variance
			scaleID = 0;
			resized_imgs.push_back(img);
			blurred_imgs.push_back(imgBlurred);
Vladimir's avatar
Vladimir committed
356 357 358
			do
			{
				Mat_<double> intImgP, intImgP2;
359 360
				computeIntegralImages(resized_imgs[scaleID], intImgP, intImgP2);
				for (int i = 0, imax = cvFloor((0.0 + resized_imgs[scaleID].cols - initSize.width) / dx); i < imax; i++)
Vladimir's avatar
Vladimir committed
361
				{
362
					for (int j = 0, jmax = cvFloor((0.0 + resized_imgs[scaleID].rows - initSize.height) / dy); j < jmax; j++)
Vladimir's avatar
Vladimir committed
363
					{
Vladimir's avatar
Vladimir committed
364
						if (!patchVariance(intImgP, intImgP2, originalVariancePtr, Point(dx * i, dy * j), initSize))
Vladimir's avatar
Vladimir committed
365
							continue;
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
						varBuffer.push_back(Point(dx * i, dy * j));
						varScaleIDs.push_back(scaleID);
					}
				}
				scaleID++;
				size.width /= SCALE_STEP;
				size.height /= SCALE_STEP;
				scale *= SCALE_STEP;
				resize(img, tmp, size, 0, 0, DOWNSCALE_MODE);
				resized_imgs.push_back(tmp);
				GaussianBlur(resized_imgs[scaleID], tmp, GaussBlurKernelSize, 0.0f);
				blurred_imgs.push_back(tmp);
			} while (size.width >= initSize.width && size.height >= initSize.height);

			//Encsemble classification
Vladimir's avatar
Vladimir committed
381
			for (int i = 0; i < (int)varBuffer.size(); i++)
382
			{
Vladimir's avatar
Vladimir committed
383
				prepareClassifiers(static_cast<int> (blurred_imgs[varScaleIDs[i]].step[0]));
384 385 386 387 388 389
				if (ensembleClassifierNum(&blurred_imgs[varScaleIDs[i]].at<uchar>(varBuffer[i].y, varBuffer[i].x)) <= ENSEMBLE_THRESHOLD)
					continue;
				ensBuffer.push_back(varBuffer[i]);
				ensScaleIDs.push_back(varScaleIDs[i]);
			}

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
			//Batch preparation
			srValues.resize (ensBuffer.size());
			scValues.resize (ensBuffer.size());

			//Carefully resize standard patches with reference-counted Mat members
			const int oldPatchesSize = (int)standardPatches.size();
			standardPatches.resize (ensBuffer.size());
			if ((int)ensBuffer.size() > oldPatchesSize)
			{
				Mat_<uchar> standardPatch(STANDARD_PATCH_SIZE, STANDARD_PATCH_SIZE);
				for (int i = oldPatchesSize; i < (int)ensBuffer.size(); ++i)
				{
					standardPatches[i] = standardPatch.clone();
				}
			}

			//Batch calculation
			cv::parallel_for_ (cv::Range (0, (int)ensBuffer.size ()), CalcScSrParallelLoopBody (this, initSize));

409
			//NN classification
Vladimir's avatar
Vladimir committed
410
			for (int i = 0; i < (int)ensBuffer.size(); i++)
411 412 413 414 415
			{
				LabeledPatch labPatch;
				double curScale = pow(SCALE_STEP, ensScaleIDs[i]);
				labPatch.rect = Rect2d(ensBuffer[i].x*curScale, ensBuffer[i].y*curScale, initSize.width * curScale, initSize.height * curScale);

416 417
				const double srValue = srValues[i];
				const double scValue = scValues[i];
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

				////To fix: Check the paper, probably this cause wrong learning
				//
				labPatch.isObject = srValue > THETA_NN;
				labPatch.shouldBeIntegrated = abs(srValue - THETA_NN) < 0.1;
				patches.push_back(labPatch);
				//

				if (!labPatch.isObject)
				{
					nneg++;
					continue;
				}
				else
				{
					npos++;
				}
435

436 437 438 439 440 441
				if (scValue > maxSc)
				{
					maxSc = scValue;
					maxScRect = labPatch.rect;
				}
			}
Vladimir's avatar
Vladimir committed
442

443 444
			if (maxSc < 0)
				return false;
445 446 447 448 449
			else
			{
				res = maxScRect;
				return true;
			}
450
		}
Vladimir's avatar
Vladimir committed
451

452
#ifdef HAVE_OPENCL
453 454 455 456 457 458 459 460 461 462 463 464 465 466
		bool TLDDetector::ocl_detect(const Mat& img, const Mat& imgBlurred, Rect2d& res, std::vector<LabeledPatch>& patches, Size initSize)
		{
			patches.clear();
			Mat_<uchar> standardPatch(STANDARD_PATCH_SIZE, STANDARD_PATCH_SIZE);
			Mat tmp;
			int dx = initSize.width / 10, dy = initSize.height / 10;
			Size2d size = img.size();
			double scale = 1.0;
			int npos = 0, nneg = 0;
			double maxSc = -5.0;
			Rect2d maxScRect;
			int scaleID;
			std::vector <Mat> resized_imgs, blurred_imgs;
			std::vector <Point> varBuffer, ensBuffer;
Vladimir's avatar
Vladimir committed
467
			std::vector <int> varScaleIDs, ensScaleIDs;
Vladimir's avatar
Vladimir committed
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482
			//Detection part
			//Generate windows and filter by variance
			scaleID = 0;
			resized_imgs.push_back(img);
			blurred_imgs.push_back(imgBlurred);
			do
			{
				Mat_<double> intImgP, intImgP2;
				computeIntegralImages(resized_imgs[scaleID], intImgP, intImgP2);
				for (int i = 0, imax = cvFloor((0.0 + resized_imgs[scaleID].cols - initSize.width) / dx); i < imax; i++)
				{
					for (int j = 0, jmax = cvFloor((0.0 + resized_imgs[scaleID].rows - initSize.height) / dy); j < jmax; j++)
					{
						if (!patchVariance(intImgP, intImgP2, originalVariancePtr, Point(dx * i, dy * j), initSize))
Vladimir's avatar
Vladimir committed
483
							continue;
484 485
						varBuffer.push_back(Point(dx * i, dy * j));
						varScaleIDs.push_back(scaleID);
Vladimir's avatar
Vladimir committed
486 487
					}
				}
488
				scaleID++;
Vladimir's avatar
Vladimir committed
489 490 491
				size.width /= SCALE_STEP;
				size.height /= SCALE_STEP;
				scale *= SCALE_STEP;
492 493 494 495
				resize(img, tmp, size, 0, 0, DOWNSCALE_MODE);
				resized_imgs.push_back(tmp);
				GaussianBlur(resized_imgs[scaleID], tmp, GaussBlurKernelSize, 0.0f);
				blurred_imgs.push_back(tmp);
Vladimir's avatar
Vladimir committed
496
			} while (size.width >= initSize.width && size.height >= initSize.height);
497 498

			//Encsemble classification
Vladimir's avatar
Vladimir committed
499
			for (int i = 0; i < (int)varBuffer.size(); i++)
500 501 502 503 504 505 506 507 508 509
			{
				prepareClassifiers((int)blurred_imgs[varScaleIDs[i]].step[0]);
				if (ensembleClassifierNum(&blurred_imgs[varScaleIDs[i]].at<uchar>(varBuffer[i].y, varBuffer[i].x)) <= ENSEMBLE_THRESHOLD)
					continue;
				ensBuffer.push_back(varBuffer[i]);
				ensScaleIDs.push_back(varScaleIDs[i]);
			}

			//NN classification
			//Prepare batch of patches
Vladimir's avatar
Vladimir committed
510
			int numOfPatches = (int)ensBuffer.size();
511 512 513 514 515
			Mat_<uchar> stdPatches(numOfPatches, 225);
			double *resultSr = new double[numOfPatches];
			double *resultSc = new double[numOfPatches];

			uchar *patchesData = stdPatches.data;
Vladimir's avatar
Vladimir committed
516
			for (int i = 0; i < (int)ensBuffer.size(); i++)
517 518 519 520 521 522 523 524 525 526
			{
				resample(resized_imgs[ensScaleIDs[i]], Rect2d(ensBuffer[i], initSize), standardPatch);
				uchar *stdPatchData = standardPatch.data;
				for (int j = 0; j < 225; j++)
					patchesData[225*i+j] = stdPatchData[j];
			}
			//Calculate Sr and Sc batches
			ocl_batchSrSc(stdPatches, resultSr, resultSc, numOfPatches);


Vladimir's avatar
Vladimir committed
527
			for (int i = 0; i < (int)ensBuffer.size(); i++)
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
			{
				LabeledPatch labPatch;
				standardPatch.data = &stdPatches.data[225 * i];
				double curScale = pow(SCALE_STEP, ensScaleIDs[i]);
				labPatch.rect = Rect2d(ensBuffer[i].x*curScale, ensBuffer[i].y*curScale, initSize.width * curScale, initSize.height * curScale);

				double srValue, scValue;

				srValue = resultSr[i];

				////To fix: Check the paper, probably this cause wrong learning
				//
				labPatch.isObject = srValue > THETA_NN;
				labPatch.shouldBeIntegrated = abs(srValue - THETA_NN) < 0.1;
				patches.push_back(labPatch);
				//

				if (!labPatch.isObject)
				{
					nneg++;
					continue;
				}
				else
				{
					npos++;
				}
				scValue = resultSc[i];
				if (scValue > maxSc)
				{
					maxSc = scValue;
					maxScRect = labPatch.rect;
				}
			}
Vladimir's avatar
Vladimir committed
561 562 563 564 565 566

			if (maxSc < 0)
				return false;
			res = maxScRect;
			return true;
		}
567
#endif // HAVE_OPENCL
Vladimir's avatar
Vladimir committed
568 569 570

		// Computes the variance of subimage given by box, with the help of two integral
		// images intImgP and intImgP2 (sum of squares), which should be also provided.
Vladimir's avatar
Vladimir committed
571
		bool TLDDetector::patchVariance(Mat_<double>& intImgP, Mat_<double>& intImgP2, double *originalVariance, Point pt, Size size)
Vladimir's avatar
Vladimir committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
		{
			int x = (pt.x), y = (pt.y), width = (size.width), height = (size.height);
			CV_Assert(0 <= x && (x + width) < intImgP.cols && (x + width) < intImgP2.cols);
			CV_Assert(0 <= y && (y + height) < intImgP.rows && (y + height) < intImgP2.rows);
			double p = 0, p2 = 0;
			double A, B, C, D;

			A = intImgP(y, x);
			B = intImgP(y, x + width);
			C = intImgP(y + height, x);
			D = intImgP(y + height, x + width);
			p = (A + D - B - C) / (width * height);

			A = intImgP2(y, x);
			B = intImgP2(y, x + width);
			C = intImgP2(y + height, x);
			D = intImgP2(y + height, x + width);
			p2 = (A + D - B - C) / (width * height);

Vladimir's avatar
Vladimir committed
591
			return ((p2 - p * p) > VARIANCE_THRESHOLD * *originalVariance);
Vladimir's avatar
Vladimir committed
592 593 594
		}

	}
595
}