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 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
|
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
Some parts of this code are derived from ITK. See ITKCopyright.txt
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef otbBandMathXImageFilter_txx
#define otbBandMathXImageFilter_txx
#include "otbBandMathXImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"
#include "itkImageScanlineConstIterator.h"
#include "itkImageScanlineIterator.h"
#include "itkImageRegionConstIteratorWithOnlyIndex.h"
#include "itkConstNeighborhoodIterator.h"
#include "itkNumericTraits.h"
#include "itkProgressReporter.h"
#include "otbMacro.h"
#include <iostream>
#include <fstream>
#include <string>
namespace otb
{
/** Constructor */
template <class TImage>
BandMathXImageFilter<TImage>
::BandMathXImageFilter()
{
//This number will be incremented each time an image
//is added over the one minimumrequired
this->SetNumberOfRequiredInputs( 1 );
m_UnderflowCount = 0;
m_OverflowCount = 0;
m_ThreadUnderflow.SetSize(1);
m_ThreadOverflow.SetSize(1);
//idxX and idxY
adhocStruct ahcX;
ahcX.name = "idxX";
ahcX.type = 0;
m_VAllowedVarNameAuto.push_back(ahcX);
adhocStruct ahcY;
ahcY.name = "idxY";
ahcY.type = 1;
m_VAllowedVarNameAuto.push_back(ahcY);
m_SizeNeighbourhood=10;
m_ManyExpressions = true;
}
/** Destructor */
template <class TImage>
BandMathXImageFilter<TImage>
::~BandMathXImageFilter()
{
m_Expression.clear();
m_VParser.clear();
for(unsigned int i=0; i<m_AImage.size(); ++i)
m_AImage[i].clear();
m_AImage.clear();
m_VVarName.clear();
m_VAllowedVarNameAuto.clear();
m_VAllowedVarNameAddedByUser.clear();
m_VFinalAllowedVarName.clear();
m_VNotAllowedVarName.clear();
m_outputsDimensions.clear();
}
template <class TImage>
void BandMathXImageFilter<TImage>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Expressions: " << std::endl;
for (unsigned int i=0; i<m_Expression.size(); i++)
os << indent << m_Expression[i] << std::endl;
os << indent << "Computed values follow:" << std::endl;
os << indent << "UnderflowCount: " << m_UnderflowCount << std::endl;
os << indent << "OverflowCount: " << m_OverflowCount << std::endl;
os << indent << "itk::NumericTraits<typename PixelValueType>::NonpositiveMin() : "
<< itk::NumericTraits<PixelValueType>::NonpositiveMin() << std::endl;
os << indent << "itk::NumericTraits<typename PixelValueType>::max() : "
<< itk::NumericTraits<PixelValueType>::max() << std::endl;
}
template <class TImage>
void BandMathXImageFilter<TImage>
::SetNthInput(DataObjectPointerArraySizeType idx, const ImageType * image)
{
std::stringstream sstm;
sstm << "im" << (idx+1);
this->SetNthInput(idx, image, sstm.str());
}
template <class TImage>
void BandMathXImageFilter<TImage>
::SetNthInput(DataObjectPointerArraySizeType idx, const ImageType * image, const std::string& varName)
{
ImageType * imagebis = const_cast<ImageType *>( image ); // Useful for call of UpdateOutputInformation() (see below)
this->SetInput(idx, imagebis );
//imiPhyX and imiPhyY
std::stringstream sstmPhyX;
adhocStruct ahcPhyX;
sstmPhyX << varName << "PhyX";
ahcPhyX.name = sstmPhyX.str();
ahcPhyX.type = 2;
ahcPhyX.info[0] = idx; // Input image #ID
m_VAllowedVarNameAuto.push_back(ahcPhyX);
std::stringstream sstmPhyY;
adhocStruct ahcPhyY;
sstmPhyY << varName << "PhyY";
ahcPhyY.name = sstmPhyY.str();
ahcPhyY.type = 3;
ahcPhyY.info[0] = idx; // Input image #ID
m_VAllowedVarNameAuto.push_back(ahcPhyY);
//imi
std::stringstream sstm_glob;
adhocStruct ahc_glob;
sstm_glob << varName;
ahc_glob.name = sstm_glob.str();
ahc_glob.type = 4;
ahc_glob.info[0] = idx; // Input image #ID
m_VAllowedVarNameAuto.push_back(ahc_glob);
//Mandatory before call of GetNumberOfComponentsPerPixel
//Really important not to call the filter's UpdateOutputInformation method here:
//this method is not ready until all inputs, variables and expressions are set.
imagebis->UpdateOutputInformation();
//imibj
for (unsigned int j=0; j<imagebis->GetNumberOfComponentsPerPixel(); j++)
{
std::stringstream sstm;
adhocStruct ahc;
sstm << varName << "b" << (j+1);
ahc.name = sstm.str();
ahc.type = 5;
ahc.info[0] = idx; // Input image #ID
ahc.info[1] = j; // Band #ID
m_VAllowedVarNameAuto.push_back(ahc);
}
//imibjNkxp
for (unsigned int j=0; j<imagebis->GetNumberOfComponentsPerPixel(); j++)
for(unsigned int x=0; x<=m_SizeNeighbourhood; x++)
for(unsigned int y=0; y<=m_SizeNeighbourhood; y++)
{
std::stringstream sstm;
adhocStruct ahc;
sstm << varName << "b" << (j+1) << "N" << 2*x+1 << "x" << 2*y+1;
ahc.name = sstm.str();
ahc.type = 6;
ahc.info[0] = idx; // Input image #ID
ahc.info[1] = j; // Band #ID
ahc.info[2] = 2*x+1; // Size x direction (matrix convention = cols)
ahc.info[3] = 2*y+1; // Size y direction (matrix convention = rows)
m_VAllowedVarNameAuto.push_back(ahc);
}
//imibjSTATS
std::vector< std::string > statsNames;
statsNames.push_back("Mini");
statsNames.push_back("Maxi");
statsNames.push_back("Mean");
statsNames.push_back("Sum");
statsNames.push_back("Var");
for (unsigned int j=0; j<imagebis->GetNumberOfComponentsPerPixel(); j++)
for (unsigned int t=0; t<statsNames.size(); t++)
{
std::stringstream sstm;
adhocStruct ahc;
sstm << varName << "b" << (j+1) << statsNames[t];
ahc.name = sstm.str();
ahc.type = 8;
ahc.info[0] = idx; // Input image #ID
ahc.info[1] = j; // Band #ID
ahc.info[2] = t; // Sub-type : 0 Mini, 1 Maxi, 2 Mean ...
m_VAllowedVarNameAuto.push_back(ahc);
}
}
template <typename TImage>
TImage * BandMathXImageFilter<TImage>
::GetNthInput(DataObjectPointerArraySizeType idx)
{
return const_cast<TImage *>(this->GetInput(idx));
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::SetManyExpressions(bool flag)
{
m_ManyExpressions = flag;
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::SetExpression(const std::string& expression)
{
std::string expressionToBePushed = expression;
if (expression.find(";") != std::string::npos)
{
std::ostringstream oss;
oss << "cat(";
for(unsigned int i=0; i < expression.size(); ++i)
if (expression[i] == ';')
oss << ",";
else
oss << expression[i];
oss << ")";
expressionToBePushed = oss.str();
}
if (m_ManyExpressions)
m_Expression.push_back(expressionToBePushed);
else if (m_Expression.size() == 0)
m_Expression.push_back(expressionToBePushed);
if (m_Expression.size()>1)
this->SetNthOutput( (DataObjectPointerArraySizeType) (m_Expression.size()) -1, ( TImage::New() ).GetPointer() );
this->Modified();
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::SetMatrix(const std::string& name, const std::string& definition)
{
for(unsigned int i=0; i<m_VAllowedVarNameAddedByUser.size(); i++)
if (name.compare(m_VAllowedVarNameAddedByUser[i].name) == 0)
itkExceptionMacro(<< "Variable name '"<< name << "' already used." << std::endl);
if ( (definition.find("{") != 0) || (definition.find("}")) != definition.size()-1 )
itkExceptionMacro(<< "Definition of a matrix must begin with { and end with } characters." << std::endl);
//Get rid of { and } characters
std::string def;
for(unsigned int i=1; i<definition.size()-1; ++i)
def.push_back(definition[i]);
std::vector< std::vector<double> > mat;
std::istringstream iss( def );
std::string rows;
while (std::getline( iss, rows, ';' ) )
{
mat.push_back(std::vector<double>(0));
std::istringstream iss2( rows );
std::string elmt;
while (std::getline( iss2, elmt, ',' ) )
{
std::istringstream iss3( elmt );
double val;
iss3 >> val;
mat.back().push_back(val);
}
}
//Check dimensions of the matrix
for (unsigned int i=0; i<mat.size()-1; i++)
if (mat[i].size() != mat[i+1].size())
itkExceptionMacro(<< "Each row must have the same number of cols : " << definition << std::endl);
//Registration
adhocStruct ahc;
ahc.name = name;
ahc.type = 7;
ahc.info[0] = mat[0].size(); // Size x direction (matrix convention = cols)
ahc.info[1] = mat.size(); // Size y direction (matrix convention = rows)
ahc.value = ValueType(ahc.info[1],ahc.info[0],0.0);
for(unsigned int i=0; i<mat.size(); i++)
for(unsigned int j=0; j<mat[i].size(); j++)
ahc.value.At(i,j)=mat[i][j];
m_VAllowedVarNameAddedByUser.push_back(ahc);
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::SetConstant(const std::string& name, double value)
{
for(unsigned int i=0; i<m_VAllowedVarNameAddedByUser.size(); i++)
if (name.compare(m_VAllowedVarNameAddedByUser[i].name) == 0)
itkExceptionMacro(<< "Variable name '"<< name << "' already used." << std::endl);
adhocStruct ahc;
ahc.name = name;
ahc.type = 7;
ahc.value = value;
m_VAllowedVarNameAddedByUser.push_back(ahc);
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::ExportContext(const std::string& filename)
{
std::vector< std::string > vectI,vectF,vectM, vectFinal;
for(unsigned int i=0; i<m_VAllowedVarNameAddedByUser.size(); i++)
{
std::ostringstream iss;
std::string str;
switch (m_VAllowedVarNameAddedByUser[i].value.GetType())
{
case 'i':
iss << "#I " << m_VAllowedVarNameAddedByUser[i].name << " " << m_VAllowedVarNameAddedByUser[i].value.GetInteger();
str=iss.str();
vectI.push_back(str);
break;
case 'f':
iss << "#F " << m_VAllowedVarNameAddedByUser[i].name << " " << m_VAllowedVarNameAddedByUser[i].value.GetFloat();
str=iss.str();
vectF.push_back(str);
break;
case 'c':
itkExceptionMacro(<< "Complex numbers not supported." << std::endl);
break;
case 'm':
iss << "#M " << m_VAllowedVarNameAddedByUser[i].name << " " << "{";
for(int k=0; k<m_VAllowedVarNameAddedByUser[i].value.GetRows(); k++)
{
iss << " " << m_VAllowedVarNameAddedByUser[i].value.At(k,0);
for(int p=1; p<m_VAllowedVarNameAddedByUser[i].value.GetCols(); p++)
iss << " , " << m_VAllowedVarNameAddedByUser[i].value.At(k,p);
iss << ";";
}
str=iss.str();
str.erase(str.size()-1);
str.push_back('}');
vectM.push_back(str);
break;
}
}
// Sorting : I F M and E
for(unsigned int i=0; i<vectI.size(); ++i)
vectFinal.push_back(vectI[i]);
for(unsigned int i=0; i<vectF.size(); ++i)
vectFinal.push_back(vectF[i]);
for(unsigned int i=0; i<vectM.size(); ++i)
vectFinal.push_back(vectM[i]);
for(unsigned int i=0; i < m_Expression.size(); ++i)
{
std::ostringstream iss;
iss << "#E " << m_Expression[i] << std::endl;
std::string str=iss.str();
vectFinal.push_back(str);
}
std::ofstream exportFile(filename.c_str(), std::ios::out | std::ios::trunc);
if(exportFile)
{
for(unsigned int i=0; i<vectFinal.size(); ++i)
exportFile << vectFinal[i] << std::endl;
exportFile.close();
}
else
itkExceptionMacro(<< "Could not open " << filename << "." << std::endl);
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::ImportContext(const std::string& filename)
{
std::ifstream importFile(filename.c_str(), std::ios::in);
std::string wholeline,line,name,matrixdef;
int pos,pos2,lineID=0,nbSuccesses=0;
double value;
if(importFile)
{
while(std::getline(importFile,wholeline))
{
lineID++;
pos = wholeline.find_first_not_of(' ');
if (pos != (int) std::string::npos)
{
line = wholeline.substr(pos);
if ( (line[0] == '#') && ((line[1] == 'I') || (line[1] == 'i') || (line[1] == 'F') || (line[1] == 'f')) )
{
pos = line.find_first_not_of(' ',2);
if (pos == (int) std::string::npos)
itkExceptionMacro(<< "In file '"<< filename << "', line " << lineID << " : please, set the name and the value of the constant." << std::endl);
std::string sub = line.substr(pos);
pos = sub.find_first_of(' ');
name = sub.substr(0,pos);
if (sub.find_first_of('{',pos) != std::string::npos)
itkExceptionMacro(<< "In file '"<< filename << "', line " << lineID
<< " : symbol #F found, but find vector/matrix definition. Please, set an integer or a float number." << std::endl);
if (sub.find_first_not_of(' ',pos) == std::string::npos )
itkExceptionMacro(<< "In file '"<< filename << "', line " << lineID << " : please, set the value of the constant." << std::endl)
std::istringstream iss( sub.substr(pos) );
iss >> value;
SetConstant(name,value);
nbSuccesses++;
}
else if ( (line[0] == '#') && ((line[1] == 'M') || (line[1] == 'm')) )
{
pos = line.find_first_not_of(' ',2);
if (pos == (int) std::string::npos)
itkExceptionMacro(<< "In file '"<< filename << "', line " << lineID << " : please, set the name and the definition of the vector/matrix." << std::endl);
std::string sub = line.substr(pos);
pos = sub.find_first_of(' ');
name = sub.substr(0,pos);
pos2 = sub.find_first_of('{');
if (pos2 != (int) std::string::npos)
matrixdef = sub.substr(pos2);
else
itkExceptionMacro(<< "In file '"<< filename << "', line " << lineID << " : symbol #M found, but couldn't not find vector/matrix definition." << std::endl);
SetMatrix(name,matrixdef);
nbSuccesses++;
}
else if ( (line[0] == '#') && ((line[1] == 'E') || (line[1] == 'e')) )
{
pos = line.find_first_not_of(' ',2);
if (pos == (int) std::string::npos)
itkExceptionMacro(<< "In file '"<< filename << "', line " << lineID << " : symbol #E found, but couldn't not find any expression." << std::endl);
std::string sub = line.substr(pos);
SetExpression(sub);
nbSuccesses++;
}
}
}//while
importFile.close();
if (nbSuccesses == 0)
itkExceptionMacro(<< "No constant or expression could be set; please, ensure that the file '" << filename << "' is correct." << std::endl);
}
else
itkExceptionMacro(<< "Could not open " << filename << "." << std::endl);
}
template< typename TImage >
std::string BandMathXImageFilter<TImage>
::GetExpression(int IDExpression) const
{
return m_Expression[IDExpression];
}
template< typename TImage >
std::vector<std::string> BandMathXImageFilter<TImage>
::GetVarNames() const
{
std::vector<std::string> res;
for(int y=0; y<m_VVarName.size(); y++)
res.push_back(m_VVarName[y].name);
return res;
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::AddVariable(adhocStruct &ahc)
{
bool found=false;
for(unsigned int i=0; i<m_VVarName.size(); ++i)
if (m_VVarName[i].name == ahc.name)
found=true;
if (!found)
m_VVarName.push_back(ahc);
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::PrepareParsers()
{
if (m_Expression.size() == 0)
itkExceptionMacro(<< "No expression set; please set at least one expression." << std::endl);
// Generate variables names
m_VVarName.clear();
m_VNotAllowedVarName.clear();
m_VFinalAllowedVarName.clear();
// m_VFinalAllowedVarName = m_VAllowedVarNameAuto + m_VAllowedVarNameAddedByUser
// m_VFinalAllowedVarName = variable names dictionary
for(unsigned int i=0; i<m_VAllowedVarNameAddedByUser.size(); i++)
m_VFinalAllowedVarName.push_back(m_VAllowedVarNameAddedByUser[i]);
for(unsigned int i=0; i<m_VAllowedVarNameAuto.size(); i++)
m_VFinalAllowedVarName.push_back(m_VAllowedVarNameAuto[i]);
unsigned int nbExpr = m_Expression.size();
for(unsigned int IDExpression=0; IDExpression < nbExpr; ++IDExpression) // For each expression
{
ParserType::Pointer dummyParser = ParserType::New();
dummyParser->SetExpr(this->GetExpression(IDExpression));
mup::var_maptype vmap = dummyParser->GetExprVar();
for (mup::var_maptype::iterator item = vmap.begin(); item!=vmap.end(); ++item)
{
bool OK=false; int i=0;
while( ( !OK ) && (i < (int) m_VFinalAllowedVarName.size()) )
{
if (item->first == m_VFinalAllowedVarName[i].name)
OK=true;
else
i++;
}
if (OK) {AddVariable(m_VFinalAllowedVarName[i]); }
else {
adhocStruct ahc;
ahc.name = item->first;
m_VNotAllowedVarName.push_back(ahc);
}
}
}// At this step, m_VVarName has been built
//Checking formulas consistency
if (m_VNotAllowedVarName.size()>0)
{
std::stringstream sstm;
sstm << "Following variables not allowed : ";
for(unsigned int i=0; i<m_VNotAllowedVarName.size(); ++i)
sstm << m_VNotAllowedVarName[i].name << " ";
sstm << std::endl;
itkExceptionMacro(<< sstm.str());
}
// Register variables for each parser (important : one parser per thread and per expression)
m_VParser.clear();
unsigned int nbThreads = this->GetNumberOfThreads();
for (unsigned int k=0 ; k<nbThreads ; k++)
{
std::vector<ParserType::Pointer> parserList;
for (unsigned int i=0 ; i<nbExpr ; i++)
{
parserList.push_back(ParserType::New());
}
m_VParser.push_back(parserList);
}
// Important to remember that variables of m_VVarName come from a call of GetExprVar method
// Only useful variables are allocated in this filter
int nbVar = m_VVarName.size();
m_StatsVarDetected.clear();
m_NeighDetected.clear();
m_NeighExtremaSizes.clear();
unsigned int nbInputImages = this->GetNumberOfInputs();
RadiusType dummyRadius; dummyRadius[0]=1; dummyRadius[1]=1;
m_NeighExtremaSizes.resize(nbInputImages,dummyRadius);
//Reset
for(unsigned int i=0; i<m_AImage.size(); ++i)
m_AImage[i].clear();
m_AImage.clear();
m_AImage.resize(nbThreads);
double initValue = 0.1;
for(unsigned int i = 0; i < nbThreads; ++i) // For each thread
{
m_AImage[i].resize(nbVar); // For each variable
for(int j=0; j < nbVar; ++j)
{
m_AImage[i][j].name = m_VVarName[j].name;
m_AImage[i][j].type = m_VVarName[j].type;
for (int t=0; t<5; ++t)
m_AImage[i][j].info[t]=m_VVarName[j].info[t];
if ( (m_AImage[i][j].type == 0 ) || (m_AImage[i][j].type == 1) ) // indices (idxX & idxY)
{
m_AImage[i][j].value = ValueType(initValue);
}
if (m_AImage[i][j].type == 2) //imiPhyX
{
SpacingType spacing = this->GetNthInput(m_AImage[i][j].info[0])->GetSpacing();
m_AImage[i][j].value = ValueType(static_cast<double>(spacing[0]));
}
if (m_AImage[i][j].type == 3) //imiPhyY
{
SpacingType spacing = this->GetNthInput(m_AImage[i][j].info[0])->GetSpacing();
m_AImage[i][j].value = ValueType(static_cast<double>(spacing[1]));
}
if (m_AImage[i][j].type == 4 ) // vector
{
unsigned int nbBands = this->GetNthInput(m_AImage[i][j].info[0])->GetNumberOfComponentsPerPixel();
m_AImage[i][j].value = ValueType(1,nbBands,initValue);
}
if (m_AImage[i][j].type == 5 ) // pixel
{
m_AImage[i][j].value = ValueType(initValue);
}
if (m_AImage[i][j].type == 6 ) // neighborhood
{
m_AImage[i][j].value = ValueType(m_AImage[i][j].info[3],m_AImage[i][j].info[2],initValue);
//m_AImage[i][j].info[0] = Image ID
bool found = false;
for (unsigned int r=0; r<m_NeighDetected.size() && !found; r++)
if (m_NeighDetected[r] == (unsigned int) m_AImage[i][j].info[0])
found = true;
if (!found)
m_NeighDetected.push_back(m_AImage[i][j].info[0]);
// find biggest radius for a given input image (idis given by info[0])
if (m_NeighExtremaSizes[m_AImage[i][j].info[0]][0] < (unsigned int) ((m_VVarName[j].info[2]-1)/2) ) // Size x direction (otb convention)
m_NeighExtremaSizes[m_AImage[i][j].info[0]][0] = (unsigned int) ((m_VVarName[j].info[2]-1)/2);
if (m_NeighExtremaSizes[m_AImage[i][j].info[0]][1] < (unsigned int) ((m_VVarName[j].info[3]-1)/2) ) // Size y direction (otb convention)
m_NeighExtremaSizes[m_AImage[i][j].info[0]][1] = (unsigned int) ((m_VVarName[j].info[3]-1)/2);
}
if (m_AImage[i][j].type == 7 ) // user defined variables
{
for(int t=0; t<(int) m_VAllowedVarNameAddedByUser.size(); t++)
if (m_VAllowedVarNameAddedByUser[t].name.compare(m_AImage[i][j].name) == 0)
m_AImage[i][j].value = m_VAllowedVarNameAddedByUser[t].value;
}
if (m_AImage[i][j].type == 8 ) // global stats
{
m_AImage[i][j].value = ValueType(initValue);
//m_AImage[i][j].info[0] = Image ID
bool found = false;
for (unsigned int r=0; r<m_StatsVarDetected.size() && !found; r++)
if (m_StatsVarDetected[r] == m_AImage[i][j].info[0])
found = true;
if (!found)
m_StatsVarDetected.push_back(m_AImage[i][j].info[0]);
}
//Register variable
for (unsigned int k=0 ; k<nbExpr ; k++)
{
m_VParser[i][k]->DefineVar(m_AImage[i][j].name, &(m_AImage[i][j].value));
}
initValue += 0.001;
if (initValue>1.0)
initValue=0.1;
}
}
// Set expressions
for (unsigned int k=0 ; k<nbThreads ; k++)
{
for (unsigned int i=0 ; i<nbExpr ; i++)
{
m_VParser[k][i]->SetExpr(m_Expression[i]);
}
}
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::PrepareParsersGlobStats()
{
// Must instantiate stats variables of the parsers
// Note : at this stage, inputs have already been set to largest possible regions.
for (unsigned int i=0; i<m_StatsVarDetected.size(); i++)
{
StreamingStatisticsVectorImageFilterPointerType filter = StreamingStatisticsVectorImageFilterType::New();
filter->SetInput( this->GetNthInput(m_StatsVarDetected[i]) );
filter->Update();
PixelType pix; //Variable length vector
MatrixType mat;
for(unsigned int t=0; t<m_AImage.size(); t++) // for each thread
for(unsigned int v=0; v<m_AImage[t].size(); v++) // for each variable
if ( (m_AImage[t][v].type == 8) && (m_AImage[t][v].info[0] == m_StatsVarDetected[i]) )// type 8 : flag identifying a glob stat; info[0] : input ID
{
switch ( m_AImage[t][v].info[2] ) // info[2] sub-type (see also SetNthInput method above)
{
case 0: // mini
pix = filter->GetMinimum();
for (int b=0; b<(int) pix.GetSize(); b++) // for each band
if (m_AImage[t][v].info[1] == b) // info[1] : band ID
m_AImage[t][v].value = pix[b];
break;
case 1: // maxi
pix = filter->GetMaximum();
for (int b=0; b<(int) pix.GetSize(); b++) // for each band
if (m_AImage[t][v].info[1] == b) // info[1] : band ID
m_AImage[t][v].value = pix[b];
break;
case 2: // mean
pix = filter->GetMean();
for (int b=0; b<(int) pix.GetSize(); b++) // for each band
if (m_AImage[t][v].info[1] == b) // info[1] : band ID
m_AImage[t][v].value = pix[b];
break;
break;
case 3: // sum
pix = filter->GetSum();
for (int b=0; b<(int) pix.GetSize(); b++) // for each band
if (m_AImage[t][v].info[1] == b) // info[1] : band ID
m_AImage[t][v].value = pix[b];
break;
case 4: // stddev
mat = filter->GetCovariance();
for (int b=0; b<(int) mat.Cols(); b++) // for each band
if (m_AImage[t][v].info[1] == b) // info[1] : band ID
m_AImage[t][v].value = mat(b,b);
break;
}
}
}
}
template< typename TImage >
void BandMathXImageFilter< TImage >
::OutputsDimensions()
{
this->SetNumberOfRequiredOutputs((int) m_Expression.size());
m_outputsDimensions.clear();
for(int i=0; i<(int) m_Expression.size(); ++i)
{
ValueType value = m_VParser[0][i]->EvalRef();
switch (value.GetType())
{ //ValueType
case 'b':
itkExceptionMacro(<< "Booleans not supported." << std::endl);
break;
case 'i':
m_outputsDimensions.push_back(1);
break;
case 'f':
m_outputsDimensions.push_back(1);
break;
case 'c':
itkExceptionMacro(<< "Complex numbers not supported." << std::endl);
break;
case 'm':
{
const mup::matrix_type &vect = value.GetArray();
if ( vect.GetRows() == 1 ) //Vector
m_outputsDimensions.push_back(vect.GetCols());
else //Matrix
itkExceptionMacro(<< "Result of the evaluation can't be a matrix." << std::endl);
}
break;
default:
itkExceptionMacro(<< "Unknown output type : "<< value.GetType() << std::endl);
break;
}
//std::cout << "Type = " << value.GetType() << " dimension = " << m_outputsDimensions.back() << std::endl;
}
}
template< typename TImage >
void BandMathXImageFilter< TImage >
::CheckImageDimensions(void)
{
// Check if input image dimensions match
unsigned int nbInputImages = this->GetNumberOfInputs();
unsigned int inputSize[2];
inputSize[0] = this->GetNthInput(0)->GetLargestPossibleRegion().GetSize(0);
inputSize[1] = this->GetNthInput(0)->GetLargestPossibleRegion().GetSize(1);
for(unsigned int p = 1; p < nbInputImages; p++)
if((inputSize[0] != this->GetNthInput(p)->GetLargestPossibleRegion().GetSize(0))
|| (inputSize[1] != this->GetNthInput(p)->GetLargestPossibleRegion().GetSize(1)))
{
itkExceptionMacro(<< "Input images must have the same dimensions." << std::endl
<< "band #1 is [" << inputSize[0] << ";" << inputSize[1] << "]" << std::endl
<< "band #" << p+1 << " is ["
<< this->GetNthInput(p)->GetLargestPossibleRegion().GetSize(0) << ";"
<< this->GetNthInput(p)->GetLargestPossibleRegion().GetSize(1) << "]");
}
}
template< typename TImage >
void BandMathXImageFilter< TImage >
::GenerateOutputInformation(void)
{
Superclass::GenerateOutputInformation();
CheckImageDimensions();
PrepareParsers();
if (globalStatsDetected())
PrepareParsersGlobStats();
OutputsDimensions();
typedef itk::ImageBase< TImage::ImageDimension > ImageBaseType;
typename ImageBaseType::Pointer outputPtr;
int i=0;
for ( itk::OutputDataObjectIterator it(this); !it.IsAtEnd(); i++, it++ )
{
// Check whether the output is an image of the appropriate
// dimension (use ProcessObject's version of the GetInput()
// method since it returns the input as a pointer to a
// DataObject as opposed to the subclass version which
// static_casts the input to an TImage).
outputPtr = dynamic_cast< ImageBaseType * >( it.GetOutput() );
if ( outputPtr )
outputPtr->SetNumberOfComponentsPerPixel(m_outputsDimensions[i]);
}
}
template< typename TImage >
void BandMathXImageFilter< TImage >
::GenerateInputRequestedRegion()
{
// call the superclass' implementation of this method
Superclass::GenerateInputRequestedRegion();
for(unsigned int i=0; i<m_NeighDetected.size(); i++)
if ( m_NeighDetected[i] < this->GetNumberOfInputs() )
{
// get pointers to the input and output
typename Superclass::InputImagePointer inputPtr = const_cast<TImage *>( this->GetNthInput(m_NeighDetected[i]) );
ImageRegionType inputRequestedRegion;
inputRequestedRegion = inputPtr->GetRequestedRegion();
// pad the input requested region by the operator radius
inputRequestedRegion.PadByRadius( m_NeighExtremaSizes[m_NeighDetected[i]] );
// crop the input requested region at the input's largest possible region
if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion()))
{
inputPtr->SetRequestedRegion(inputRequestedRegion);
return;
}
else
{
// Couldn't crop the region (requested region is outside the largest
// possible region). Throw an exception.
// store what we tried to request (prior to trying to crop)
inputPtr->SetRequestedRegion(inputRequestedRegion);
// build an exception
itk::InvalidRequestedRegionError e(__FILE__, __LINE__);
std::ostringstream msg,msg2;
msg << static_cast<const char *>(this->GetNameOfClass())
<< "::GenerateInputRequestedRegion()";
e.SetLocation(msg.str().c_str());
msg2 << "Requested region is (at least partially) outside the largest possible region (input #" << m_NeighDetected[i] << ").";
e.SetDescription(msg2.str().c_str());
e.SetDataObject(inputPtr);
throw e;
}
}
else
itkExceptionMacro(<< "Requested input #" << m_NeighDetected[i] << ", but only " << this->GetNumberOfInputs() << " inputs are available." << std::endl);
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::BeforeThreadedGenerateData()
{
unsigned int nbThreads = this->GetNumberOfThreads();
// Allocate and initialize the thread temporaries
m_ThreadUnderflow.SetSize(nbThreads);
m_ThreadUnderflow.Fill(0);
m_ThreadOverflow.SetSize(nbThreads);
m_ThreadOverflow.Fill(0);
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::AfterThreadedGenerateData()
{
unsigned int nbThreads = this->GetNumberOfThreads();
unsigned int i;
m_UnderflowCount = 0;
m_OverflowCount = 0;
// Accumulate counts for each thread
for(i = 0; i < nbThreads; ++i)
{
m_UnderflowCount += m_ThreadUnderflow[i];
m_OverflowCount += m_ThreadOverflow[i];
}
if((m_UnderflowCount != 0) || (m_OverflowCount!=0))
{
std::stringstream sstm;
sstm << std::endl
<< "The Following Parsed Expression : ";
for(unsigned int t=0; t<m_Expression.size(); ++t)
sstm << this->GetExpression(t) << std::endl;
sstm << "Generated " << m_UnderflowCount << " Underflow(s) "
<< "And " << m_OverflowCount << " Overflow(s) " << std::endl
<< "The Parsed Expression, The Inputs And The Output "
<< "Type May Be Incompatible !";
otbWarningMacro(<< sstm.str());
}
}
template< typename TImage >
void BandMathXImageFilter<TImage>
::ThreadedGenerateData(const ImageRegionType& outputRegionForThread,
itk::ThreadIdType threadId)
{
ValueType value;
unsigned int nbInputImages = this->GetNumberOfInputs();
//----------------- --------- -----------------//
//----------------- Iterators -----------------//
//----------------- --------- -----------------//
typedef itk::ImageScanlineConstIterator<TImage> ImageScanlineConstIteratorType;
typedef itk::ImageScanlineIterator<TImage> ImageScanlineIteratorType;
typedef itk::ImageRegionConstIteratorWithOnlyIndex<TImage> IndexIteratorType;
std::vector< ImageScanlineConstIteratorType > Vit;
Vit.resize(nbInputImages);
for(unsigned int j=0; j < nbInputImages; ++j)
Vit[j] = ImageScanlineConstIteratorType (this->GetNthInput(j), outputRegionForThread);
std::vector< ImageScanlineIteratorType > VoutIt;
VoutIt.resize(m_Expression.size());
for(unsigned int j=0; j < VoutIt.size(); ++j)
VoutIt[j] = ImageScanlineIteratorType (this->GetOutput(j), outputRegionForThread);
//Special case : neighborhoods
std::vector< itk::ConstNeighborhoodIterator<TImage> > VNit;
for(unsigned int j=0; j<m_VVarName.size(); ++j)
if (m_VVarName[j].type == 6)
{
RadiusType radius;
radius[0]=(int) ((m_VVarName[j].info[2]-1)/2); // Size x direction (otb convention)
radius[1]=(int) ((m_VVarName[j].info[3]-1)/2); // Size y direction (otb convention)
VNit.push_back( itk::ConstNeighborhoodIterator<TImage>(radius, this->GetNthInput(m_VVarName[j].info[0]),outputRegionForThread)); // info[0] = Input image ID
VNit.back().NeedToUseBoundaryConditionOn();
}
// Index only iterator
IndexIteratorType indexIterator(this->GetNthInput(0), outputRegionForThread);
// Support progress methods/callbacks
itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());
// iterator on variables
typename std::vector<adhocStruct>::iterator iterVarStart =
m_AImage[threadId].begin();
typename std::vector<adhocStruct>::iterator iterVarEnd =
m_AImage[threadId].end();
typename std::vector<adhocStruct>::iterator iterVar =
iterVarStart;
// temporary output vectors
std::vector<PixelType> tmpOutputs(m_Expression.size());
for(unsigned int k=0; k<m_Expression.size(); ++k)
tmpOutputs[k].SetSize(m_outputsDimensions[k]);
//----------------- --------------------- -----------------//
//----------------- Variable affectations -----------------//
//----------------- --------------------- -----------------//
for(unsigned int j=0; j < nbInputImages; ++j) { Vit[j].GoToBegin(); }
for(unsigned int j=0; j < m_Expression.size(); ++j) { VoutIt[j].GoToBegin(); }
for(unsigned int j=0; j < VNit.size(); ++j) { VNit[j].GoToBegin(); }
indexIterator.GoToBegin();
while(!Vit[0].IsAtEnd()) // For each pixel
{
while(!Vit[0].IsAtEndOfLine()) // For each line
{
int ngbhNameIndex=0; int index;
iterVar = iterVarStart;
while (iterVar != iterVarEnd)
{
switch (iterVar->type)
{
case 0 : //idxX
iterVar->value = static_cast<double>(indexIterator.GetIndex()[0]);
break;
case 1 : //idxY
iterVar->value = static_cast<double>(indexIterator.GetIndex()[1]);
break;
case 2 : //Spacing X (imiPhyX)
//Nothing to do (already set inside BeforeThreadedGenerateData)"
break;
case 3 : //Spacing Y (imiPhyY)
//Nothing to do (already set inside BeforeThreadedGenerateData)"
break;
case 4 : //vector
// iterVar->info[0] : Input image #ID
for(int p=0; p < iterVar->value.GetCols(); ++p)
iterVar->value.At(0,p) = Vit[iterVar->info[0]].Get()[p];
break;
case 5 : //pixel
// iterVar->info[0] : Input image #ID
// iterVar->info[1] : Band #ID
iterVar->value = Vit[iterVar->info[0]].Get()[iterVar->info[1]];
break;
case 6 : //neighborhood
// iterVar->info[1] : Band #ID
if (iterVar->info[2]*iterVar->info[3] != (int) VNit[ngbhNameIndex].Size() )
itkExceptionMacro(<< "Size of muparserx variable is different from its related otb neighborhood iterator")
index=0;
for(int rows=0; rows<iterVar->info[3]; ++rows)
for(int cols=0; cols<iterVar->info[2]; ++cols)
{
iterVar->value.At(rows,cols) = VNit[ngbhNameIndex].GetPixel(index)[iterVar->info[1]];
index++;
}
ngbhNameIndex++;
break;
case 7 :
//Nothing to do : user defined variable or constant, which have already been set inside PrepareParsers (see above)
break;
case 8 :
//Nothing to do : variable has already been set inside PrepareParsersGlobStats method (see above)
break;
default :
itkExceptionMacro(<< "Type of the variable is unknown");
break;
}
iterVar++;
}//End while on vars
//----------------- ----------- -----------------//
//----------------- Evaluations -----------------//
//----------------- ----------- -----------------//
for(unsigned int IDExpression=0; IDExpression<m_Expression.size(); ++IDExpression)
{
value = m_VParser[threadId][IDExpression]->EvalRef();
switch (value.GetType())
{ //ValueType
case 'i':
tmpOutputs[IDExpression][0] = value.GetInteger();
break;
case 'f':
tmpOutputs[IDExpression][0] = value.GetFloat();
break;
case 'c':
itkExceptionMacro(<< "Complex numbers are not supported." << std::endl);
break;
case 'm':
{
const mup::matrix_type &vect = value.GetArray();
if ( vect.GetRows() == 1 ) //Vector
for(int p=0; p<vect.GetCols(); ++p)
tmpOutputs[IDExpression][p] = vect.At(0,p).GetFloat();
else //Matrix
itkExceptionMacro(<< "Result of the evaluation can't be a matrix." << std::endl);
}
break;
}
//----------------- Pixel affectations -----------------//
for(unsigned int p=0; p<m_outputsDimensions[IDExpression]; ++p)
{
// Case value is equal to -inf or inferior to the minimum value
// allowed by the PixelValueType cast
if (tmpOutputs[IDExpression][p] < double(itk::NumericTraits<PixelValueType>::NonpositiveMin()))
{
tmpOutputs[IDExpression][p] = itk::NumericTraits<PixelValueType>::NonpositiveMin();
m_ThreadUnderflow[threadId]++;
}
// Case value is equal to inf or superior to the maximum value
// allowed by the PixelValueType cast
else if (tmpOutputs[IDExpression][p] > double(itk::NumericTraits<PixelValueType>::max()))
{
tmpOutputs[IDExpression][p] = itk::NumericTraits<PixelValueType>::max();
m_ThreadOverflow[threadId]++;
}
}
VoutIt[IDExpression].Set(tmpOutputs[IDExpression]);
}
for(unsigned int j=0; j < nbInputImages; ++j) { ++Vit[j]; }
for(unsigned int j=0; j < m_Expression.size(); ++j) { ++VoutIt[j]; }
for(unsigned int j=0; j < VNit.size(); ++j) { ++VNit[j]; }
++indexIterator;
progress.CompletedPixel();
}
for(unsigned int j=0; j < nbInputImages; ++j) { Vit[j].NextLine(); }
for(unsigned int j=0; j < m_Expression.size(); ++j) { VoutIt[j].NextLine(); }
}
}
}// end namespace otb
#endif
|