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
|
//##########################################################################
//# #
//# CLOUDCOMPARE PLUGIN: q3DMASC #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: Dimitri Lague / CNRS / UEB #
//# #
//##########################################################################
#include "q3DMASCClassifier.h"
//Local
#include "ScalarFieldWrappers.h"
#include "q3DMASCTools.h"
//qCC_db
#include <ccPointCloud.h>
#include <ccScalarField.h>
#include <ccProgressDialog.h>
#include <ccLog.h>
//qPDALIO
#include "../../../core/IO/qPDALIO/include/LASFields.h"
//CCPluginAPI
#include <ccMainAppInterface.h>
//Qt
#include <QCoreApplication>
#include <QProgressDialog>
#include <QtConcurrent>
#include <QMessageBox>
#include "qTrain3DMASCDialog.h"
#include "confusionmatrix.h"
#if defined(_OPENMP)
#include <omp.h>
#endif
#if defined(CC_MAC_OS) || defined(CC_LINUX)
#include <unistd.h>
#endif
using namespace masc;
Classifier::Classifier()
{
}
bool Classifier::isValid() const
{
return (m_rtrees && m_rtrees->isClassifier() && m_rtrees->isTrained());
}
static IScalarFieldWrapper::Shared GetSource(const Feature::Source& fs, const ccPointCloud* cloud)
{
IScalarFieldWrapper::Shared source(nullptr);
switch (fs.type)
{
case Feature::Source::ScalarField:
{
assert(!fs.name.isEmpty());
int sfIdx = cloud->getScalarFieldIndexByName(qPrintable(fs.name));
if (sfIdx >= 0)
{
source.reset(new ScalarFieldWrapper(cloud->getScalarField(sfIdx)));
}
else
{
ccLog::Warning(QObject::tr("Internal error: unknown scalar field '%1'").arg(fs.name));
return IScalarFieldWrapper::Shared(nullptr);
}
}
break;
case Feature::Source::DimX:
source.reset(new DimScalarFieldWrapper(cloud, DimScalarFieldWrapper::DimX));
break;
case Feature::Source::DimY:
source.reset(new DimScalarFieldWrapper(cloud, DimScalarFieldWrapper::DimY));
break;
case Feature::Source::DimZ:
source.reset(new DimScalarFieldWrapper(cloud, DimScalarFieldWrapper::DimZ));
break;
case Feature::Source::Red:
source.reset(new ColorScalarFieldWrapper(cloud, ColorScalarFieldWrapper::Red));
break;
case Feature::Source::Green:
source.reset(new ColorScalarFieldWrapper(cloud, ColorScalarFieldWrapper::Green));
break;
case Feature::Source::Blue:
source.reset(new ColorScalarFieldWrapper(cloud, ColorScalarFieldWrapper::Blue));
break;
}
return source;
}
bool Classifier::classify( const Feature::Source::Set& featureSources,
ccPointCloud* cloud,
QString& errorMessage,
QWidget* parentWidget/*=nullptr*/,
ccMainAppInterface* app/*nullptr*/
)
{
if (!cloud)
{
assert(false);
errorMessage = QObject::tr("Invalid input");
return false;
}
if (!isValid())
{
errorMessage = QObject::tr("Invalid classifier");
return false;
}
if (featureSources.empty())
{
errorMessage = QObject::tr("Training method called without any feature (source)?!");
return false;
}
// add a ccConfidence value if needed
int cvConfidenceIdx = cloud->getScalarFieldIndexByName("Classification_confidence");
if (cvConfidenceIdx >= 0) // if the scalar field exists, delete it
cloud->deleteScalarField(cvConfidenceIdx);
cvConfidenceIdx = cloud->addScalarField("Classification_confidence");
ccScalarField* cvConfidenceSF = static_cast<ccScalarField*>(cloud->getScalarField(cvConfidenceIdx));
//look for the classification field
CCCoreLib::ScalarField* classificationSF = Tools::GetClassificationSF(cloud);
ccScalarField* classifSFBackup = nullptr;
if (classificationSF) //save classification field (if any) by renaming it "Classification_backup"
{
ccLog::Warning("Classification SF found: copy it in Classification_backup, a confusion matrix will be generated");
// delete Classification_backup field (if any)
int sfIdx = cloud->getScalarFieldIndexByName("Classification_backup");
if (sfIdx >= 0)
cloud->deleteScalarField(sfIdx);
classificationSF->setName("Classification_backup"); // rename the classification field
classifSFBackup = static_cast<ccScalarField*>(classificationSF);
}
//create the classification SF
ccScalarField* _classificationSF = new ccScalarField(LAS_FIELD_NAMES[LAS_CLASSIFICATION]);
if (!_classificationSF->resizeSafe(cloud->size()))
{
_classificationSF->release();
errorMessage = QObject::tr("Not enough memory");
return false;
}
cloud->addScalarField(_classificationSF);
classificationSF = _classificationSF;
assert(classificationSF);
classificationSF->fill(0); //0 = no classification?
int sampleCount = static_cast<int>(cloud->size());
int attributesPerSample = static_cast<int>(featureSources.size());
ccLog::Print(QObject::tr("[3DMASC] Classifying %1 points with %2 feature(s)").arg(sampleCount).arg(attributesPerSample));
//create the field wrappers
std::vector< IScalarFieldWrapper::Shared > wrappers;
{
wrappers.reserve(attributesPerSample);
for (int fIndex = 0; fIndex < attributesPerSample; ++fIndex)
{
const Feature::Source& fs = featureSources[fIndex];
IScalarFieldWrapper::Shared source = GetSource(fs, cloud);
if (!source || !source->isValid())
{
assert(false);
errorMessage = QObject::tr("Internal error: invalid source '%1'").arg(fs.name);
return false;
}
wrappers.push_back(source);
}
}
QScopedPointer<ccProgressDialog> pDlg;
if (parentWidget)
{
pDlg.reset(new ccProgressDialog(parentWidget));
pDlg->setLabelText(QString("Classify (%1 points)").arg(sampleCount));
pDlg->show();
QCoreApplication::processEvents();
}
CCCoreLib::NormalizedProgress nProgress(pDlg.data(), cloud->size());
bool success = true;
int numberOfTrees = static_cast<int>(m_rtrees->getRoots().size());
bool cancelled = false;
#ifndef _DEBUG
#if defined(_OPENMP)
#pragma omp parallel for num_threads(omp_get_max_threads() - 2)
#endif
#endif
for (int i = 0; i < static_cast<int>(cloud->size()); ++i)
{
{
//allocate the data matrix
cv::Mat test_data;
try
{
test_data.create(1, attributesPerSample, CV_32FC1);
}
catch (const cv::Exception& cvex)
{
errorMessage = cvex.msg.c_str();
success = false;
cancelled = true;
}
if (!cancelled)
{
for (int fIndex = 0; fIndex < attributesPerSample; ++fIndex)
{
double value = wrappers[fIndex]->pointValue(i);
test_data.at<float>(0, fIndex) = static_cast<float>(value);
}
float predictedClass = m_rtrees->predict(test_data.row(0), cv::noArray(), cv::ml::DTrees::PREDICT_MAX_VOTE);
classificationSF->setValue(i, static_cast<int>(predictedClass));
// compute the confidence
cv::Mat result;
m_rtrees->getVotes(test_data, result, cv::ml::DTrees::PREDICT_MAX_VOTE);
int classIndex = -1;
for (int col = 0; col < result.cols; col++) // look for the index of the predicted class
if (predictedClass == result.at<int>(0, col))
{
classIndex = col;
break;
}
if (classIndex != -1)
{
float nbVotes = result.at<int>(1, classIndex); // get the number of votes
cvConfidenceSF->setValue(i, static_cast<ScalarType>(nbVotes / numberOfTrees)); // compute the confidence
}
else
cvConfidenceSF->setValue(i, CCCoreLib::NAN_VALUE);
if (pDlg && !nProgress.oneStep())
{
//process cancelled by the user
success = false;
cancelled = true;
}
}
}
}
classificationSF->computeMinAndMax();
cvConfidenceSF->computeMinAndMax();
//show the classification field by default
{
int classifSFIdx = cloud->getScalarFieldIndexByName(classificationSF->getName());
cloud->setCurrentDisplayedScalarField(classifSFIdx);
cloud->showSF(true);
}
if (parentWidget && cloud->getDisplay())
{
cloud->getDisplay()->redraw();
QCoreApplication::processEvents();
}
if (classifSFBackup != nullptr)
{
if (app)
{
ConfusionMatrix *confusionMatrix = new ConfusionMatrix(*classifSFBackup, *classificationSF);
}
}
return success;
}
bool Classifier::evaluate(const Feature::Source::Set& featureSources,
ccPointCloud* testCloud,
AccuracyMetrics& metrics,
QString& errorMessage,
Train3DMASCDialog& train3DMASCDialog,
CCCoreLib::ReferenceCloud* testSubset/*=nullptr=*/,
QString outputSFName/*=QString()*/,
QWidget* parentWidget/*=nullptr*/,
ccMainAppInterface *app/*=nullptr*/)
{
if (!testCloud)
{
//invalid input
assert(false);
errorMessage = QObject::tr("Invalid input cloud");
return false;
}
metrics.sampleCount = metrics.goodGuess = 0;
metrics.ratio = 0.0f;
if (!m_rtrees || !m_rtrees->isTrained())
{
errorMessage = QObject::tr("Classifier hasn't been trained yet");
return false;
}
if (featureSources.empty())
{
errorMessage = QObject::tr("Training method called without any feature (source)?!");
return false;
}
if (testSubset && testSubset->getAssociatedCloud() != testCloud)
{
errorMessage = QObject::tr("Invalid test subset (associated point cloud is different)");
return false;
}
//look for the classification field
CCCoreLib::ScalarField* classifSF = Tools::GetClassificationSF(testCloud);
if (!classifSF || classifSF->size() < testCloud->size())
{
assert(false);
errorMessage = QObject::tr("Missing/invalid 'Classification' field on input cloud");
return false;
}
ccScalarField* outSF = nullptr;
ccScalarField* cvConfidenceSF = nullptr;
if (!outputSFName.isEmpty())
{
int outIdx = testCloud->getScalarFieldIndexByName(qPrintable(outputSFName));
if (outIdx >= 0)
testCloud->deleteScalarField(outIdx);
else
ccLog::Print("add " + outputSFName + " to the TEST cloud");
outIdx = testCloud->addScalarField(qPrintable(outputSFName));
outSF = static_cast<ccScalarField*>(testCloud->getScalarField(outIdx));
}
if (outSF) // add a Classification_confidence value to the test cloud if needed
{
int cvConfidenceIdx = testCloud->getScalarFieldIndexByName("Classification_confidence");
if (cvConfidenceIdx >= 0) // if the scalar field exists, delete it
testCloud->deleteScalarField(cvConfidenceIdx);
else
ccLog::Print("add Classification_confidence to the TEST cloud");
cvConfidenceIdx = testCloud->addScalarField("Classification_confidence");
cvConfidenceSF = static_cast<ccScalarField*>(testCloud->getScalarField(cvConfidenceIdx));
}
unsigned testSampleCount = (testSubset ? testSubset->size() : testCloud->size());
int attributesPerSample = static_cast<int>(featureSources.size());
ccLog::Print(QObject::tr("[3DMASC] Testing data: %1 samples with %2 feature(s)").arg(testSampleCount).arg(attributesPerSample));
//allocate the data matrix
cv::Mat test_data;
try
{
test_data.create(static_cast<int>(testSampleCount), attributesPerSample, CV_32FC1);
}
catch (const cv::Exception& cvex)
{
errorMessage = cvex.msg.c_str();
return false;
}
QScopedPointer<ccProgressDialog> pDlg;
if (parentWidget)
{
pDlg.reset(new ccProgressDialog(parentWidget));
pDlg->setLabelText(QString("Evaluating the classifier on %1 points").arg(testSampleCount));
pDlg->show();
QCoreApplication::processEvents();
}
CCCoreLib::NormalizedProgress nProgress(pDlg.data(), testSampleCount);
//fill the data matrix
for (int fIndex = 0; fIndex < attributesPerSample; ++fIndex)
{
const Feature::Source& fs = featureSources[fIndex];
IScalarFieldWrapper::Shared source = GetSource(fs, testCloud);
if (!source || !source->isValid())
{
assert(false);
errorMessage = QObject::tr("Internal error: invalid source '%1'").arg(fs.name);
return false;
}
for (unsigned i = 0; i < testSampleCount; ++i)
{
unsigned pointIndex = (testSubset ? testSubset->getPointGlobalIndex(i) : i);
double value = source->pointValue(pointIndex);
test_data.at<float>(i, fIndex) = static_cast<float>(value);
}
}
int numberOfTrees = static_cast<int>(m_rtrees->getRoots().size());
//estimate the efficiency of the classifier
std::vector<ScalarType> actualClass(testSampleCount);
std::vector<ScalarType> predictectedClass(testSampleCount);
{
metrics.sampleCount = testSampleCount;
metrics.goodGuess = 0;
for (unsigned i = 0; i < testSampleCount; ++i)
{
unsigned pointIndex = (testSubset ? testSubset->getPointGlobalIndex(i) : i);
ScalarType pointClass = classifSF->getValue(pointIndex);
int iClass = static_cast<int>(pointClass);
//if (iClass < 0 || iClass > 255)
//{
// errorMessage = QObject::tr("Classification values out of range (0-255)");
// return false;
//}
float fPredictedClass = m_rtrees->predict(test_data.row(i), cv::noArray(), cv::ml::DTrees::PREDICT_MAX_VOTE);
int iPredictedClass = static_cast<int>(fPredictedClass);
actualClass.at(i) = iClass;
predictectedClass.at(i) = iPredictedClass;
if (iPredictedClass == iClass)
{
++metrics.goodGuess;
}
if (outSF)
{
outSF->setValue(pointIndex, static_cast<ScalarType>(iPredictedClass));
if (cvConfidenceSF)
{
// compute the confidence
cv::Mat result;
m_rtrees->getVotes(test_data.row(i), result, cv::ml::DTrees::PREDICT_MAX_VOTE);
int classIndex = -1;
for (int col = 0; col < result.cols; col++) // look for the index of the predicted class
if (iPredictedClass == result.at<int>(0, col))
{
classIndex = col;
break;
}
if (classIndex != -1)
{
float nbVotes = result.at<int>(1, classIndex); // get the number of votes
cvConfidenceSF->setValue(i, static_cast<ScalarType>(nbVotes / numberOfTrees)); // compute the confidence
}
else
cvConfidenceSF->setValue(i, CCCoreLib::NAN_VALUE);
}
}
if (pDlg && !nProgress.oneStep())
{
//process cancelled by the user
return false;
}
}
if (outSF)
outSF->computeMinAndMax();
if (cvConfidenceSF)
cvConfidenceSF->computeMinAndMax();
metrics.ratio = static_cast<float>(metrics.goodGuess) / metrics.sampleCount;
}
ConfusionMatrix* confusionMatrix = new ConfusionMatrix(actualClass, predictectedClass);
train3DMASCDialog.addConfusionMatrixAndSaveTraces(confusionMatrix);
if (app)
{
confusionMatrix->show();
}
//show the Classification_prediction field by default
if (outSF)
{
int classifSFIdx = testCloud->getScalarFieldIndexByName(outSF->getName());
testCloud->setCurrentDisplayedScalarField(classifSFIdx);
testCloud->showSF(true);
}
if (parentWidget && testCloud->getDisplay())
{
testCloud->getDisplay()->redraw();
QCoreApplication::processEvents();
}
return true;
}
bool Classifier::train( const ccPointCloud* cloud,
const RandomTreesParams& params,
const Feature::Source::Set& featureSources,
QString& errorMessage,
CCCoreLib::ReferenceCloud* trainSubset/*=nullptr*/,
ccMainAppInterface* app/*=nullptr*/,
QWidget* parentWidget/*=nullptr*/)
{
if (featureSources.empty())
{
errorMessage = QObject::tr("Training method called without any feature (source)?!");
return false;
}
if (!cloud)
{
errorMessage = QObject::tr("Invalid input cloud");
return false;
}
if (trainSubset && trainSubset->getAssociatedCloud() != cloud)
{
errorMessage = QObject::tr("Invalid train subset (associated point cloud is different)");
return false;
}
//look for the classification field
CCCoreLib::ScalarField* classifSF = Tools::GetClassificationSF(cloud);
if (!classifSF || classifSF->size() < cloud->size())
{
assert(false);
errorMessage = QObject::tr("Missing/invalid 'Classification' field on input cloud");
return false;
}
int sampleCount = static_cast<int>(trainSubset ? trainSubset->size() : cloud->size());
int attributesPerSample = static_cast<int>(featureSources.size());
if (app)
{
app->dispToConsole(QString("[3DMASC] Training data: %1 samples with %2 feature(s)").arg(sampleCount).arg(attributesPerSample));
}
cv::Mat training_data, train_labels;
try
{
training_data.create(sampleCount, attributesPerSample, CV_32FC1);
train_labels.create(sampleCount, 1, CV_32FC1);
}
catch (const cv::Exception& cvex)
{
errorMessage = cvex.msg.c_str();
return false;
}
//fill the classification labels vector
{
for (int i = 0; i < sampleCount; ++i)
{
int pointIndex = (trainSubset ? static_cast<int>(trainSubset->getPointGlobalIndex(i)) : i);
ScalarType pointClass = classifSF->getValue(pointIndex);
int iClass = static_cast<int>(pointClass);
//if (iClass < 0 || iClass > 255)
//{
// errorMessage = QObject::tr("Classification values out of range (0-255)");
// return false;
//}
train_labels.at<float>(i) = static_cast<unsigned char>(iClass);
}
}
//fill the training data matrix
for (int fIndex = 0; fIndex < attributesPerSample; ++fIndex)
{
const Feature::Source& fs = featureSources[fIndex];
IScalarFieldWrapper::Shared source = GetSource(fs, cloud);
if (!source || !source->isValid())
{
assert(false);
errorMessage = QObject::tr("Internal error: invalid source '%1'").arg(fs.name);
return false;
}
for (int i = 0; i < sampleCount; ++i)
{
int pointIndex = (trainSubset ? static_cast<int>(trainSubset->getPointGlobalIndex(i)) : i);
double value = source->pointValue(pointIndex);
training_data.at<float>(i, fIndex) = static_cast<float>(value);
}
}
QScopedPointer<QProgressDialog> pDlg;
if (parentWidget)
{
pDlg.reset(new QProgressDialog(parentWidget));
pDlg->setRange(0, 0); //infinite loop
pDlg->setLabelText("Training classifier");
pDlg->show();
QCoreApplication::processEvents();
}
m_rtrees = cv::ml::RTrees::create();
m_rtrees->setMaxDepth(params.maxDepth);
m_rtrees->setMinSampleCount(params.minSampleCount);
m_rtrees->setRegressionAccuracy(0);
// If true then surrogate splits will be built. These splits allow to work with missing data and compute variable importance correctly. Default value is false.
m_rtrees->setUseSurrogates(false);
m_rtrees->setPriors(cv::Mat());
//m_rtrees->setMaxCategories(params.maxCategories); //not important?
m_rtrees->setCalculateVarImportance(true);
m_rtrees->setActiveVarCount(params.activeVarCount);
cv::TermCriteria terminationCriteria(cv::TermCriteria::MAX_ITER, params.maxTreeCount, std::numeric_limits<double>::epsilon());
m_rtrees->setTermCriteria(terminationCriteria);
QFuture<bool> future = QtConcurrent::run([&]()
{
// Code in this block will run in another thread
try
{
cv::Mat sampleIndexes = cv::Mat::zeros(1, training_data.rows, CV_8U);
// cv::Mat trainSamples = sampleIndexes.colRange(0, sampleCount);
// trainSamples.setTo(cv::Scalar::all(1));
cv::Mat varTypes(training_data.cols + 1, 1, CV_8U);
varTypes.setTo(cv::Scalar::all(cv::ml::VAR_ORDERED));
varTypes.at<uchar>(training_data.cols) = cv::ml::VAR_CATEGORICAL;
cv::Ptr<cv::ml::TrainData> trainData = cv::ml::TrainData::create(training_data, cv::ml::ROW_SAMPLE, train_labels, /* samples layout responses */
cv::noArray(), sampleIndexes, /* varIdx sampleIdx */
cv::noArray(), varTypes); // sampleWeights varType
bool success = m_rtrees->train(trainData);
if (!success || !m_rtrees->isClassifier())
{
errorMessage = "Training failed";
return false;
}
}
catch (const cv::Exception& cvex)
{
m_rtrees.release();
errorMessage = cvex.msg.c_str();
return false;
}
catch (const std::exception& stdex)
{
errorMessage = stdex.what();
return false;
}
catch (...)
{
errorMessage = QObject::tr("Unknown error");
return false;
}
return true;
});
while (!future.isFinished())
{
#if defined(CC_WINDOWS)
::Sleep(500);
#else
usleep(500 * 1000);
#endif
if (pDlg)
{
if (pDlg->wasCanceled())
{
// future.cancel();
QMessageBox msgBox;
msgBox.setText("The training is still in progress, not possible to cancel.");
msgBox.exec();
// break;
pDlg->reset();
pDlg->show();
}
pDlg->setValue(pDlg->value() + 1);
}
QCoreApplication::processEvents();
}
if (pDlg)
{
pDlg->close();
QCoreApplication::processEvents();
}
if (future.isCanceled() || !future.result() || !m_rtrees->isTrained())
{
errorMessage = QObject::tr("Training failed for an unknown reason...");
m_rtrees.release();
return false;
}
return true;
}
bool Classifier::toFile(QString filename, QWidget* parentWidget/*=nullptr*/) const
{
if (!m_rtrees)
{
ccLog::Warning(QObject::tr("Classifier hasn't been trained, can't save it"));
return false;
}
//save the classifier
QProgressDialog pDlg(parentWidget);
pDlg.setRange(0, 0); //infinite loop
pDlg.setLabelText(QObject::tr("Saving classifier"));
pDlg.show();
QCoreApplication::processEvents();
cv::String cvFilename = filename.toStdString();
m_rtrees->save(cvFilename);
pDlg.close();
QCoreApplication::processEvents();
ccLog::Print("Classifier file saved to: " + QString::fromStdString(cvFilename));
return true;
}
bool Classifier::fromFile(QString filename, QWidget* parentWidget/*=nullptr*/)
{
//load the classifier
QScopedPointer<QProgressDialog> pDlg;
if (parentWidget)
{
pDlg.reset(new QProgressDialog(parentWidget));
pDlg->setRange(0, 0); //infinite loop
pDlg->setLabelText(QObject::tr("Loading classifier"));
pDlg->show();
QCoreApplication::processEvents();
}
try
{
m_rtrees = cv::ml::RTrees::load(filename.toStdString());
}
catch (const cv::Exception& cvex)
{
ccLog::Warning(cvex.msg.c_str());
ccLog::Error("Failed to load file: " + filename);
return false;
}
if (pDlg)
{
pDlg->close();
QCoreApplication::processEvents();
}
if (m_rtrees->empty() || !m_rtrees->isClassifier())
{
ccLog::Error(QObject::tr("Loaded classifier is invalid"));
return false;
}
else if (!m_rtrees->isTrained())
{
ccLog::Warning(QObject::tr("Loaded classifier doesn't seem to be trained"));
}
return true;
}
|