From: srit Date: Tue, 18 May 2010 16:20:43 +0000 (+0000) Subject: Reformatted using new coding style X-Git-Tag: v1.2.0~652 X-Git-Url: https://git.creatis.insa-lyon.fr/pubgit/?a=commitdiff_plain;h=1e034c70105f0926939acaaa27ddb46e904ae8bf;p=clitk.git Reformatted using new coding style --- diff --git a/common/clitkCommon.cxx b/common/clitkCommon.cxx index fa1c595..d3f6016 100644 --- a/common/clitkCommon.cxx +++ b/common/clitkCommon.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -26,24 +26,24 @@ //------------------------------------------------------------------ // skip line which begin with a sharp '#' -void clitk::skipComment(std::istream & is) +void clitk::skipComment(std::istream & is) { char c; char line[1024]; if (is.eof()) return; - is >> c ; + is >> c ; while (is && (c == '#')) { - is.getline (line, 1024); - is >> c; - if (is.eof()) return; + is.getline (line, 1024); + is >> c; + if (is.eof()) return; } is.unget(); } //// //------------------------------------------------------------------ - + //------------------------------------------------------------------ // linear (rough) conversion from Hounsfield Unit to density -double clitk::HU2density(double HU) +double clitk::HU2density(double HU) { return (HU+1000.0)/1000.0; } //// @@ -51,15 +51,15 @@ double clitk::HU2density(double HU) //------------------------------------------------------------------ // Return filename extension -std::string clitk::GetExtension(const std::string& filename) +std::string clitk::GetExtension(const std::string& filename) { // This assumes that the final '.' in a file name is the delimiter // for the file's extension type - const std::string::size_type it = filename.find_last_of( "." ); + const std::string::size_type it = filename.find_last_of( "." ); // This determines the file's type by creating a new string // who's value is the extension of the input filename // eg. "myimage.gif" has an extension of "gif" - std::string fileExt( filename, it+1, filename.length() ); + std::string fileExt( filename, it+1, filename.length() ); return( fileExt ); } //// //------------------------------------------------------------------ @@ -70,15 +70,15 @@ void clitk::VerboseInProgress(const int nb, const int current, const int percent { static int previous = -1; const int rounded = (100*current)/nb; - if (previous==rounded) return; + if (previous==rounded) return; previous = rounded; std::ostringstream oss; oss << std::setw(4) << rounded << '%'; std::cout << oss.str() << std::flush; - for (unsigned int i=0; i -bool clitk::IsSameType(std::string t) { - if ((t==GetTypeAsString()) || (t == "schar")) return true; else return false; +bool clitk::IsSameType(std::string t) +{ + if ((t==GetTypeAsString()) || (t == "schar")) return true; + else return false; } template<> -bool clitk::IsSameType(std::string t) { - if ((t==GetTypeAsString()) || (t == "char")) return true; else return false; +bool clitk::IsSameType(std::string t) +{ + if ((t==GetTypeAsString()) || (t == "char")) return true; + else return false; } template<> -bool clitk::IsSameType(std::string t) { - if ((t==GetTypeAsString()) || (t == "uchar")) return true; else return false; +bool clitk::IsSameType(std::string t) +{ + if ((t==GetTypeAsString()) || (t == "uchar")) return true; + else return false; } template<> -bool clitk::IsSameType(std::string t) { - if ((t==GetTypeAsString()) || (t == "ushort")) return true; else return false; +bool clitk::IsSameType(std::string t) +{ + if ((t==GetTypeAsString()) || (t == "ushort")) return true; + else return false; } //------------------------------------------------------------------ //------------------------------------------------------------------ -void clitk::FindAndReplace(std::string & line, - const std::string & tofind, - const std::string & replacement) { +void clitk::FindAndReplace(std::string & line, + const std::string & tofind, + const std::string & replacement) +{ int pos = line.find(tofind); while (pos!= (int)std::string::npos) { line.replace(pos, tofind.size(), replacement); @@ -166,9 +178,10 @@ void clitk::FindAndReplace(std::string & line, //------------------------------------------------------------------ //------------------------------------------------------------------ -void clitk::FindAndReplace(std::string & line, - const std::vector & tofind, - const std::vector & toreplace) { +void clitk::FindAndReplace(std::string & line, + const std::vector & tofind, + const std::vector & toreplace) +{ for(unsigned int i=0; i & tofind, - const std::vector & toreplace, - std::ofstream & out) { +void clitk::FindAndReplace(std::ifstream & in, + const std::vector & tofind, + const std::vector & toreplace, + std::ofstream & out) +{ std::string line; if (tofind.size() != toreplace.size()) { std::cerr << "Error' tofind' is size=" << tofind.size() << std::endl; @@ -194,9 +208,10 @@ void clitk::FindAndReplace(std::ifstream & in, //------------------------------------------------------------------ //------------------------------------------------------------------ -double clitk::ComputeEuclideanDistanceFromPointToPlane(const itk::ContinuousIndex point, - const itk::ContinuousIndex pointInPlane, - const itk::ContinuousIndex normalPlane) { +double clitk::ComputeEuclideanDistanceFromPointToPlane(const itk::ContinuousIndex point, + const itk::ContinuousIndex pointInPlane, + const itk::ContinuousIndex normalPlane) +{ // http://mathworld.wolfram.com/Plane.html // http://mathworld.wolfram.com/Point-PlaneDistance.html double a = normalPlane[0]; @@ -214,24 +229,26 @@ double clitk::ComputeEuclideanDistanceFromPointToPlane(const itk::ContinuousInde double d = -a*x0 - b*y0 - c*z0; DD(d); double distance = (a*x + b*y + c*z + d) / norm; - + return distance; } //------------------------------------------------------------------ //-------------------------------------------------------------------- // Open a file for reading -void clitk::openFileForReading(std::ifstream & is, const std::string & filename) { +void clitk::openFileForReading(std::ifstream & is, const std::string & filename) +{ is.open(filename.c_str(), std::ios::in); if ( is.fail() ) { itkGenericExceptionMacro(<< "Could not open file (for reading): " << filename); } } //-------------------------------------------------------------------- - + //-------------------------------------------------------------------- // Open a file for writing -void clitk::openFileForWriting(std::ofstream & os, const std::string & filename) { +void clitk::openFileForWriting(std::ofstream & os, const std::string & filename) +{ os.open(filename.c_str(), std::ios::out); if ( os.fail() ) { itkGenericExceptionMacro(<< "Could not open file (for writing): " << filename); @@ -240,14 +257,17 @@ void clitk::openFileForWriting(std::ofstream & os, const std::string & filename) //-------------------------------------------------------------------- //-------------------------------------------------------------------- -double clitk::cotan(double i) { return(1.0 / tan(i)); } -double clitk::invcotan(double x) { +double clitk::cotan(double i) +{ + return(1.0 / tan(i)); +} +double clitk::invcotan(double x) +{ // http://mathworld.wolfram.com/InverseCotangent.html double y; if (x<0) { y = -0.5*M_PI-atan(x); - } - else { + } else { y = 0.5*M_PI-atan(x); } return y; @@ -256,7 +276,8 @@ double clitk::invcotan(double x) { //-------------------------------------------------------------------- std::streambuf * clitk_stdcerr_backup; -void clitk::disableStdCerr() { +void clitk::disableStdCerr() +{ clitk_stdcerr_backup = std::cerr.rdbuf(); std::stringstream oss; std::cerr.rdbuf( oss.rdbuf() ); @@ -264,14 +285,16 @@ void clitk::disableStdCerr() { //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::enableStdCerr() { +void clitk::enableStdCerr() +{ std::cerr.rdbuf(clitk_stdcerr_backup); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::readDoubleFromFile(const std::string & filename, std::vector & list) { +void clitk::readDoubleFromFile(const std::string & filename, std::vector & list) +{ std::ifstream is; clitk::openFileForReading(is, filename); list.clear(); diff --git a/common/clitkCommon.txx b/common/clitkCommon.txx index f9eeb8c..c2e9a4a 100644 --- a/common/clitkCommon.txx +++ b/common/clitkCommon.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,13 +22,14 @@ * @file clitkCommon.txx * @author David Sarrut * @date 18 May 2006 - * + * -------------------------------------------------*/ //-------------------------------------------------------------------- // Convert float, double ... to string template -std::string toString(const T & t) { +std::string toString(const T & t) +{ std::ostringstream myStream; myStream << t << std::flush; return(myStream.str()); @@ -38,7 +39,8 @@ std::string toString(const T & t) { //-------------------------------------------------------------------- // Convert float*, double* ... to string template -std::string toStringVector(const T * t, const int n) { +std::string toStringVector(const T * t, const int n) +{ std::ostringstream myStream; for(int i=0; i(t[i]) << " "; @@ -50,7 +52,8 @@ std::string toStringVector(const T * t, const int n) { //-------------------------------------------------------------------- // Convert float*, double* ... to string template -std::string toStringVector(const T & t, const int n) { +std::string toStringVector(const T & t, const int n) +{ std::ostringstream myStream; for(int i=0; i -std::string toStringVector(const std::vector & t) { +std::string toStringVector(const std::vector & t) +{ return toStringVector(&t[0], t.size()); } //-------------------------------------------------------------------- @@ -70,7 +74,8 @@ std::string toStringVector(const std::vector & t) { //-------------------------------------------------------------------- // Convert a pixel type to another (downcast) template -TPixelDown PixelTypeDownCast(const TPixelUp & x) { +TPixelDown PixelTypeDownCast(const TPixelUp & x) +{ return (TPixelDown)lrint(x); } //-------------------------------------------------------------------- @@ -79,7 +84,7 @@ TPixelDown PixelTypeDownCast(const TPixelUp & x) { template struct vectorComparisonLowerThan: public std::binary_function { vectorComparisonLowerThan(const std::vector & v):vect(v) {}; - bool operator()(int x, int y) { + bool operator()(int x, int y) { return (vect[x] < vect[y]); } const std::vector & vect; @@ -90,7 +95,7 @@ struct vectorComparisonLowerThan: public std::binary_function { template struct vectorComparisonGreaterThan: public std::binary_function { vectorComparisonGreaterThan(const std::vector & v):vect(v) {}; - bool operator()(int x, int y) { + bool operator()(int x, int y) { return (vect[x] > vect[y]); } const std::vector & vect; @@ -99,23 +104,25 @@ struct vectorComparisonGreaterThan: public std::binary_function //-------------------------------------------------------------------- template -void GetSortedIndex(const std::vector & toSort, std::vector & index, bool increasing) { - index.resize(toSort.size()); +void GetSortedIndex(const std::vector & toSort, std::vector & index, bool increasing) +{ + index.resize(toSort.size()); for(unsigned int i=0; i(toSort)); - else - std::sort(index.begin(), - index.end(), - vectorComparisonGreaterThan(toSort)); + if (increasing) + std::sort(index.begin(), + index.end(), + vectorComparisonLowerThan(toSort)); + else + std::sort(index.begin(), + index.end(), + vectorComparisonGreaterThan(toSort)); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -std::string GetTypeAsString() { +std::string GetTypeAsString() +{ // http://www.vtk.org/doc/release/3/html/vtkSetGet_8h-source.html // and // itkImageIOBase.cxx @@ -137,17 +144,18 @@ std::string GetTypeAsString() { //-------------------------------------------------------------------- template -void CloneImage(const typename ImageType::Pointer & input, typename ImageType::Pointer & output) { +void CloneImage(const typename ImageType::Pointer & input, typename ImageType::Pointer & output) +{ output->SetRegions(input->GetLargestPossibleRegion()); output->SetOrigin(input->GetOrigin()); output->SetSpacing(input->GetSpacing()); output->Allocate(); - typedef itk::ImageRegionConstIterator ConstIteratorType; + typedef itk::ImageRegionConstIterator ConstIteratorType; ConstIteratorType pi(input,input->GetLargestPossibleRegion()); - pi.GoToBegin(); - typedef itk::ImageRegionIterator IteratorType; + pi.GoToBegin(); + typedef itk::ImageRegionIterator IteratorType; IteratorType po(output,input->GetLargestPossibleRegion()); - po.GoToBegin(); + po.GoToBegin(); while (!pi.IsAtEnd()) { po.Set(pi.Get()); ++pi; diff --git a/common/clitkDicomRT_Contour.cxx b/common/clitkDicomRT_Contour.cxx index ac6d441..5c12802 100644 --- a/common/clitkDicomRT_Contour.cxx +++ b/common/clitkDicomRT_Contour.cxx @@ -2,7 +2,7 @@ Program: vv http://www.creatis.insa-lyon.fr/rio/vv Main authors : XX XX XX - Authors belongs to: + Authors belongs to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,11 +17,12 @@ =========================================================================*/ -#include "clitkDicomRT_Contour.h" +#include "clitkDicomRT_Contour.h" #include //-------------------------------------------------------------------- -clitk::DicomRT_Contour::DicomRT_Contour() { +clitk::DicomRT_Contour::DicomRT_Contour() +{ mMeshIsUpToDate = false; mNbOfPoints = 0; } @@ -29,23 +30,26 @@ clitk::DicomRT_Contour::DicomRT_Contour() { //-------------------------------------------------------------------- -clitk::DicomRT_Contour::~DicomRT_Contour() { - +clitk::DicomRT_Contour::~DicomRT_Contour() +{ + } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::DicomRT_Contour::Print(std::ostream & os) const { +void clitk::DicomRT_Contour::Print(std::ostream & os) const +{ DD("TODO : print Contours"); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -bool clitk::DicomRT_Contour::Read(gdcm::SQItem * item) { - +bool clitk::DicomRT_Contour::Read(gdcm::SQItem * item) +{ + // Contour type [Contour Geometric Type] mType = item->GetEntryValue(0x3006,0x0042); // DD(mType); @@ -53,15 +57,15 @@ bool clitk::DicomRT_Contour::Read(gdcm::SQItem * item) { std::cerr << "Skip this contour : type=" << mType << std::endl; return false; } - + // Number of points [Number of Contour Points] mNbOfPoints = parse_value(item->GetEntryValue(0x3006,0x0046)); // DD(mNbOfPoints); - + // Read values [Contour Data] std::vector points = parse_string(item->GetEntryValue(0x3006,0x0050),'\\'); assert(points.size() == static_cast(mNbOfPoints)*3); - + // Organize values mData = vtkPoints::New(); mData->SetDataTypeToDouble(); @@ -89,7 +93,8 @@ bool clitk::DicomRT_Contour::Read(gdcm::SQItem * item) { //-------------------------------------------------------------------- -vtkPolyData * clitk::DicomRT_Contour::GetMesh() { +vtkPolyData * clitk::DicomRT_Contour::GetMesh() +{ if (!mMeshIsUpToDate) { ComputeMesh(); } @@ -99,17 +104,18 @@ vtkPolyData * clitk::DicomRT_Contour::GetMesh() { //-------------------------------------------------------------------- -void clitk::DicomRT_Contour::ComputeMesh() { - // DD("ComputeMesh Contour"); +void clitk::DicomRT_Contour::ComputeMesh() +{ +// DD("ComputeMesh Contour"); mMesh = vtkPolyData::New(); mMesh->Allocate(); //for cell structures mMesh->SetPoints(vtkPoints::New()); vtkIdType ids[2]; for (unsigned int idx=0 ; idxGetPoints()->InsertNextPoint(mData->GetPoint(idx)[0], - mData->GetPoint(idx)[1], + mMesh->GetPoints()->InsertNextPoint(mData->GetPoint(idx)[0], + mData->GetPoint(idx)[1], mData->GetPoint(idx)[2]); - ids[0]=idx; + ids[0]=idx; ids[1]=(ids[0]+1) % mNbOfPoints; //0-1,1-2,...,n-1-0 // DD(ids[0]); // DD(ids[1]); diff --git a/common/clitkDicomRT_ROI.cxx b/common/clitkDicomRT_ROI.cxx index 72f8273..119b638 100644 --- a/common/clitkDicomRT_ROI.cxx +++ b/common/clitkDicomRT_ROI.cxx @@ -2,7 +2,7 @@ Program: vv http://www.creatis.insa-lyon.fr/rio/vv Main authors : XX XX XX - Authors belongs to: + Authors belongs to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,12 +17,13 @@ =========================================================================*/ -#include "clitkDicomRT_ROI.h" +#include "clitkDicomRT_ROI.h" #include #include //-------------------------------------------------------------------- -clitk::DicomRT_ROI::DicomRT_ROI() { +clitk::DicomRT_ROI::DicomRT_ROI() +{ mName = "NoName"; mNumber = -1; mColor.resize(3); @@ -33,14 +34,16 @@ clitk::DicomRT_ROI::DicomRT_ROI() { //-------------------------------------------------------------------- -clitk::DicomRT_ROI::~DicomRT_ROI() { - +clitk::DicomRT_ROI::~DicomRT_ROI() +{ + } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::DicomRT_ROI::SetDisplayColor(double r, double v, double b) { +void clitk::DicomRT_ROI::SetDisplayColor(double r, double v, double b) +{ mColor.resize(3); mColor[0] = r; mColor[1] = v; @@ -50,29 +53,33 @@ void clitk::DicomRT_ROI::SetDisplayColor(double r, double v, double b) { //-------------------------------------------------------------------- -int clitk::DicomRT_ROI::GetROINumber() const { +int clitk::DicomRT_ROI::GetROINumber() const +{ return mNumber; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_ROI::GetName() const { +const std::string & clitk::DicomRT_ROI::GetName() const +{ return mName; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::vector & clitk::DicomRT_ROI::GetDisplayColor() const { +const std::vector & clitk::DicomRT_ROI::GetDisplayColor() const +{ return mColor; } //-------------------------------------------------------------------- - + //-------------------------------------------------------------------- -void clitk::DicomRT_ROI::Print(std::ostream & os) const { - os << "ROI " << mNumber << "\t" << mName +void clitk::DicomRT_ROI::Print(std::ostream & os) const +{ + os << "ROI " << mNumber << "\t" << mName << "\t(" << mColor[0] << " " << mColor[1] << " " << mColor[2] << ")" << "\t Contours = " << mListOfContours.size() << std::endl; } @@ -80,29 +87,32 @@ void clitk::DicomRT_ROI::Print(std::ostream & os) const { //-------------------------------------------------------------------- -void clitk::DicomRT_ROI::SetBackgroundValueLabelImage(double bg){ +void clitk::DicomRT_ROI::SetBackgroundValueLabelImage(double bg) +{ mBackgroundValue = bg; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -double clitk::DicomRT_ROI::GetBackgroundValueLabelImage() const { +double clitk::DicomRT_ROI::GetBackgroundValueLabelImage() const +{ return mBackgroundValue; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::DicomRT_ROI::Read(std::map & rois, gdcm::SQItem * item) { - +void clitk::DicomRT_ROI::Read(std::map & rois, gdcm::SQItem * item) +{ + // Change number if needed - + // TODO // ROI number [Referenced ROI Number] mNumber = atoi(item->GetEntryValue(0x3006,0x0084).c_str()); - + // Retrieve ROI Name mName = rois[mNumber]; @@ -111,8 +121,8 @@ void clitk::DicomRT_ROI::Read(std::map & rois, gdcm::SQItem * // Read contours [Contour Sequence] gdcm::SeqEntry * contours=item->GetSeqEntry(0x3006,0x0040); - for(gdcm::SQItem* j=contours->GetFirstSQItem();j!=0;j=contours->GetNextSQItem()) { - DicomRT_Contour * c = new DicomRT_Contour; + for(gdcm::SQItem* j=contours->GetFirstSQItem(); j!=0; j=contours->GetNextSQItem()) { + DicomRT_Contour * c = new DicomRT_Contour; bool b = c->Read(j); if (b) mListOfContours.push_back(c); } @@ -121,7 +131,8 @@ void clitk::DicomRT_ROI::Read(std::map & rois, gdcm::SQItem * //-------------------------------------------------------------------- -vtkPolyData * clitk::DicomRT_ROI::GetMesh() { +vtkPolyData * clitk::DicomRT_ROI::GetMesh() +{ if (!mMeshIsUpToDate) { ComputeMesh(); } @@ -131,7 +142,8 @@ vtkPolyData * clitk::DicomRT_ROI::GetMesh() { //-------------------------------------------------------------------- -void clitk::DicomRT_ROI::ComputeMesh() { +void clitk::DicomRT_ROI::ComputeMesh() +{ vtkAppendPolyData * append = vtkAppendPolyData::New(); for(unsigned int i=0; iAddInput(mListOfContours[i]->GetMesh()); @@ -144,16 +156,17 @@ void clitk::DicomRT_ROI::ComputeMesh() { //-------------------------------------------------------------------- -void clitk::DicomRT_ROI::SetFromBinaryImage(vvImage::Pointer image, int n, - std::string name, - std::vector color) { - +void clitk::DicomRT_ROI::SetFromBinaryImage(vvImage::Pointer image, int n, + std::string name, + std::vector color) +{ + // ROI number [Referenced ROI Number] mNumber = n; - + // ROI Name mName = name; - + // ROI Color [ROI Display Color] mColor = color; @@ -167,7 +180,8 @@ void clitk::DicomRT_ROI::SetFromBinaryImage(vvImage::Pointer image, int n, //-------------------------------------------------------------------- -const vvImage::Pointer clitk::DicomRT_ROI::GetImage() const { +const vvImage::Pointer clitk::DicomRT_ROI::GetImage() const +{ return mImage; } //-------------------------------------------------------------------- diff --git a/common/clitkDicomRT_ROI_ConvertToImageFilter.cxx b/common/clitkDicomRT_ROI_ConvertToImageFilter.cxx index ef5ecb4..9694639 100644 --- a/common/clitkDicomRT_ROI_ConvertToImageFilter.cxx +++ b/common/clitkDicomRT_ROI_ConvertToImageFilter.cxx @@ -2,7 +2,7 @@ Program: vv http://www.creatis.insa-lyon.fr/rio/vv Main authors : XX XX XX - Authors belongs to: + Authors belongs to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,7 +17,7 @@ =========================================================================*/ -#include "clitkDicomRT_ROI_ConvertToImageFilter.h" +#include "clitkDicomRT_ROI_ConvertToImageFilter.h" #include #include #include @@ -26,7 +26,8 @@ #include "clitkImageCommon.h" //-------------------------------------------------------------------- -clitk::DicomRT_ROI_ConvertToImageFilter::DicomRT_ROI_ConvertToImageFilter() { +clitk::DicomRT_ROI_ConvertToImageFilter::DicomRT_ROI_ConvertToImageFilter() +{ mROI = NULL; mImageInfoIsSet = false; mWriteOutput = false; @@ -36,28 +37,32 @@ clitk::DicomRT_ROI_ConvertToImageFilter::DicomRT_ROI_ConvertToImageFilter() { //-------------------------------------------------------------------- -clitk::DicomRT_ROI_ConvertToImageFilter::~DicomRT_ROI_ConvertToImageFilter() { - +clitk::DicomRT_ROI_ConvertToImageFilter::~DicomRT_ROI_ConvertToImageFilter() +{ + } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::DicomRT_ROI_ConvertToImageFilter::SetROI(clitk::DicomRT_ROI * roi) { +void clitk::DicomRT_ROI_ConvertToImageFilter::SetROI(clitk::DicomRT_ROI * roi) +{ mROI = roi; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::DicomRT_ROI_ConvertToImageFilter::SetCropMaskEnabled(bool b) { +void clitk::DicomRT_ROI_ConvertToImageFilter::SetCropMaskEnabled(bool b) +{ mCropMask = b; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::DicomRT_ROI_ConvertToImageFilter::SetOutputImageFilename(std::string s) { +void clitk::DicomRT_ROI_ConvertToImageFilter::SetOutputImageFilename(std::string s) +{ mOutputFilename = s; mWriteOutput = true; } @@ -65,7 +70,8 @@ void clitk::DicomRT_ROI_ConvertToImageFilter::SetOutputImageFilename(std::string //-------------------------------------------------------------------- -void clitk::DicomRT_ROI_ConvertToImageFilter::SetImageFilename(std::string f) { +void clitk::DicomRT_ROI_ConvertToImageFilter::SetImageFilename(std::string f) +{ itk::ImageIOBase::Pointer header = clitk::readImageHeader(f); if (header->GetNumberOfDimensions() < 3) { std::cerr << "Error. Please provide a 3D image instead of " << f << std::endl; @@ -88,7 +94,8 @@ void clitk::DicomRT_ROI_ConvertToImageFilter::SetImageFilename(std::string f) { //-------------------------------------------------------------------- -void clitk::DicomRT_ROI_ConvertToImageFilter::Update() { +void clitk::DicomRT_ROI_ConvertToImageFilter::Update() +{ if (!mROI) { std::cerr << "Error. No ROI set, please use SetROI." << std::endl; exit(0); @@ -98,31 +105,31 @@ void clitk::DicomRT_ROI_ConvertToImageFilter::Update() { exit(0); } // DD("Update"); - + // Get Mesh vtkPolyData * mesh = mROI->GetMesh(); DD(mesh->GetNumberOfCells()); - + // Get bounds - double *bounds=mesh->GetBounds(); + double *bounds=mesh->GetBounds(); // for(int i=0; i<6; i++){ // DD(bounds[i]); // } // Compute origin - std::vector origin; + std::vector origin; origin.resize(3); origin[0] = floor((bounds[0]-mOrigin[0])/mSpacing[0]-2)*mSpacing[0]+mOrigin[0]; origin[1] = floor((bounds[2]-mOrigin[1])/mSpacing[1]-2)*mSpacing[1]+mOrigin[1]; origin[2] = floor((bounds[4]-mOrigin[2])/mSpacing[2]-2)*mSpacing[2]+mOrigin[2]; - + // Compute extend - std::vector extend; + std::vector extend; extend.resize(3); extend[0] = ceil((bounds[1]-origin[0])/mSpacing[0]+4); extend[1] = ceil((bounds[3]-origin[1])/mSpacing[1]+4); extend[2] = ceil((bounds[5]-origin[2])/mSpacing[2]+4); - + // If no crop, set initial image size/origin if (!mCropMask) { for(int i=0; i<3; i++) { @@ -130,14 +137,14 @@ void clitk::DicomRT_ROI_ConvertToImageFilter::Update() { extend[i] = mSize[i]-1; } } - + // Create new output image mBinaryImage = vtkImageData::New(); mBinaryImage->SetScalarTypeToUnsignedChar(); mBinaryImage->SetOrigin(&origin[0]); mBinaryImage->SetSpacing(&mSpacing[0]); - mBinaryImage->SetExtent(0, extend[0], - 0, extend[1], + mBinaryImage->SetExtent(0, extend[0], + 0, extend[1], 0, extend[2]); mBinaryImage->AllocateScalars(); @@ -148,14 +155,14 @@ void clitk::DicomRT_ROI_ConvertToImageFilter::Update() { // } memset(mBinaryImage->GetScalarPointer(), 0, mBinaryImage->GetDimensions()[0]*mBinaryImage->GetDimensions()[1]*mBinaryImage->GetDimensions()[2]*sizeof(unsigned char)); - + // Extrude vtkSmartPointer extrude=vtkSmartPointer::New(); extrude->SetInput(mesh); ///We extrude in the -slice_spacing direction to respect the FOCAL convention // ????????????? extrude->SetVector(0, 0, -mSpacing[2]); - // Binarization + // Binarization vtkSmartPointer sts=vtkSmartPointer::New(); //The following line is extremely important //http://www.nabble.com/Bug-in-vtkPolyDataToImageStencil--td23368312.html#a23370933 @@ -165,27 +172,28 @@ void clitk::DicomRT_ROI_ConvertToImageFilter::Update() { //sts->SetInput(mesh); vtkSmartPointer stencil=vtkSmartPointer::New(); - stencil->SetStencil(sts->GetOutput()); + stencil->SetStencil(sts->GetOutput()); stencil->SetInput(mBinaryImage); stencil->ReverseStencilOn(); stencil->Update(); mBinaryImage->ShallowCopy(stencil->GetOutput()); - + if (mWriteOutput) { - typedef itk::Image ImageType; - typedef itk::VTKImageToImageFilter ConnectorType; - ConnectorType::Pointer connector = ConnectorType::New(); - connector->SetInput(GetOutput()); - connector->Update(); - clitk::writeImage(connector->GetOutput(), mOutputFilename); + typedef itk::Image ImageType; + typedef itk::VTKImageToImageFilter ConnectorType; + ConnectorType::Pointer connector = ConnectorType::New(); + connector->SetInput(GetOutput()); + connector->Update(); + clitk::writeImage(connector->GetOutput(), mOutputFilename); } } //-------------------------------------------------------------------- - + //-------------------------------------------------------------------- -vtkImageData * clitk::DicomRT_ROI_ConvertToImageFilter::GetOutput() { +vtkImageData * clitk::DicomRT_ROI_ConvertToImageFilter::GetOutput() +{ return mBinaryImage; } //-------------------------------------------------------------------- diff --git a/common/clitkDicomRT_StructureSet.cxx b/common/clitkDicomRT_StructureSet.cxx index d7c4e79..fb23570 100644 --- a/common/clitkDicomRT_StructureSet.cxx +++ b/common/clitkDicomRT_StructureSet.cxx @@ -2,7 +2,7 @@ Program: vv http://www.creatis.insa-lyon.fr/rio/vv Main authors : XX XX XX - Authors belongs to: + Authors belongs to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,11 +17,12 @@ =========================================================================*/ -#include "clitkDicomRT_StructureSet.h" +#include "clitkDicomRT_StructureSet.h" #include //-------------------------------------------------------------------- -clitk::DicomRT_StructureSet::DicomRT_StructureSet() { +clitk::DicomRT_StructureSet::DicomRT_StructureSet() +{ mStudyID = "NoStudyID"; mStudyTime = "NoStudyTime"; mStudyDate = "NoStudyDate"; @@ -34,83 +35,94 @@ clitk::DicomRT_StructureSet::DicomRT_StructureSet() { //-------------------------------------------------------------------- -clitk::DicomRT_StructureSet::~DicomRT_StructureSet() { - +clitk::DicomRT_StructureSet::~DicomRT_StructureSet() +{ + } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetStudyID() const { +const std::string & clitk::DicomRT_StructureSet::GetStudyID() const +{ return mStudyID; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetStudyTime() const{ +const std::string & clitk::DicomRT_StructureSet::GetStudyTime() const +{ return mStudyTime; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetStudyDate() const { +const std::string & clitk::DicomRT_StructureSet::GetStudyDate() const +{ return mStudyDate; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetLabel() const { +const std::string & clitk::DicomRT_StructureSet::GetLabel() const +{ return mLabel; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetName() const { +const std::string & clitk::DicomRT_StructureSet::GetName() const +{ return mName; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetDate() const { +const std::string & clitk::DicomRT_StructureSet::GetDate() const +{ return mDate; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -const std::string & clitk::DicomRT_StructureSet::GetTime() const { +const std::string & clitk::DicomRT_StructureSet::GetTime() const +{ return mTime; } //-------------------------------------------------------------------- - - + + //-------------------------------------------------------------------- -const std::vector & clitk::DicomRT_StructureSet::GetListOfROI() const { +const std::vector & clitk::DicomRT_StructureSet::GetListOfROI() const +{ return mListOfROI; } //-------------------------------------------------------------------- - - + + //-------------------------------------------------------------------- -clitk::DicomRT_ROI* clitk::DicomRT_StructureSet::GetROI(int n) { +clitk::DicomRT_ROI* clitk::DicomRT_StructureSet::GetROI(int n) +{ if (mMapOfROIIndex.find(n) == mMapOfROIIndex.end()) { std::cerr << "No ROI number " << n << std::endl; return NULL; } DD(mListOfROI[mMapOfROIIndex[n]]->GetName()); - DD(mListOfROI[mMapOfROIIndex[n]]->GetROINumber()); + DD(mListOfROI[mMapOfROIIndex[n]]->GetROINumber()); return mListOfROI[mMapOfROIIndex[n]]; } //-------------------------------------------------------------------- - - + + //-------------------------------------------------------------------- -void clitk::DicomRT_StructureSet::Print(std::ostream & os) const { +void clitk::DicomRT_StructureSet::Print(std::ostream & os) const +{ os << "Study ID = " << mStudyID << std::endl << "Study Date = " << mStudyDate << std::endl << "Study Time = " << mStudyTime << std::endl @@ -126,7 +138,8 @@ void clitk::DicomRT_StructureSet::Print(std::ostream & os) const { //-------------------------------------------------------------------- -void clitk::DicomRT_StructureSet::Read(const std::string & filename) { +void clitk::DicomRT_StructureSet::Read(const std::string & filename) +{ // Open DICOM gdcm::File reader; reader.SetFileName(filename.c_str()); @@ -137,17 +150,17 @@ void clitk::DicomRT_StructureSet::Read(const std::string & filename) { // Check file type //Verify if the file is a RT-Structure-Set dicom file if (!gdcm::Util::DicomStringEqual(reader.GetEntryValue(0x0008,0x0016),"1.2.840.10008.5.1.4.1.1.481.3")) { //SOP clas UID - std::cerr << "Error. the file " << filename + std::cerr << "Error. the file " << filename << " is not a Dicom Struct ? (must have a SOP Class UID [0008|0016] = 1.2.840.10008.5.1.4.1.1.481.3 ==> [RT Structure Set Storage])" << std::endl; exit(0); - } + } if (!gdcm::Util::DicomStringEqual(reader.GetEntryValue(0x0008,0x0060),"RTSTRUCT")) { //SOP clas UID - std::cerr << "Error. the file " << filename + std::cerr << "Error. the file " << filename << " is not a Dicom Struct ? (must have 0x0008,0x0060 = RTSTRUCT [RT Structure Set Storage])" << std::endl; exit(0); - } + } // Read global info mStudyID = reader.GetValEntry(0x0020,0x0010)->GetValue(); @@ -156,36 +169,36 @@ void clitk::DicomRT_StructureSet::Read(const std::string & filename) { mLabel = reader.GetValEntry(0x3006,0x002)->GetValue(); mName = reader.GetValEntry(0x3006,0x004)->GetValue(); mTime = reader.GetValEntry(0x3006,0x009)->GetValue(); - + //---------------------------------- // Read all ROI Names and number // 0x3006,0x0020 = [ Structure Set ROI Sequence ] gdcm::SeqEntry * roi_seq=reader.GetSeqEntry(0x3006,0x0020); assert(roi_seq); // TODO error message - for (gdcm::SQItem* r=roi_seq->GetFirstSQItem();r!=0;r=roi_seq->GetNextSQItem()) { - std::string name = r->GetEntryValue(0x3006,0x0026); // 0x3006,0x0026 = [ROI Name] + for (gdcm::SQItem* r=roi_seq->GetFirstSQItem(); r!=0; r=roi_seq->GetNextSQItem()) { + std::string name = r->GetEntryValue(0x3006,0x0026); // 0x3006,0x0026 = [ROI Name] int nb = atoi(r->GetEntryValue(0x3006,0x0022).c_str()); // 0x3006,0x0022 = [ROI Number] // Change number if needed - + //TODO // Check if such a number already exist if (mMapOfROIName.find(nb) != mMapOfROIName.end()) { - std::cerr << "WARNING. A Roi already exist with the number " - << nb << ". I replace." << std::endl; + std::cerr << "WARNING. A Roi already exist with the number " + << nb << ". I replace." << std::endl; } // Add in map mMapOfROIName[nb] = name; } // DD(mMapOfROIName.size()); - + //---------------------------------- - // Read all ROI + // Read all ROI // 0x3006,0x0039 = [ ROI Contour Sequence ] gdcm::SeqEntry * roi_contour_seq=reader.GetSeqEntry(0x3006,0x0039); assert(roi_contour_seq); // TODO error message int n=0; - for (gdcm::SQItem* r=roi_contour_seq->GetFirstSQItem();r!=0;r=roi_contour_seq->GetNextSQItem()) { + for (gdcm::SQItem* r=roi_contour_seq->GetFirstSQItem(); r!=0; r=roi_contour_seq->GetNextSQItem()) { DicomRT_ROI * roi = new DicomRT_ROI; roi->Read(mMapOfROIName, r); mListOfROI.push_back(roi); @@ -198,12 +211,13 @@ void clitk::DicomRT_StructureSet::Read(const std::string & filename) { //-------------------------------------------------------------------- -int clitk::DicomRT_StructureSet::AddBinaryImageAsNewROI(vvImage::Pointer im, std::string n) { +int clitk::DicomRT_StructureSet::AddBinaryImageAsNewROI(vvImage::Pointer im, std::string n) +{ DD("AddBinaryImageAsNewROI"); // Search max ROI number int max = -1; for(unsigned int i=0; iGetROINumber() > max) + if (mListOfROI[i]->GetROINumber() > max) max = mListOfROI[i]->GetROINumber(); } DD(max); @@ -222,13 +236,13 @@ int clitk::DicomRT_StructureSet::AddBinaryImageAsNewROI(vvImage::Pointer im, std color.push_back(1); color.push_back(0); color.push_back(0); - + // Create ROI DicomRT_ROI * roi = new DicomRT_ROI; - roi->SetFromBinaryImage(im, - max, - oss.str(), - color); + roi->SetFromBinaryImage(im, + max, + oss.str(), + color); mListOfROI.push_back(roi); mMapOfROIIndex[mListOfROI.size()-1] = max; DD(mMapOfROIIndex[mListOfROI.size()-1]); diff --git a/common/clitkHisImageIO.cxx b/common/clitkHisImageIO.cxx index 702a1ba..e8b878c 100755 --- a/common/clitkHisImageIO.cxx +++ b/common/clitkHisImageIO.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,10 +23,10 @@ * @file clitkHisImageIO.cxx * @author Simon Rit * @date 16 Feb 2010 - * - * @brief - * - * + * + * @brief + * + * -------------------------------------------------*/ // Based on a true story by the Nederlands Kanker Instituut (AVS_HEIMANN.CPP from the 20090608) @@ -40,52 +40,61 @@ //-------------------------------------------------------------------- // Read Image Information -void clitk::HisImageIO::ReadImageInformation() { +void clitk::HisImageIO::ReadImageInformation() +{ // open file std::ifstream file(m_FileName.c_str(), std::ios::in | std::ios::binary); if ( file.fail() ) itkGenericExceptionMacro(<< "Could not open file (for reading): " << m_FileName); // read header - char header[HEADER_INFO_SIZE]; - file.read(header, HEADER_INFO_SIZE); - - if (header[0]!=0 || header[1]!=112 || header[2]!=68 || header[3]!=0) - { itkExceptionMacro(<< "clitk::HisImageIO::ReadImageInformation: file " << m_FileName << " not in Heimann HIS format version 100"); - return; - } - - int nrframes, type, ulx, uly, brx, bry; - m_HeaderSize = header[10] + (header[11]<<8); - ulx = header[12] + (header[13]<<8); - uly = header[14] + (header[15]<<8); - brx = header[16] + (header[17]<<8); - bry = header[18] + (header[19]<<8); - nrframes = header[20] + (header[21]<<8); - type = header[32] + (header[34]<<8); - - switch(type) - { case 4: SetComponentType(itk::ImageIOBase::USHORT); break; -// case 8: SetComponentType(itk::ImageIOBase::INT); break; -// case 16: SetComponentType(itk::ImageIOBase::FLOAT); break; -// case 32: SetComponentType(itk::ImageIOBase::INT); break; - default: SetComponentType(itk::ImageIOBase::USHORT); break; - } - - switch(nrframes) - { case 1: SetNumberOfDimensions(2); break; - default: SetNumberOfDimensions(3); break; + char header[HEADER_INFO_SIZE]; + file.read(header, HEADER_INFO_SIZE); + + if (header[0]!=0 || header[1]!=112 || header[2]!=68 || header[3]!=0) { + itkExceptionMacro(<< "clitk::HisImageIO::ReadImageInformation: file " << m_FileName << " not in Heimann HIS format version 100"); + return; + } + + int nrframes, type, ulx, uly, brx, bry; + m_HeaderSize = header[10] + (header[11]<<8); + ulx = header[12] + (header[13]<<8); + uly = header[14] + (header[15]<<8); + brx = header[16] + (header[17]<<8); + bry = header[18] + (header[19]<<8); + nrframes = header[20] + (header[21]<<8); + type = header[32] + (header[34]<<8); + + switch(type) { + case 4: + SetComponentType(itk::ImageIOBase::USHORT); + break; +// case 8: SetComponentType(itk::ImageIOBase::INT); break; +// case 16: SetComponentType(itk::ImageIOBase::FLOAT); break; +// case 32: SetComponentType(itk::ImageIOBase::INT); break; + default: + SetComponentType(itk::ImageIOBase::USHORT); + break; + } + + switch(nrframes) { + case 1: + SetNumberOfDimensions(2); + break; + default: + SetNumberOfDimensions(3); + break; } SetDimensions(0, bry-uly+1); SetDimensions(1, brx-ulx+1); - if (nrframes>1) - SetDimensions(2, nrframes); + if (nrframes>1) + SetDimensions(2, nrframes); } //// //-------------------------------------------------------------------- // Read Image Information -bool clitk::HisImageIO::CanReadFile(const char* FileNameToRead) +bool clitk::HisImageIO::CanReadFile(const char* FileNameToRead) { std::string filename(FileNameToRead); std::string filenameext = GetExtension(filename); @@ -95,7 +104,8 @@ bool clitk::HisImageIO::CanReadFile(const char* FileNameToRead) //-------------------------------------------------------------------- // Read Image Content -void clitk::HisImageIO::Read(void * buffer) { +void clitk::HisImageIO::Read(void * buffer) +{ // open file std::ifstream file(m_FileName.c_str(), std::ios::in | std::ios::binary); if ( file.fail() ) @@ -106,8 +116,8 @@ void clitk::HisImageIO::Read(void * buffer) { if ( file.fail() ) itkExceptionMacro(<<"File seek failed (His Read)"); - - file.read((char*)buffer, GetImageSizeInBytes()); + + file.read((char*)buffer, GetImageSizeInBytes()); if ( file.fail() ) itkExceptionMacro(<<"Read failed: Wanted " << GetImageSizeInBytes() @@ -115,10 +125,11 @@ void clitk::HisImageIO::Read(void * buffer) { << file.gcount() << " bytes. The current state is: " << file.rdstate()); } - + //-------------------------------------------------------------------- bool clitk::HisImageIO::CanWriteFile(const char* FileNameToWrite) -{ std::string filename(FileNameToWrite); +{ + std::string filename(FileNameToWrite); std::string filenameext = GetExtension(filename); if (filenameext != std::string("his")) return false; return true; @@ -132,51 +143,52 @@ void clitk::HisImageIO::Write(const void* buffer) if ( file.fail() ) itkGenericExceptionMacro(<< "Could not open file (for writing): " << m_FileName); - m_HeaderSize = HEADER_INFO_SIZE + 32; - char szHeader[HEADER_INFO_SIZE + 32] = { - 0x00, 0x70, 0x44, 0x00, 0x64, 0x00, 0x64, 0x00, 0x20, 0x00, 0x20, 0x00, 0x01, 0x00, 0x01, 0x00, - 0x00, 0x04, 0x00, 0x04, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6A, 0x18, 0x41, - 0x04, 0x00, 0x40, 0x5F, 0x48, 0x01, 0x40, 0x00, 0x86, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x08, 0x63, 0x13, 0x00, 0xE8, 0x51, 0x13, 0x00, 0x5C, 0xE7, 0x12, 0x00, - 0xFE, 0x2A, 0x49, 0x5F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00}; - - /* Fill into the header the essentials - The 'iheader' in previous module is fixed to 0x20, and is included in szHeader. - The 'ulx' and 'uly' are fixed to 0x01, so that 'brx' and 'bry' reflect the dimensions of - the image. - */ - const unsigned int ndim = GetNumberOfDimensions(); - if ((ndim < 2) || (ndim > 3)) - itkExceptionMacro( <<"Only 2D or 3D support"); - - szHeader[16] = (char)(GetDimensions(0) % 256); // X-size lsb - szHeader[17] = (char)(GetDimensions(0) / 256); // X-size msb - szHeader[18] = (char)(GetDimensions(1) % 256); // Y-size lsb - szHeader[19] = (char)(GetDimensions(1) / 256); // Y-size msb - if (ndim == 3) - { szHeader[20] = (char)(GetDimensions(0) % 256); // NbFrames lsb - szHeader[21] = (char)(GetDimensions(0) / 256); // NbFrames msb - } - - switch (GetComponentType()) - { case itk::ImageIOBase::USHORT: - szHeader[32] = 4; - break; - //case AVS_TYPE_INTEGER: - // szHeader[32] = 8; - // break; - //case AVS_TYPE_REAL: - // szHeader[32] = 16; - // break; - default: - itkExceptionMacro(<< "Unsupported field type"); - break; - } - - file.write(szHeader, m_HeaderSize); - file.write((const char *)buffer, GetImageSizeInBytes()); + m_HeaderSize = HEADER_INFO_SIZE + 32; + char szHeader[HEADER_INFO_SIZE + 32] = { + 0x00, 0x70, 0x44, 0x00, 0x64, 0x00, 0x64, 0x00, 0x20, 0x00, 0x20, 0x00, 0x01, 0x00, 0x01, 0x00, + 0x00, 0x04, 0x00, 0x04, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6A, 0x18, 0x41, + 0x04, 0x00, 0x40, 0x5F, 0x48, 0x01, 0x40, 0x00, 0x86, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, 0x63, 0x13, 0x00, 0xE8, 0x51, 0x13, 0x00, 0x5C, 0xE7, 0x12, 0x00, + 0xFE, 0x2A, 0x49, 0x5F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00 + }; + + /* Fill into the header the essentials + The 'iheader' in previous module is fixed to 0x20, and is included in szHeader. + The 'ulx' and 'uly' are fixed to 0x01, so that 'brx' and 'bry' reflect the dimensions of + the image. + */ + const unsigned int ndim = GetNumberOfDimensions(); + if ((ndim < 2) || (ndim > 3)) + itkExceptionMacro( <<"Only 2D or 3D support"); + + szHeader[16] = (char)(GetDimensions(0) % 256); // X-size lsb + szHeader[17] = (char)(GetDimensions(0) / 256); // X-size msb + szHeader[18] = (char)(GetDimensions(1) % 256); // Y-size lsb + szHeader[19] = (char)(GetDimensions(1) / 256); // Y-size msb + if (ndim == 3) { + szHeader[20] = (char)(GetDimensions(0) % 256); // NbFrames lsb + szHeader[21] = (char)(GetDimensions(0) / 256); // NbFrames msb + } + + switch (GetComponentType()) { + case itk::ImageIOBase::USHORT: + szHeader[32] = 4; + break; + //case AVS_TYPE_INTEGER: + // szHeader[32] = 8; + // break; + //case AVS_TYPE_REAL: + // szHeader[32] = 16; + // break; + default: + itkExceptionMacro(<< "Unsupported field type"); + break; + } + + file.write(szHeader, m_HeaderSize); + file.write((const char *)buffer, GetImageSizeInBytes()); file.close(); } //// diff --git a/common/clitkHisImageIOFactory.cxx b/common/clitkHisImageIOFactory.cxx index 9dae8a6..963a7c5 100755 --- a/common/clitkHisImageIOFactory.cxx +++ b/common/clitkHisImageIOFactory.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkHisImageIOFactory.cxx * @author Simon Rit * @date 16 Feb 2010 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ #include "clitkHisImageIOFactory.h" @@ -33,7 +33,7 @@ #include //==================================================================== -clitk::HisImageIOFactory::HisImageIOFactory() +clitk::HisImageIOFactory::HisImageIOFactory() { this->RegisterOverride("itkImageIOBase", "HisImageIO", diff --git a/common/clitkIO.cxx b/common/clitkIO.cxx index 227e2bb..39b8514 100755 --- a/common/clitkIO.cxx +++ b/common/clitkIO.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,10 +20,10 @@ * @file clitkHisImageIO.cxx * @author Simon Rit * @date 16 Feb 2010 - * - * @brief - * - * + * + * @brief + * + * -------------------------------------------------*/ // std include @@ -49,10 +49,10 @@ // Register factories void clitk::RegisterClitkFactories() { - itk::ImageIOFactory::RegisterBuiltInFactories(); - clitk::VoxImageIOFactory::RegisterOneFactory(); - clitk::VfImageIOFactory::RegisterOneFactory(); - clitk::HisImageIOFactory::RegisterOneFactory(); - clitk::XdrImageIOFactory::RegisterOneFactory(); + itk::ImageIOFactory::RegisterBuiltInFactories(); + clitk::VoxImageIOFactory::RegisterOneFactory(); + clitk::VfImageIOFactory::RegisterOneFactory(); + clitk::HisImageIOFactory::RegisterOneFactory(); + clitk::XdrImageIOFactory::RegisterOneFactory(); } //// diff --git a/common/clitkImageCommon.cxx b/common/clitkImageCommon.cxx index c9085c6..03aa9b6 100644 --- a/common/clitkImageCommon.cxx +++ b/common/clitkImageCommon.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,26 +22,27 @@ * @file clitkImageCommon.cxx * @author David Sarrut * @date 02 Oct 2007 14:30:47 - * - * @brief - * - * + * + * @brief + * + * ------------------------------------------------=*/ #include "clitkImageCommon.h" //-------------------------------------------------------------------- -void clitk::ReadImageDimensionAndPixelType(const std::string & filename, - int & dimension, - std::string & pixeType) { - itk::ImageIOBase::Pointer genericReader = +void clitk::ReadImageDimensionAndPixelType(const std::string & filename, + int & dimension, + std::string & pixeType) +{ + itk::ImageIOBase::Pointer genericReader = itk::ImageIOFactory::CreateImageIO(filename.c_str(), itk::ImageIOFactory::ReadMode); if (!genericReader) { std::cerr << "Image file format unknown while reading " << filename << std::endl; exit(0); } genericReader->SetFileName(filename.c_str()); - genericReader->ReadImageInformation(); + genericReader->ReadImageInformation(); pixeType = genericReader->GetComponentTypeAsString(genericReader->GetComponentType()); dimension = genericReader->GetNumberOfDimensions(); } @@ -49,17 +50,18 @@ void clitk::ReadImageDimensionAndPixelType(const std::string & filename, //-------------------------------------------------------------------- -void clitk::ReadImageDimensionAndPixelType(const std::string & filename, - int & dimension, - std::string & pixeType, int & components) { - itk::ImageIOBase::Pointer genericReader = +void clitk::ReadImageDimensionAndPixelType(const std::string & filename, + int & dimension, + std::string & pixeType, int & components) +{ + itk::ImageIOBase::Pointer genericReader = itk::ImageIOFactory::CreateImageIO(filename.c_str(), itk::ImageIOFactory::ReadMode); if (!genericReader) { std::cerr << "Image file format unknown while reading " << filename << std::endl; exit(0); } genericReader->SetFileName(filename.c_str()); - genericReader->ReadImageInformation(); + genericReader->ReadImageInformation(); pixeType = genericReader->GetComponentTypeAsString(genericReader->GetComponentType()); dimension = genericReader->GetNumberOfDimensions(); components= genericReader->GetNumberOfComponents(); @@ -67,9 +69,10 @@ void clitk::ReadImageDimensionAndPixelType(const std::string & filename, //-------------------------------------------------------------------- //-------------------------------------------------------------------- -// Read a dicom header -gdcm::File * clitk::readDicomHeader(const std::string & filename, - const bool verbose) { +// Read a dicom header +gdcm::File * clitk::readDicomHeader(const std::string & filename, + const bool verbose) +{ if (verbose) { std::cout << "Reading DICOM <" << filename << ">" << std::endl; } @@ -82,17 +85,16 @@ gdcm::File * clitk::readDicomHeader(const std::string & filename, //-------------------------------------------------------------------- //-------------------------------------------------------------------- -itk::ImageIOBase::Pointer clitk::readImageHeader(const std::string & filename, bool exit_on_error) { +itk::ImageIOBase::Pointer clitk::readImageHeader(const std::string & filename, bool exit_on_error) +{ itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(filename.c_str(), itk::ImageIOFactory::ReadMode); if (!reader) { - if (exit_on_error) //default behavior for tools who don't handle the problem - { - std::cerr << "Error reading file " << filename << ", exiting immediately" << std::endl; - std::exit(-1); - } - else - return NULL; + if (exit_on_error) { //default behavior for tools who don't handle the problem + std::cerr << "Error reading file " << filename << ", exiting immediately" << std::endl; + std::exit(-1); + } else + return NULL; } reader->SetFileName(filename); reader->ReadImageInformation(); @@ -101,7 +103,8 @@ itk::ImageIOBase::Pointer clitk::readImageHeader(const std::string & filename, b //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::printImageHeader(itk::ImageIOBase::Pointer header, std::ostream & os, const int level) { +void clitk::printImageHeader(itk::ImageIOBase::Pointer header, std::ostream & os, const int level) +{ unsigned int dim = header->GetNumberOfDimensions(); std::string pixelTypeName = header->GetComponentTypeAsString(header->GetComponentType()); std::vector inputSize; @@ -115,7 +118,7 @@ void clitk::printImageHeader(itk::ImageIOBase::Pointer header, std::ostream & os inputSize[i] = header->GetDimensions(i); inputOrigin[i] = header->GetOrigin(i); } - int pixelSize = + int pixelSize = clitk::GetTypeSizeFromString(header->GetComponentTypeAsString(header->GetComponentType())); unsigned int nbOfComponents = header->GetNumberOfComponents(); if (level == 0) { @@ -129,13 +132,12 @@ void clitk::printImageHeader(itk::ImageIOBase::Pointer header, std::ostream & os << " "; for(unsigned int i=0; i< dim-1; i++) os << inputSpacing[i] << "x"; - os << inputSpacing[dim-1] + os << inputSpacing[dim-1] << " "; for(unsigned int i=0; i< dim-1; i++) os << inputOrigin[i] << "x"; os << inputOrigin[dim-1] << " "; - } - else { + } else { os << "Dim = " << dim << "D" << std::endl; os << "PixelType = " << pixelTypeName << std::endl; if (nbOfComponents > 1) @@ -154,19 +156,19 @@ void clitk::printImageHeader(itk::ImageIOBase::Pointer header, std::ostream & os os << "# voxels = " << header->GetImageSizeInPixels() << std::endl; os << "Size (mm) = "; for(unsigned int i=0; i< dim; i++) { - os << inputSize[i]*inputSpacing[i] << " "; + os << inputSize[i]*inputSpacing[i] << " "; } os << "mm" << std::endl; os << "Origin (mm)= "; for(unsigned int i=0; i< dim; i++) { - os << inputOrigin[i] << " "; + os << inputOrigin[i] << " "; } os << "mm" << std::endl; os << "Volume = "; double vol=1.0; for(unsigned int i=0; i< dim; i++) { - vol *= inputSize[i]*inputSpacing[i]/10.0; + vol *= inputSize[i]*inputSpacing[i]/10.0; } os << vol << " cc" << std::endl; int mem = header->GetImageSizeInPixels()*pixelSize*nbOfComponents; @@ -174,16 +176,16 @@ void clitk::printImageHeader(itk::ImageIOBase::Pointer header, std::ostream & os double memMb = (double)mem/1024.0/1024.0; double memGb = (double)mem/1024.0/1024.0/1024.0; if (lrint(memKb) <= 0) - os << "Memory = " << mem << " bytes" << std::endl; + os << "Memory = " << mem << " bytes" << std::endl; else { - if (lrint(memMb) <= 0) - os << "Memory = " << memKb << " Kb (" << mem << " bytes)" << std::endl; - else { - if (lrint(memGb) <= 0) - os << "Memory = " << memMb << " Mb (" << mem << " bytes)" << std::endl; - else - os << "Memory = " << memGb << " Gb (" << mem << " bytes)" << std::endl; - } + if (lrint(memMb) <= 0) + os << "Memory = " << memKb << " Kb (" << mem << " bytes)" << std::endl; + else { + if (lrint(memGb) <= 0) + os << "Memory = " << memMb << " Mb (" << mem << " bytes)" << std::endl; + else + os << "Memory = " << memGb << " Gb (" << mem << " bytes)" << std::endl; + } } } } diff --git a/common/clitkImageCommon.txx b/common/clitkImageCommon.txx index e682593..5fb4b86 100644 --- a/common/clitkImageCommon.txx +++ b/common/clitkImageCommon.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -21,7 +21,8 @@ //-------------------------------------------------------------------- template -typename itk::Image::Pointer NewImage1D(int vsize, double vspacing) { +typename itk::Image::Pointer NewImage1D(int vsize, double vspacing) +{ typedef itk::Image ImageType; typename ImageType::Pointer g = ImageType::New(); typename ImageType::SizeType size; @@ -38,16 +39,19 @@ typename itk::Image::Pointer NewImage1D(int vsize, double vspacing) //-------------------------------------------------------------------- template -typename itk::Image::Pointer NewImage2D(int sx, int sy, double dx, double dy) { +typename itk::Image::Pointer NewImage2D(int sx, int sy, double dx, double dy) +{ typedef itk::Image ImageType; typename ImageType::Pointer g = ImageType::New(); typename ImageType::SizeType size; - size[0] = sx; size[1] = sy; + size[0] = sx; + size[1] = sy; typename ImageType::RegionType region; region.SetSize(size); g->SetRegions(region); typename ImageType::SpacingType spacing; - spacing[0] = dx; spacing[1] = dy; + spacing[0] = dx; + spacing[1] = dy; g->SetSpacing(spacing); return g; } @@ -55,16 +59,21 @@ typename itk::Image::Pointer NewImage2D(int sx, int sy, double dx, //-------------------------------------------------------------------- template -typename itk::Image::Pointer NewImage3D(int sx, int sy, int sz, double dx, double dy, double dz) { +typename itk::Image::Pointer NewImage3D(int sx, int sy, int sz, double dx, double dy, double dz) +{ typedef itk::Image ImageType; typename ImageType::Pointer g = ImageType::New(); typename ImageType::SizeType size; - size[0] = sx; size[1] = sy; size[2] = sz; + size[0] = sx; + size[1] = sy; + size[2] = sz; typename ImageType::RegionType region; region.SetSize(size); g->SetRegions(region); typename ImageType::SpacingType spacing; - spacing[0] = dx; spacing[1] = dy; spacing[2] = dz; + spacing[0] = dx; + spacing[1] = dy; + spacing[2] = dz; g->SetSpacing(spacing); return g; } @@ -72,16 +81,23 @@ typename itk::Image::Pointer NewImage3D(int sx, int sy, int sz, dou //-------------------------------------------------------------------- template -typename itk::Image::Pointer NewImage4D(int sx, int sy, int sz, int st, double dx, double dy, double dz, double dt) { +typename itk::Image::Pointer NewImage4D(int sx, int sy, int sz, int st, double dx, double dy, double dz, double dt) +{ typedef itk::Image ImageType; typename ImageType::Pointer g = ImageType::New(); typename ImageType::SizeType size; - size[0] = sx; size[1] = sy; size[2] = sz; size[3] = st; + size[0] = sx; + size[1] = sy; + size[2] = sz; + size[3] = st; typename ImageType::RegionType region; region.SetSize(size); g->SetRegions(region); typename ImageType::SpacingType spacing; - spacing[0] = dx; spacing[1] = dy; spacing[2] = dz; spacing[3] = dt; + spacing[0] = dx; + spacing[1] = dy; + spacing[2] = dz; + spacing[3] = dt; g->SetSpacing(spacing); return g; } @@ -90,10 +106,11 @@ typename itk::Image::Pointer NewImage4D(int sx, int sy, int sz, int //-------------------------------------------------------------------- template -typename ImageType::Pointer NewImageLike(const typename ImageType::Pointer input, bool allocate) { +typename ImageType::Pointer NewImageLike(const typename ImageType::Pointer input, bool allocate) +{ typename ImageType::Pointer output = ImageType::New(); output->CopyInformation(input); - output->SetRegions(input->GetLargestPossibleRegion()); + output->SetRegions(input->GetLargestPossibleRegion()); if (allocate) output->Allocate(); return output; } @@ -102,14 +119,15 @@ typename ImageType::Pointer NewImageLike(const typename ImageType::Pointer input //-------------------------------------------------------------------- template -void CopyValues(const typename ImageType::Pointer input, - typename ImageType::Pointer output) { - typedef itk::ImageRegionConstIterator ConstIteratorType; +void CopyValues(const typename ImageType::Pointer input, + typename ImageType::Pointer output) +{ + typedef itk::ImageRegionConstIterator ConstIteratorType; ConstIteratorType pi(input,input->GetLargestPossibleRegion()); - pi.GoToBegin(); - typedef itk::ImageRegionIterator IteratorType; + pi.GoToBegin(); + typedef itk::ImageRegionIterator IteratorType; IteratorType po(output,input->GetLargestPossibleRegion()); - po.GoToBegin(); + po.GoToBegin(); while (!pi.IsAtEnd()) { po.Set(pi.Get()); ++pi; @@ -121,17 +139,17 @@ void CopyValues(const typename ImageType::Pointer input, //-------------------------------------------------------------------- template -typename ImageType::Pointer readImage(const std::string & filename, const bool verbose) { +typename ImageType::Pointer readImage(const std::string & filename, const bool verbose) +{ typedef itk::ImageFileReader ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(filename.c_str()); if (verbose) { std::cout << "Reading [" << filename << "] ... " << std::endl; } - try { - reader->Update(); - } - catch(itk::ExceptionObject & err) { + try { + reader->Update(); + } catch(itk::ExceptionObject & err) { std::cerr << "Exception while reading image [" << filename << "]" << std::endl; std::cerr << err << std::endl; exit(0); @@ -142,8 +160,9 @@ typename ImageType::Pointer readImage(const std::string & filename, const bool v //-------------------------------------------------------------------- template -typename ImageType::Pointer readImage(const std::vector & filenames, - const bool verbose) { +typename ImageType::Pointer readImage(const std::vector & filenames, + const bool verbose) +{ if (filenames.size() == 1) return readImage(filenames[0], verbose); typedef itk::ImageSeriesReader ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); @@ -152,11 +171,10 @@ typename ImageType::Pointer readImage(const std::vector & filenames std::cout << "Reading " << filenames[0] << " and others ..." << std::endl; } try { - reader->Update(); - } - catch( itk::ExceptionObject & err ) { + reader->Update(); + } catch( itk::ExceptionObject & err ) { std::cerr << "Error while reading " << filenames[0] - << " or other files ..." << err << std::endl; + << " or other files ..." << err << std::endl; exit(0); } return reader->GetOutput(); @@ -165,7 +183,8 @@ typename ImageType::Pointer readImage(const std::vector & filenames //-------------------------------------------------------------------- template -void writeImage(const typename ImageType::Pointer image, const std::string & filename, const bool verbose) { +void writeImage(const typename ImageType::Pointer image, const std::string & filename, const bool verbose) +{ typedef itk::ImageFileWriter WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename.c_str()); @@ -173,10 +192,9 @@ void writeImage(const typename ImageType::Pointer image, const std::string & fil if (verbose) { std::cout << "Writing [" << filename << "] ... " << std::endl; } - try { - writer->Update(); - } - catch( itk::ExceptionObject & err ) { + try { + writer->Update(); + } catch( itk::ExceptionObject & err ) { std::cerr << "Exception while writing image [" << filename << "]" << std::endl; std::cerr << err << std::endl; exit(-1); @@ -186,7 +204,8 @@ void writeImage(const typename ImageType::Pointer image, const std::string & fil //-------------------------------------------------------------------- template -void writeImage(const ImageType* image, const std::string & filename, const bool verbose) { +void writeImage(const ImageType* image, const std::string & filename, const bool verbose) +{ typedef itk::ImageFileWriter WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename.c_str()); @@ -194,10 +213,9 @@ void writeImage(const ImageType* image, const std::string & filename, const bool if (verbose) { std::cout << "Writing [" << filename << "] ... " << std::endl; } - try { - writer->Update(); - } - catch( itk::ExceptionObject & err ) { + try { + writer->Update(); + } catch( itk::ExceptionObject & err ) { std::cerr << "Exception while writing image [" << filename << "]" << std::endl; std::cerr << err << std::endl; exit(-1); @@ -215,8 +233,8 @@ void writeImage(const ImageType* image, const std::string & filename, const bool // if (verbose) { // std::cout << "Writing [" << filename << "] ... " << std::endl; // } -// try { -// writer->Update(); +// try { +// writer->Update(); // } // catch( itk::ExceptionObject & err ) { // std::cerr << "Exception while writing image [" << filename << "]" << std::endl; @@ -230,8 +248,8 @@ void writeImage(const ImageType* image, const std::string & filename, const bool //-------------------------------------------------------------------- // Compute the number of different intensities in an image template -int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, - std::vector & l) +int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, + std::vector & l) { //std::set listOfIntensities; std::map listOfIntensities; @@ -241,14 +259,14 @@ int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, pi.Begin(); while (!pi.IsAtEnd()) { if (!listOfIntensities[pi.Get()]) listOfIntensities[pi.Get()] = true; - // if (std::find(listOfIntensities.begin(), - // listOfIntensities.end(), + // if (std::find(listOfIntensities.begin(), + // listOfIntensities.end(), // pi.Get()) == listOfIntensities.end()) { // listOfIntensities.insert(pi.Get()); // } ++pi; } - + //typename std::set::const_iterator ppi = listOfIntensities.begin(); typename std::map::const_iterator ppi = listOfIntensities.begin(); while (ppi != listOfIntensities.end()) { @@ -259,21 +277,22 @@ int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, return listOfIntensities.size(); } //-------------------------------------------------------------------- - + //-------------------------------------------------------------------- template -void ComputeWeightsOfEachClasses(const typename InputImageType::Pointer & input, - const typename MaskImageType::Pointer & mask, - const std::vector & listOfIntensities, - std::map > & mapOfLabelsAndWeights) { +void ComputeWeightsOfEachClasses(const typename InputImageType::Pointer & input, + const typename MaskImageType::Pointer & mask, + const std::vector & listOfIntensities, + std::map > & mapOfLabelsAndWeights) +{ // Check size if (input->GetLargestPossibleRegion() != mask->GetLargestPossibleRegion()) { itkGenericExceptionMacro(<< "Input and mask images have not the same size" - << std::endl - << "Input = " << input->GetLargestPossibleRegion() - << std::endl - << "Mask = " << mask->GetLargestPossibleRegion()); + << std::endl + << "Input = " << input->GetLargestPossibleRegion() + << std::endl + << "Mask = " << mask->GetLargestPossibleRegion()); } // reset weights list diff --git a/common/clitkImageToImageGenericFilter.cxx b/common/clitkImageToImageGenericFilter.cxx index 4b702f4..8561f69 100644 --- a/common/clitkImageToImageGenericFilter.cxx +++ b/common/clitkImageToImageGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -102,7 +102,7 @@ // } // else // assert(false); //No input image, shouldn't happen - + // if (mIOVerbose) { // std::cout << "Input is " << mDim << "D " << mPixelTypeName << "." << std::endl; // } @@ -162,8 +162,8 @@ // //-------------------------------------------------------------------- // void clitk::ImageToImageGenericFilterBase::ImageTypeError() { -// std::cerr << "**Error** The filter <" << mFilterName << "> is not available for " -// << mDim << "D images with pixel=" +// std::cerr << "**Error** The filter <" << mFilterName << "> is not available for " +// << mDim << "D images with pixel=" // << mPixelTypeName << " and " // << mNbOfComponents << " component." << std::endl; // std::cerr << GetAvailableImageTypes(); diff --git a/common/clitkImageToImageGenericFilter.txx b/common/clitkImageToImageGenericFilter.txx index 2592c98..51256da 100644 --- a/common/clitkImageToImageGenericFilter.txx +++ b/common/clitkImageToImageGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,7 +17,7 @@ ======================================================================-====*/ template clitk::ImageToImageGenericFilter::ImageToImageGenericFilter(std::string filterName) : - ImageToImageGenericFilterBase(filterName), + ImageToImageGenericFilterBase(filterName), mImageTypesManager(static_cast(this)) { } @@ -26,9 +26,10 @@ clitk::ImageToImageGenericFilter::ImageToImageGenericFilter(std::str //-------------------------------------------------------------------- template -bool clitk::ImageToImageGenericFilter::Update() { - GetInputImageDimensionAndPixelType(mDim,mPixelTypeName,mNbOfComponents); - +bool clitk::ImageToImageGenericFilter::Update() +{ + GetInputImageDimensionAndPixelType(mDim,mPixelTypeName,mNbOfComponents); + // Check ImageType if (!CheckImageType()) { if (mFailOnImageTypeError) ImageTypeError(); @@ -45,7 +46,8 @@ bool clitk::ImageToImageGenericFilter::Update() { //-------------------------------------------------------------------- template bool clitk::ImageToImageGenericFilter::CheckImageType(unsigned int dim, unsigned int ncomp, std::string pixeltype) -{ //SR: commented line creates an element in mMapOfImageTypeToFunction which, even if 0, is confusing, e.g. for GetAvailableImageTypes +{ + //SR: commented line creates an element in mMapOfImageTypeToFunction which, even if 0, is confusing, e.g. for GetAvailableImageTypes //return static_cast(mImageTypesManager.mMapOfImageTypeToFunction[dim][ncomp][pixeltype]); typename ImageTypesManager::MapOfImageDimensionToFunctionType &m = mImageTypesManager.mMapOfImageTypeToFunction; return (m .find(dim) != m.end() && @@ -66,10 +68,11 @@ bool clitk::ImageToImageGenericFilter::CheckImageType() //-------------------------------------------------------------------- template -std::string clitk::ImageToImageGenericFilter::GetAvailableImageTypes() { +std::string clitk::ImageToImageGenericFilter::GetAvailableImageTypes() +{ std::ostringstream oss; oss << "The filter <" << mFilterName << "> manages:" << std::endl; - + typedef typename ImageTypesManager::MapOfImageComponentsToFunctionType::const_iterator MCompItType; typedef typename ImageTypesManager::MapOfImageDimensionToFunctionType::const_iterator MDimItType; typedef typename ImageTypesManager::MapOfPixelTypeToFunctionType::const_iterator MPixelItType; @@ -79,8 +82,8 @@ std::string clitk::ImageToImageGenericFilter::GetAvailableImageTypes for (MCompItType j=(*i).second.begin(); j!= (*i).second.end(); j++) { for (MPixelItType k=(*j).second.begin(); k!= (*j).second.end(); k++) { oss << "Dim: " << (*i).first; - if ((*j).first != 1) oss << ", Components: " << (*j).first; - oss << ", Type: " << (*k).first << std::endl; + if ((*j).first != 1) oss << ", Components: " << (*j).first; + oss << ", Type: " << (*k).first << std::endl; } } } diff --git a/common/clitkImageToImageGenericFilterBase.cxx b/common/clitkImageToImageGenericFilterBase.cxx index 12781e7..bf68c9c 100644 --- a/common/clitkImageToImageGenericFilterBase.cxx +++ b/common/clitkImageToImageGenericFilterBase.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -25,7 +25,8 @@ clitk::ImageToImageGenericFilterBase::~ImageToImageGenericFilterBase() {} //-------------------------------------------------------------------- clitk::ImageToImageGenericFilterBase::ImageToImageGenericFilterBase(std::string n) - :mIOVerbose(false) { + :mIOVerbose(false) +{ mFilterName = n; mFailOnImageTypeError = true; mReadOnDisk = true; @@ -34,21 +35,24 @@ clitk::ImageToImageGenericFilterBase::ImageToImageGenericFilterBase(std::string //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::SetInputFilenames(const std::vector & filenames) { - mInputFilenames=filenames; +void clitk::ImageToImageGenericFilterBase::SetInputFilenames(const std::vector & filenames) +{ + mInputFilenames=filenames; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::EnableReadOnDisk(bool b) { +void clitk::ImageToImageGenericFilterBase::EnableReadOnDisk(bool b) +{ mReadOnDisk = b; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::SetInputFilename(const std::string & filename) { +void clitk::ImageToImageGenericFilterBase::SetInputFilename(const std::string & filename) +{ std::vector f; f.push_back(filename); SetInputFilenames(f); @@ -57,14 +61,16 @@ void clitk::ImageToImageGenericFilterBase::SetInputFilename(const std::string & //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::AddInputFilename(const std::string & filename) { +void clitk::ImageToImageGenericFilterBase::AddInputFilename(const std::string & filename) +{ mInputFilenames.push_back(filename); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::SetOutputFilename(const std::string & filename) { +void clitk::ImageToImageGenericFilterBase::SetOutputFilename(const std::string & filename) +{ mOutputFilenames.clear(); mOutputFilenames.push_back(filename); } @@ -82,8 +88,8 @@ void clitk::ImageToImageGenericFilterBase::AddOutputFilename(const std::string & //-------------------------------------------------------------------- void clitk::ImageToImageGenericFilterBase::SetOutputFilenames(const std::vector & filenames) { - mOutputFilenames.clear(); - std::copy(filenames.begin(),filenames.end(),mOutputFilenames.begin()); + mOutputFilenames.clear(); + std::copy(filenames.begin(),filenames.end(),mOutputFilenames.begin()); } //-------------------------------------------------------------------- @@ -91,29 +97,28 @@ void clitk::ImageToImageGenericFilterBase::SetOutputFilenames(const std::vector< //-------------------------------------------------------------------- std::string clitk::ImageToImageGenericFilterBase::GetOutputFilename() { - assert(mOutputFilenames.size() == 1); - return mOutputFilenames.front(); + assert(mOutputFilenames.size() == 1); + return mOutputFilenames.front(); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- void clitk::ImageToImageGenericFilterBase::GetInputImageDimensionAndPixelType(unsigned int& dim, \ - std::string& pixeltype,unsigned int& components) + std::string& pixeltype,unsigned int& components) { if (mReadOnDisk && mInputFilenames.size()) { int comp_temp,dim_temp; //clitkCommonImage takes ints ReadImageDimensionAndPixelType(mInputFilenames[0], dim_temp, pixeltype,comp_temp); - components=comp_temp; dim=dim_temp; - } - else { + components=comp_temp; + dim=dim_temp; + } else { if (mInputVVImages.size()) { pixeltype=mInputVVImages[0]->GetScalarTypeAsString(); dim=mInputVVImages[0]->GetNumberOfDimensions(); components=mInputVVImages[0]->GetNumberOfScalarComponents(); - } - else - assert(false); //No input image, shouldn't happen + } else + assert(false); //No input image, shouldn't happen } if (mIOVerbose) { std::cout << "Input is " << mDim << "D " << mPixelTypeName << "." << std::endl; @@ -125,8 +130,8 @@ void clitk::ImageToImageGenericFilterBase::GetInputImageDimensionAndPixelType(un //-------------------------------------------------------------------- vvImage::Pointer clitk::ImageToImageGenericFilterBase::GetOutputVVImage () { - assert(mOutputVVImages.size()); - return mOutputVVImages[0]; + assert(mOutputVVImages.size()); + return mOutputVVImages[0]; } //-------------------------------------------------------------------- @@ -134,7 +139,7 @@ vvImage::Pointer clitk::ImageToImageGenericFilterBase::GetOutputVVImage () //-------------------------------------------------------------------- std::vector clitk::ImageToImageGenericFilterBase::GetOutputVVImages() { - return mOutputVVImages; + return mOutputVVImages; } //-------------------------------------------------------------------- @@ -142,8 +147,8 @@ std::vector clitk::ImageToImageGenericFilterBase::GetOutputVVI //-------------------------------------------------------------------- void clitk::ImageToImageGenericFilterBase::SetInputVVImage (vvImage::Pointer input) { - mInputVVImages.clear(); - mInputVVImages.push_back(input); + mInputVVImages.clear(); + mInputVVImages.push_back(input); } //-------------------------------------------------------------------- @@ -151,7 +156,7 @@ void clitk::ImageToImageGenericFilterBase::SetInputVVImage (vvImage::Pointer inp //-------------------------------------------------------------------- void clitk::ImageToImageGenericFilterBase::AddInputVVImage (vvImage::Pointer input) { - mInputVVImages.push_back(input); + mInputVVImages.push_back(input); } //-------------------------------------------------------------------- @@ -159,13 +164,14 @@ void clitk::ImageToImageGenericFilterBase::AddInputVVImage (vvImage::Pointer inp //-------------------------------------------------------------------- void clitk::ImageToImageGenericFilterBase::SetInputVVImages (std::vector input) { - mInputVVImages=input; + mInputVVImages=input; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::PrintAvailableImageTypes() { +void clitk::ImageToImageGenericFilterBase::PrintAvailableImageTypes() +{ std::cout << GetAvailableImageTypes(); } //-------------------------------------------------------------------- @@ -173,9 +179,10 @@ void clitk::ImageToImageGenericFilterBase::PrintAvailableImageTypes() { //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::ImageTypeError() { - std::cerr << "**Error** The filter <" << mFilterName << "> is not available for " - << mDim << "D images with pixel=" +void clitk::ImageToImageGenericFilterBase::ImageTypeError() +{ + std::cerr << "**Error** The filter <" << mFilterName << "> is not available for " + << mDim << "D images with pixel=" << mPixelTypeName << " and " << mNbOfComponents << " component." << std::endl; std::cerr << GetAvailableImageTypes(); @@ -185,7 +192,8 @@ void clitk::ImageToImageGenericFilterBase::ImageTypeError() { //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::SetImageTypeError() { +void clitk::ImageToImageGenericFilterBase::SetImageTypeError() +{ std::cerr << "TODO ! " << std::endl; exit(0); } @@ -193,22 +201,25 @@ void clitk::ImageToImageGenericFilterBase::SetImageTypeError() { //-------------------------------------------------------------------- -const std::string & clitk::ImageToImageGenericFilterBase::GetFilterName() { - return mFilterName; +const std::string & clitk::ImageToImageGenericFilterBase::GetFilterName() +{ + return mFilterName; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::SetFilterName(std::string & n) { - mFilterName = n; +void clitk::ImageToImageGenericFilterBase::SetFilterName(std::string & n) +{ + mFilterName = n; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageToImageGenericFilterBase::SetIOVerbose(bool b) { - mIOVerbose = b; +void clitk::ImageToImageGenericFilterBase::SetIOVerbose(bool b) +{ + mIOVerbose = b; } //-------------------------------------------------------------------- @@ -260,13 +271,13 @@ DEF_SetNextOutput_And_GetInput(double, 4); //-------------------------------------------------------------------- -template -void clitk::ImageToImageGenericFilterBase::SetNextOutput(typename ImageType::Pointer output) { - if (mOutputFilenames.size()) - { - clitk::writeImage(output, mOutputFilenames.front(), mIOVerbose); - mOutputFilenames.pop_front(); - } +template +void clitk::ImageToImageGenericFilterBase::SetNextOutput(typename ImageType::Pointer output) +{ + if (mOutputFilenames.size()) { + clitk::writeImage(output, mOutputFilenames.front(), mIOVerbose); + mOutputFilenames.pop_front(); + } if (mInputVVImages.size()) //We assume that if a vv image is set as input, we want one as the output mOutputVVImages.push_back(vvImageFromITK(output)); } @@ -274,19 +285,18 @@ void clitk::ImageToImageGenericFilterBase::SetNextOutput(typename ImageType::Poi //-------------------------------------------------------------------- -template -typename ImageType::Pointer clitk::ImageToImageGenericFilterBase::GetInput(unsigned int n) { +template +typename ImageType::Pointer clitk::ImageToImageGenericFilterBase::GetInput(unsigned int n) +{ if (mReadOnDisk && mInputFilenames.size() > n) { return clitk::readImage(mInputFilenames[n], mIOVerbose); - } - else { + } else { if (mInputVVImages.size() > n) return typename ImageType::Pointer(const_cast(vvImageToITK(mInputVVImages[n]).GetPointer())); - else - { - assert(false); //No input, this shouldn't happen - return typename ImageType::Pointer(NULL); - } + else { + assert(false); //No input, this shouldn't happen + return typename ImageType::Pointer(NULL); + } } } //-------------------------------------------------------------------- diff --git a/common/clitkImageToImageGenericFilterBase.txx b/common/clitkImageToImageGenericFilterBase.txx index 1fbd22b..0525ad4 100644 --- a/common/clitkImageToImageGenericFilterBase.txx +++ b/common/clitkImageToImageGenericFilterBase.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr diff --git a/common/clitkImageUtilities.cxx b/common/clitkImageUtilities.cxx index 4c87261..65c593b 100644 --- a/common/clitkImageUtilities.cxx +++ b/common/clitkImageUtilities.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkImageUtilities.cxx * @author David Sarrut * @date 22 Sep 2006 10:39:40 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ #include "clitkImageUtilities.h" diff --git a/common/clitkImageUtilities.txx b/common/clitkImageUtilities.txx index e237334..60382f2 100644 --- a/common/clitkImageUtilities.txx +++ b/common/clitkImageUtilities.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,17 +22,17 @@ * @file clitkImageUtilities.txx * @author David Sarrut * @date 22 Sep 2006 10:39:48 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ //==================================================================== // Compute the number of different intensities in an image template -int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, - std::vector & l) +int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, + std::vector & l) { //std::set listOfIntensities; std::map listOfIntensities; @@ -41,40 +41,41 @@ int ComputeHowManyDifferentIntensity(const typename ImageType::Pointer & image, ConstIteratorType pi(image, image->GetLargestPossibleRegion()); pi.Begin(); while (!pi.IsAtEnd()) { - if (!listOfIntensities[pi.Get()]) listOfIntensities[pi.Get()] = true; - // if (std::find(listOfIntensities.begin(), -// listOfIntensities.end(), + if (!listOfIntensities[pi.Get()]) listOfIntensities[pi.Get()] = true; + // if (std::find(listOfIntensities.begin(), +// listOfIntensities.end(), // pi.Get()) == listOfIntensities.end()) { // listOfIntensities.insert(pi.Get()); // } - ++pi; + ++pi; } - + //typename std::set::const_iterator ppi = listOfIntensities.begin(); typename std::map::const_iterator ppi = listOfIntensities.begin(); while (ppi != listOfIntensities.end()) { - l.push_back(ppi->first); - ++ppi; + l.push_back(ppi->first); + ++ppi; } return listOfIntensities.size(); } //==================================================================== - + //==================================================================== template -void ComputeWeightsOfEachClasses(const typename InputImageType::Pointer & input, - const typename MaskImageType::Pointer & mask, - const std::vector & listOfIntensities, - std::map > & mapOfLabelsAndWeights) { +void ComputeWeightsOfEachClasses(const typename InputImageType::Pointer & input, + const typename MaskImageType::Pointer & mask, + const std::vector & listOfIntensities, + std::map > & mapOfLabelsAndWeights) +{ // Check size if (input->GetLargestPossibleRegion() != mask->GetLargestPossibleRegion()) { - itkGenericExceptionMacro(<< "Input and mask images have not the same size" - << std::endl - << "Input = " << input->GetLargestPossibleRegion() - << std::endl - << "Mask = " << mask->GetLargestPossibleRegion()); + itkGenericExceptionMacro(<< "Input and mask images have not the same size" + << std::endl + << "Input = " << input->GetLargestPossibleRegion() + << std::endl + << "Mask = " << mask->GetLargestPossibleRegion()); } // reset weights list @@ -88,16 +89,16 @@ void ComputeWeightsOfEachClasses(const typename InputImageType::Pointer & input, pi.Begin(); pm.Begin(); while (!pi.IsAtEnd()) { - mapOfLabelsAndWeights[pm.Get()][pi.Get()]++; - ++pi; - ++pm; + mapOfLabelsAndWeights[pm.Get()][pi.Get()]++; + ++pi; + ++pm; } } //==================================================================== // //==================================================================== // template -// typename ImageType::Pointer NewImage3D(int x, int y, int z, float dx, float dy, float dz) { +// typename ImageType::Pointer NewImage3D(int x, int y, int z, float dx, float dy, float dz) { // typename ImageType::Pointer output = ImageType::New(); // typename ImageType::RegionType region; // typename ImageType::SizeType size; @@ -107,7 +108,7 @@ void ComputeWeightsOfEachClasses(const typename InputImageType::Pointer & input, // region.SetSize(size); // output->SetRegions(region); // output->Allocate(); -// typename ImageType::SpacingType spacing; +// typename ImageType::SpacingType spacing; // spacing[0] = dx; // spacing[1] = dy; // spacing[2] = dz; diff --git a/common/clitkListOfPair.cxx b/common/clitkListOfPair.cxx index defbe60..a96705c 100644 --- a/common/clitkListOfPair.cxx +++ b/common/clitkListOfPair.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,25 +22,26 @@ * @file clitkListOfPair.cxx * @author David Sarrut * @date 27 Feb 2007 09:55:56 - * - * @brief - * - * + * + * @brief + * + * ------------------------------------------------=*/ #include "clitkListOfPair.h" //-------------------------------------------------------------------- -double clitk::convertValue(double v, - const std::multimap & conversionTable, - bool linear) { +double clitk::convertValue(double v, + const std::multimap & conversionTable, + bool linear) +{ std::multimap::const_iterator i; - i = conversionTable.lower_bound(v); + i = conversionTable.lower_bound(v); if (i == conversionTable.end()) { std::cerr << "The value " << v << " is out of the table" << std::endl; exit(0); } - + double v2 = i->first; double p2 = i->second; if (i != conversionTable.begin()) i--; @@ -51,8 +52,7 @@ double clitk::convertValue(double v, if (!linear) { if ((v-v1) > (v2-v)) return p2; else return p1; - } - else { + } else { double w = (v-v1)/(v2-v1); return p1*(1.0-w)+w*p2; } diff --git a/common/clitkListOfPair.txx b/common/clitkListOfPair.txx index 5e3a843..5c9a133 100644 --- a/common/clitkListOfPair.txx +++ b/common/clitkListOfPair.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,15 +22,16 @@ * @file clitkListOfPair.txx * @author David Sarrut * @date 27 Feb 2007 09:44:48 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ //==================================================================== template -void ReadMap(const std::string & filename, MapType & list, bool inverse) { +void ReadMap(const std::string & filename, MapType & list, bool inverse) +{ std::ifstream is; clitk::openFileForReading(is, filename); clitk::skipComment(is); @@ -39,13 +40,13 @@ void ReadMap(const std::string & filename, MapType & list, bool inverse) { typedef typename MapType::mapped_type MType; MType v2; while (is) { - is >> v1; - is >> v2; - if (is) { - if (!inverse) list.insert(std::pair(v1,v2)); - else list.insert(std::pair(v2,v1)); - } - clitk::skipComment(is); + is >> v1; + is >> v2; + if (is) { + if (!inverse) list.insert(std::pair(v1,v2)); + else list.insert(std::pair(v2,v1)); + } + clitk::skipComment(is); } is.close(); } diff --git a/common/clitkOrientation.cxx b/common/clitkOrientation.cxx index 4c173a0..1315d1d 100644 --- a/common/clitkOrientation.cxx +++ b/common/clitkOrientation.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkOrientation.cxx * @author David Sarrut * @date 01 Nov 2006 18:02:49 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ #include "clitkOrientation.h" @@ -39,34 +39,34 @@ itk::SpatialOrientation::CoordinateTerms clitk::GetOrientation(char c) if ((c == 'A') || (c == 'a')) return itk::SpatialOrientation::ITK_COORDINATE_Anterior; if ((c == 'I') || (c == 'i')) return itk::SpatialOrientation::ITK_COORDINATE_Inferior; if ((c == 'S') || (c == 's')) return itk::SpatialOrientation::ITK_COORDINATE_Superior; - std::cerr <<"I don't know the orientation '" << c - << "'. Valid letters are LR/AP/IS (or in lowercase)" << std::endl; + std::cerr <<"I don't know the orientation '" << c + << "'. Valid letters are LR/AP/IS (or in lowercase)" << std::endl; exit(0); } //==================================================================== //==================================================================== bool clitk::CheckOrientation(itk::SpatialOrientation::CoordinateTerms a, - itk::SpatialOrientation::CoordinateTerms b) + itk::SpatialOrientation::CoordinateTerms b) { - if ((a==itk::SpatialOrientation::ITK_COORDINATE_Right) || + if ((a==itk::SpatialOrientation::ITK_COORDINATE_Right) || (a==itk::SpatialOrientation::ITK_COORDINATE_Left)) { if ((b==itk::SpatialOrientation::ITK_COORDINATE_Right) || - (b==itk::SpatialOrientation::ITK_COORDINATE_Left)) { + (b==itk::SpatialOrientation::ITK_COORDINATE_Left)) { return false; } } - if ((a==itk::SpatialOrientation::ITK_COORDINATE_Posterior) || + if ((a==itk::SpatialOrientation::ITK_COORDINATE_Posterior) || (a==itk::SpatialOrientation::ITK_COORDINATE_Anterior)) { if ((b==itk::SpatialOrientation::ITK_COORDINATE_Posterior) || - (b==itk::SpatialOrientation::ITK_COORDINATE_Anterior)) { + (b==itk::SpatialOrientation::ITK_COORDINATE_Anterior)) { return false; } } - if ((a==itk::SpatialOrientation::ITK_COORDINATE_Inferior) || + if ((a==itk::SpatialOrientation::ITK_COORDINATE_Inferior) || (a==itk::SpatialOrientation::ITK_COORDINATE_Superior)) { if ((b==itk::SpatialOrientation::ITK_COORDINATE_Inferior) || - (b==itk::SpatialOrientation::ITK_COORDINATE_Superior)) { + (b==itk::SpatialOrientation::ITK_COORDINATE_Superior)) { return false; } } @@ -83,12 +83,12 @@ itk::SpatialOrientation::ValidCoordinateOrientationFlags clitk::GetOrientation(c if (CheckOrientation(f1, f2) && CheckOrientation(f2,f3) && CheckOrientation(f1,f3)) { return static_cast( - (f1 << itk::SpatialOrientation::ITK_COORDINATE_PrimaryMinor) - + (f2 << itk::SpatialOrientation::ITK_COORDINATE_SecondaryMinor) - + (f3 << itk::SpatialOrientation::ITK_COORDINATE_TertiaryMinor)); + (f1 << itk::SpatialOrientation::ITK_COORDINATE_PrimaryMinor) + + (f2 << itk::SpatialOrientation::ITK_COORDINATE_SecondaryMinor) + + (f3 << itk::SpatialOrientation::ITK_COORDINATE_TertiaryMinor)); } - std::cerr <<"I don't know the orientation '" << a << b << c - << "'. Valid letters are LR/AP/IS (or in lowercase)" << std::endl; + std::cerr <<"I don't know the orientation '" << a << b << c + << "'. Valid letters are LR/AP/IS (or in lowercase)" << std::endl; exit(0); } //==================================================================== @@ -97,8 +97,8 @@ itk::SpatialOrientation::ValidCoordinateOrientationFlags clitk::GetOrientation(c itk::SpatialOrientation::ValidCoordinateOrientationFlags clitk::GetOrientation(const std::string & orient) { if (orient.size() >= 3) return GetOrientation(orient[0], orient[1], orient[2]); - std::cerr <<"I don't know the orientation '" << orient - << "'. Valid string are three letters LR/AP/IS (or in lowercase)" << std::endl; + std::cerr <<"I don't know the orientation '" << orient + << "'. Valid string are three letters LR/AP/IS (or in lowercase)" << std::endl; exit(0); } //==================================================================== @@ -115,28 +115,29 @@ itk::SpatialOrientation::CoordinateTerms clitk::GetOrientation(const int i, cons //==================================================================== //==================================================================== -int clitk::WhereIsDimInThisOrientation(const int dim, const itk::SpatialOrientation::ValidCoordinateOrientationFlags flag) { +int clitk::WhereIsDimInThisOrientation(const int dim, const itk::SpatialOrientation::ValidCoordinateOrientationFlags flag) +{ if (dim ==0) { for(int i=0; i<3; i++) { int j = GetOrientation(i, flag); - if ((j == itk::SpatialOrientation::ITK_COORDINATE_Right) || - (j == itk::SpatialOrientation::ITK_COORDINATE_Left)) return i; + if ((j == itk::SpatialOrientation::ITK_COORDINATE_Right) || + (j == itk::SpatialOrientation::ITK_COORDINATE_Left)) return i; } - } + } if (dim ==1) { for(int i=0; i<3; i++) { int j = GetOrientation(i, flag); - if ((j == itk::SpatialOrientation::ITK_COORDINATE_Anterior) || - (j == itk::SpatialOrientation::ITK_COORDINATE_Posterior)) return i; + if ((j == itk::SpatialOrientation::ITK_COORDINATE_Anterior) || + (j == itk::SpatialOrientation::ITK_COORDINATE_Posterior)) return i; } - } + } if (dim ==2) { for(int i=0; i<3; i++) { int j = GetOrientation(i, flag); - if ((j == itk::SpatialOrientation::ITK_COORDINATE_Superior) || - (j == itk::SpatialOrientation::ITK_COORDINATE_Inferior)) return i; + if ((j == itk::SpatialOrientation::ITK_COORDINATE_Superior) || + (j == itk::SpatialOrientation::ITK_COORDINATE_Inferior)) return i; } - } + } return 0; // just to avoid warning } //==================================================================== @@ -144,11 +145,11 @@ int clitk::WhereIsDimInThisOrientation(const int dim, const itk::SpatialOrientat //==================================================================== int clitk::GetDim(const itk::SpatialOrientation::CoordinateTerms t) { - if ((t == itk::SpatialOrientation::ITK_COORDINATE_Right) || + if ((t == itk::SpatialOrientation::ITK_COORDINATE_Right) || (t == itk::SpatialOrientation::ITK_COORDINATE_Left)) return 0; if ((t == itk::SpatialOrientation::ITK_COORDINATE_Anterior) || (t == itk::SpatialOrientation::ITK_COORDINATE_Posterior)) return 1; - if ((t == itk::SpatialOrientation::ITK_COORDINATE_Inferior) || + if ((t == itk::SpatialOrientation::ITK_COORDINATE_Inferior) || (t == itk::SpatialOrientation::ITK_COORDINATE_Superior)) return 2; std::cerr <<"Invalid CoordinateTerms = " << t << std::endl; exit(0); @@ -156,11 +157,11 @@ int clitk::GetDim(const itk::SpatialOrientation::CoordinateTerms t) //==================================================================== //==================================================================== -void clitk::FlipPoint(const itk::Point in, - const itk::SpatialOrientation::ValidCoordinateOrientationFlags inFlag, - const itk::SpatialOrientation::ValidCoordinateOrientationFlags outFlag, - const itk::Point & imageSize, - itk::Point & out) +void clitk::FlipPoint(const itk::Point in, + const itk::SpatialOrientation::ValidCoordinateOrientationFlags inFlag, + const itk::SpatialOrientation::ValidCoordinateOrientationFlags outFlag, + const itk::Point & imageSize, + itk::Point & out) { for(int i=0; i<3; i++) { // DD(i); diff --git a/common/clitkTimer.cxx b/common/clitkTimer.cxx index 89297f3..d6987fa 100644 --- a/common/clitkTimer.cxx +++ b/common/clitkTimer.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkTimer.cxx * @author David Sarrut * @date 18 Jul 2007 16:27:45 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ // #ifdef UNIX @@ -33,9 +33,10 @@ #include "clitkTimer.h" //==================================================================== -/// Constructs the class -clitk::Timer::Timer() { - Reset(); +/// Constructs the class +clitk::Timer::Timer() +{ + Reset(); #if defined(WIN32) QueryPerformanceFrequency((LARGE_INTEGER*)&mFrequency); #endif @@ -43,7 +44,8 @@ clitk::Timer::Timer() { //==================================================================== //==================================================================== -void clitk::Timer::Start() { +void clitk::Timer::Start() +{ #if defined(unix) || defined(__APPLE__) getrusage(RUSAGE_SELF, &mBegin); #elif defined(WIN32) @@ -54,12 +56,13 @@ void clitk::Timer::Start() { //==================================================================== //==================================================================== -void clitk::Timer::Stop(bool accumulate) { +void clitk::Timer::Stop(bool accumulate) +{ #if defined(unix) || defined (__APPLE__) getrusage(RUSAGE_SELF, &mEnd); if (accumulate) { mElapsed += (mEnd.ru_utime.tv_usec - mBegin.ru_utime.tv_usec)+ - (mEnd.ru_utime.tv_sec - mBegin.ru_utime.tv_sec)*1000000; + (mEnd.ru_utime.tv_sec - mBegin.ru_utime.tv_sec)*1000000; } #elif defined(WIN32) QueryPerformanceCounter((LARGE_INTEGER*)&mEnd); @@ -74,7 +77,8 @@ void clitk::Timer::Stop(bool accumulate) { //==================================================================== //==================================================================== -void clitk::Timer::Print(std::ostream & os) const { +void clitk::Timer::Print(std::ostream & os) const +{ if (mNumberOfCall != 1) { os << "Timer # = " << mNumberOfCall << std::endl; os << "Timer total = " << mElapsed << " usec \t" << mElapsed/1000000.0 << " sec." << mElapsed/1000000.0/60 << " min." @@ -88,19 +92,21 @@ void clitk::Timer::Print(std::ostream & os) const { // os << "\tmBegin.ru_utime.tv_sec = " << mBegin.ru_utime.tv_sec << std::endl; // os << "\tmEnd.ru_utime.tv_sec = " << mEnd.ru_utime.tv_sec << std::endl; // os << "\tmBegin.ru_utime.tv_usec = " << mBegin.ru_utime.tv_usec << std::endl; -// os << "\tmEnd.ru_utime.tv_usec = " << mEnd.ru_utime.tv_usec << std::endl; +// os << "\tmEnd.ru_utime.tv_usec = " << mEnd.ru_utime.tv_usec << std::endl; } //==================================================================== //==================================================================== -void clitk::Timer::Print(std::string text, std::ostream & os) const { +void clitk::Timer::Print(std::string text, std::ostream & os) const +{ os << text; Print(os); -} +} //==================================================================== //==================================================================== -void clitk::Timer::Reset() { +void clitk::Timer::Reset() +{ mNumberOfCall = 0; mElapsed = 0; } diff --git a/common/clitkVfImageIO.cxx b/common/clitkVfImageIO.cxx index 795a96d..ee924d8 100644 --- a/common/clitkVfImageIO.cxx +++ b/common/clitkVfImageIO.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkVfImageIO.cxx * @author Simon Rit * @date Mon Sep 18 10:14:53 2006 - * + * * @brief VectorField .vf I/O implementation - * - * + * + * */ // clitk include @@ -36,41 +36,41 @@ //==================================================================== // Read Image Information -void clitk::VfImageIO::ReadImageInformation() +void clitk::VfImageIO::ReadImageInformation() { // open file std::ifstream is; - clitk::openFileForReading(is, m_FileName); + clitk::openFileForReading(is, m_FileName); // read magic number - std::string mn; - is >> mn; + std::string mn; + is >> mn; //DD(mn); if (mn != "IAMA3DVECTORFIELD") { - itkExceptionMacro(<<"read magic number '" << mn << "' while expect IAMA3DVECTORFIELD"); - } + itkExceptionMacro(<<"read magic number '" << mn << "' while expect IAMA3DVECTORFIELD"); + } // read vf file version - skipComment(is); - is >> mn; + skipComment(is); + is >> mn; //DD(mn); if (mn != "V2") { - itkExceptionMacro(<<"read old format '" << mn << "'. TODO"); - } - + itkExceptionMacro(<<"read old format '" << mn << "'. TODO"); + } + // read grid size/spacing itk::Vector dim; itk::Vector spacing; itk::Vector origin; origin.Fill(0.0); - skipComment(is); - is >> dim[0]; - is >> dim[1]; + skipComment(is); + is >> dim[0]; + is >> dim[1]; is >> dim[2]; // DD(dim); is >> spacing[0]; is >> spacing[1]; is >> spacing[2]; // DD(spacing); - + // get header size m_HeaderSize = is.tellg(); m_HeaderSize+=2; @@ -78,21 +78,21 @@ void clitk::VfImageIO::ReadImageInformation() // set dimension values SetNumberOfDimensions(3); for(unsigned int i=0; i<3; i++) { - SetDimensions(i,dim[i]); - SetSpacing(i,spacing[i]); - SetOrigin(i,origin[i]); + SetDimensions(i,dim[i]); + SetSpacing(i,spacing[i]); + SetOrigin(i,origin[i]); } // set other information SetByteOrderToLittleEndian(); SetPixelType(itk::ImageIOBase::VECTOR); - SetNumberOfComponents(3); + SetNumberOfComponents(3); SetComponentType(itk::ImageIOBase::FLOAT); } //// //==================================================================== // Read Image Information -bool clitk::VfImageIO::CanReadFile(const char* FileNameToRead) +bool clitk::VfImageIO::CanReadFile(const char* FileNameToRead) { std::string filename(FileNameToRead); std::string filenameext = GetExtension(filename); @@ -102,7 +102,7 @@ bool clitk::VfImageIO::CanReadFile(const char* FileNameToRead) //==================================================================== // Read Image Content -void clitk::VfImageIO::Read(void * buffer) +void clitk::VfImageIO::Read(void * buffer) { // Adapted from itkRawImageIO @@ -113,30 +113,30 @@ void clitk::VfImageIO::Read(void * buffer) unsigned long streamStart = m_HeaderSize; file.seekg((long)streamStart, std::ios::beg); if ( file.fail() ) { - itkExceptionMacro(<<"File seek failed (Vf Read)"); + itkExceptionMacro(<<"File seek failed (Vf Read)"); } - + float * tmpBuff = new float[GetImageSizeInComponents()]; if(!this->ReadBufferAsBinary(file, tmpBuff, GetImageSizeInBytes())) { - itkExceptionMacro(<<"Read failed: Wanted " - << GetImageSizeInBytes() - << " bytes, but read " - << file.gcount() << " bytes."); + itkExceptionMacro(<<"Read failed: Wanted " + << GetImageSizeInBytes() + << " bytes, but read " + << file.gcount() << " bytes."); } itkDebugMacro(<< "Reading Done"); - + float *pb = (float *)buffer; float *px = tmpBuff; float *py = tmpBuff + GetImageSizeInPixels(); float *pz = tmpBuff + 2 * GetImageSizeInPixels(); const float *pbe = (float *)buffer + GetImageSizeInComponents(); - while(pb != pbe){ + while(pb != pbe) { *pb++ = (*px++)*GetSpacing(0); *pb++ = (*py++)*GetSpacing(1); *pb++ = (*pz++)*GetSpacing(2); } delete [] tmpBuff; - + typedef itk::ByteSwapper< float > InternalByteSwapperType; InternalByteSwapperType::SwapRangeFromSystemToLittleEndian((float *)buffer, GetImageSizeInComponents()); } @@ -147,7 +147,7 @@ void clitk::VfImageIO::WriteImageInformation(bool keepOfStream) { // Check dimension if (GetNumberOfDimensions() != 3) { - itkExceptionMacro(<<"Write failed: only 3D image for Vf file format yet."); + itkExceptionMacro(<<"Write failed: only 3D image for Vf file format yet."); } // Open the file @@ -155,17 +155,17 @@ void clitk::VfImageIO::WriteImageInformation(bool keepOfStream) // write magic number file << "IAMA3DVECTORFIELD V2 " << std::endl; // write grid size/spacing - file << GetDimensions(0) << ' ' - << GetDimensions(1) << ' ' - << GetDimensions(2) << ' ' - << GetSpacing(0) << ' ' - << GetSpacing(1) << ' ' - << GetSpacing(2) << ' ' << std::endl; + file << GetDimensions(0) << ' ' + << GetDimensions(1) << ' ' + << GetDimensions(2) << ' ' + << GetSpacing(0) << ' ' + << GetSpacing(1) << ' ' + << GetSpacing(2) << ' ' << std::endl; // close file - if (!keepOfStream) file.close(); + if (!keepOfStream) file.close(); } - + //==================================================================== // Write Image Information bool clitk::VfImageIO::CanWriteFile(const char* FileNameToWrite) @@ -178,29 +178,29 @@ bool clitk::VfImageIO::CanWriteFile(const char* FileNameToWrite) //==================================================================== // Write Image -void clitk::VfImageIO::Write(const void * buffer) +void clitk::VfImageIO::Write(const void * buffer) { clitk::VfImageIO::WriteImageInformation(true); - + typedef itk::ByteSwapper< float > InternalByteSwapperType; std::cout << "GetImageSizeInBytes() " << GetImageSizeInBytes() << std::endl; float* tempBuffer = new float[ GetImageSizeInPixels() ]; - for(int i=0 ; i< 3 ; i++){ - float *pb = (float *)buffer; - pb+=i; - float *ptb = tempBuffer; - const float *pbe = (float *)buffer + GetImageSizeInComponents() + i; - while(pb != pbe){ - *ptb++ = (*pb)/GetSpacing(i); - pb+=3; - } - InternalByteSwapperType::SwapRangeFromSystemToLittleEndian(tempBuffer,GetImageSizeInPixels()); - file.write((char*)tempBuffer, GetImageSizeInBytes()/3 ); + for(int i=0 ; i< 3 ; i++) { + float *pb = (float *)buffer; + pb+=i; + float *ptb = tempBuffer; + const float *pbe = (float *)buffer + GetImageSizeInComponents() + i; + while(pb != pbe) { + *ptb++ = (*pb)/GetSpacing(i); + pb+=3; + } + InternalByteSwapperType::SwapRangeFromSystemToLittleEndian(tempBuffer,GetImageSizeInPixels()); + file.write((char*)tempBuffer, GetImageSizeInBytes()/3 ); } - delete [] tempBuffer; - + delete [] tempBuffer; + file.close(); } //// diff --git a/common/clitkVfImageIOFactory.cxx b/common/clitkVfImageIOFactory.cxx index 88cd04f..2b50df3 100644 --- a/common/clitkVfImageIOFactory.cxx +++ b/common/clitkVfImageIOFactory.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,22 +22,22 @@ * @file clitkVfImageIOFactory.cxx * @author Simon Rit * @date Mon Sep 18 10:14:25 2006 - * - * @brief - * - * + * + * @brief + * + * */ #include "clitkVfImageIOFactory.h" //==================================================================== -clitk::VfImageIOFactory::VfImageIOFactory() +clitk::VfImageIOFactory::VfImageIOFactory() { - this->RegisterOverride("itkImageIOBase", - "VfImageIO", - "Vf Image IO", - 1, - itk::CreateObjectFunction::New()); + this->RegisterOverride("itkImageIOBase", + "VfImageIO", + "Vf Image IO", + 1, + itk::CreateObjectFunction::New()); } diff --git a/common/clitkVoxImageIO.cxx b/common/clitkVoxImageIO.cxx index 308cd1e..3002db8 100644 --- a/common/clitkVoxImageIO.cxx +++ b/common/clitkVoxImageIO.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkVoxImageIO.cxx * @author David Sarrut * @date 17 May 2006 08:03:07 - * - * @brief - * - * + * + * @brief + * + * -------------------------------------------------*/ // clitk include @@ -37,25 +37,26 @@ //-------------------------------------------------------------------- // Read Image Information -void clitk::VoxImageIO::ReadImageInformation() { +void clitk::VoxImageIO::ReadImageInformation() +{ // open file std::ifstream is; - clitk::openFileForReading(is, m_FileName); + clitk::openFileForReading(is, m_FileName); // read magic number - std::string mn; - is >> mn; + std::string mn; + is >> mn; //DD(mn); if (mn != "VOX") { itkExceptionMacro(<<"read magic number '" << mn << "' while expect VOX"); - } + } // read vox file version - skipComment(is); - is >> mn; + skipComment(is); + is >> mn; //DD(mn); if (mn != "v2") { itkExceptionMacro(<<"read old format '" << mn << "'. TODO"); - } - + } + // ONLY 3D IMAGES YET ... // read grid size/spacing @@ -63,25 +64,25 @@ void clitk::VoxImageIO::ReadImageInformation() { itk::Vector spacing; itk::Vector origin; origin.Fill(0.0); - skipComment(is); - is >> dim[0]; - is >> dim[1]; + skipComment(is); + is >> dim[0]; + is >> dim[1]; is >> dim[2]; //DD(dim); - skipComment(is); + skipComment(is); is >> spacing[0]; is >> spacing[1]; is >> spacing[2]; //DD(spacing); skipComment(is); - int d; + int d; is >> d; if (d != 3 && d != 2) { itkExceptionMacro(<<"could not read no " << d << "D image (only 2D and 3D). TODO"); } // read data type skipComment(is); - std::string dataTypeName; + std::string dataTypeName; is >> dataTypeName; //DD(dataTypeName); @@ -101,7 +102,7 @@ void clitk::VoxImageIO::ReadImageInformation() { // set other information SetByteOrderToLittleEndian(); SetPixelType(itk::ImageIOBase::SCALAR); - SetNumberOfComponents(1); + SetNumberOfComponents(1); if (dataTypeName == "char") SetComponentType(itk::ImageIOBase::CHAR); else if (dataTypeName == "schar") SetComponentType(itk::ImageIOBase::CHAR); @@ -114,16 +115,16 @@ void clitk::VoxImageIO::ReadImageInformation() { else if (dataTypeName == "float") SetComponentType(itk::ImageIOBase::FLOAT); else if (dataTypeName == "double") SetComponentType(itk::ImageIOBase::DOUBLE); else { - itkExceptionMacro(<<"Read failed: Wanted pixel type " - << "(char, uchar, short, ushort, int, uint, float, double)" - << " but read " << dataTypeName); + itkExceptionMacro(<<"Read failed: Wanted pixel type " + << "(char, uchar, short, ushort, int, uint, float, double)" + << " but read " << dataTypeName); } } //// //-------------------------------------------------------------------- // Read Image Information -bool clitk::VoxImageIO::CanReadFile(const char* FileNameToRead) +bool clitk::VoxImageIO::CanReadFile(const char* FileNameToRead) { std::string filename(FileNameToRead); std::string filenameext = GetExtension(filename); @@ -133,7 +134,7 @@ bool clitk::VoxImageIO::CanReadFile(const char* FileNameToRead) //-------------------------------------------------------------------- // Read Image Content -void clitk::VoxImageIO::Read(void * buffer) +void clitk::VoxImageIO::Read(void * buffer) { // Adapted from itkRawImageIO @@ -146,31 +147,31 @@ void clitk::VoxImageIO::Read(void * buffer) if ( file.fail() ) { itkExceptionMacro(<<"File seek failed (Vox Read)"); } - + unsigned long numberOfBytesToBeRead = GetComponentSize(); for(unsigned int i=0; iReadBufferAsBinary(file, buffer, numberOfBytesToBeRead)) { - itkExceptionMacro(<<"Read failed: Wanted " - << numberOfBytesToBeRead - << " bytes, but read " - << file.gcount() << " bytes."); + itkExceptionMacro(<<"Read failed: Wanted " + << numberOfBytesToBeRead + << " bytes, but read " + << file.gcount() << " bytes."); } itkDebugMacro(<< "Reading Done"); { using namespace itk; // Swap bytes if necessary - if itkReadRawBytesAfterSwappingMacro( unsigned short, USHORT ) - else if itkReadRawBytesAfterSwappingMacro( short, SHORT ) - else if itkReadRawBytesAfterSwappingMacro( char, CHAR ) - else if itkReadRawBytesAfterSwappingMacro( unsigned char, UCHAR ) - else if itkReadRawBytesAfterSwappingMacro( unsigned int, UINT ) - else if itkReadRawBytesAfterSwappingMacro( int, INT ) - else if itkReadRawBytesAfterSwappingMacro( float, FLOAT ) - else if itkReadRawBytesAfterSwappingMacro( double, DOUBLE ); + if itkReadRawBytesAfterSwappingMacro( unsigned short, USHORT ) + else if itkReadRawBytesAfterSwappingMacro( short, SHORT ) + else if itkReadRawBytesAfterSwappingMacro( char, CHAR ) + else if itkReadRawBytesAfterSwappingMacro( unsigned char, UCHAR ) + else if itkReadRawBytesAfterSwappingMacro( unsigned int, UINT ) + else if itkReadRawBytesAfterSwappingMacro( int, INT ) + else if itkReadRawBytesAfterSwappingMacro( float, FLOAT ) + else if itkReadRawBytesAfterSwappingMacro( double, DOUBLE ); } } @@ -189,13 +190,13 @@ void clitk::VoxImageIO::WriteImageInformation(bool keepOfStream) file << "VOX v2" << std::endl; // write grid size/spacing file << "# Size" << std::endl; - file << GetDimensions(0) << " " - << GetDimensions(1) << " " + file << GetDimensions(0) << " " + << GetDimensions(1) << " " << GetDimensions(2) << std::endl; file << "# Spacing" << std::endl; - file.precision(40); - file << GetSpacing(0) << " " - << GetSpacing(1) << " " + file.precision(40); + file << GetSpacing(0) << " " + << GetSpacing(1) << " " << GetSpacing(2) << std::endl; file << "# Image dim" << std::endl << "3" << std::endl; file << "# Image type" << std::endl; @@ -210,16 +211,16 @@ void clitk::VoxImageIO::WriteImageInformation(bool keepOfStream) else if (GetComponentType() == itk::ImageIOBase::FLOAT) dataTypeName = "float"; else if (GetComponentType() == itk::ImageIOBase::DOUBLE) dataTypeName = "double"; else { - itkExceptionMacro(<<"Write failed: Wanted pixel type " - << "(char, uchar, short, ushort, int, uint, float, double)" - << " but Vox is : " << dataTypeName); + itkExceptionMacro(<<"Write failed: Wanted pixel type " + << "(char, uchar, short, ushort, int, uint, float, double)" + << " but Vox is : " << dataTypeName); } file << dataTypeName << std::endl; // close file - if (!keepOfStream) file.close(); + if (!keepOfStream) file.close(); } - + //-------------------------------------------------------------------- // Write Image Information bool clitk::VoxImageIO::CanWriteFile(const char* FileNameToWrite) @@ -232,7 +233,7 @@ bool clitk::VoxImageIO::CanWriteFile(const char* FileNameToWrite) //-------------------------------------------------------------------- // Write Image -void clitk::VoxImageIO::Write(const void * buffer) +void clitk::VoxImageIO::Write(const void * buffer) { clitk::VoxImageIO::WriteImageInformation(true); SetByteOrderToLittleEndian(); @@ -244,16 +245,16 @@ void clitk::VoxImageIO::Write(const void * buffer) const unsigned long numberOfComponents = this->GetImageSizeInComponents(); // Swap bytes if necessary using namespace itk; - if itkWriteRawBytesAfterSwappingMacro( unsigned short, USHORT ) - else if itkWriteRawBytesAfterSwappingMacro( short, SHORT ) - else if itkWriteRawBytesAfterSwappingMacro( char, CHAR ) - else if itkWriteRawBytesAfterSwappingMacro( unsigned char, UCHAR ) - else if itkWriteRawBytesAfterSwappingMacro( unsigned int, UINT ) - else if itkWriteRawBytesAfterSwappingMacro( int, INT ) - else if itkWriteRawBytesAfterSwappingMacro( float, FLOAT ) - else if itkWriteRawBytesAfterSwappingMacro( double, DOUBLE ) ; + if itkWriteRawBytesAfterSwappingMacro( unsigned short, USHORT ) + else if itkWriteRawBytesAfterSwappingMacro( short, SHORT ) + else if itkWriteRawBytesAfterSwappingMacro( char, CHAR ) + else if itkWriteRawBytesAfterSwappingMacro( unsigned char, UCHAR ) + else if itkWriteRawBytesAfterSwappingMacro( unsigned int, UINT ) + else if itkWriteRawBytesAfterSwappingMacro( int, INT ) + else if itkWriteRawBytesAfterSwappingMacro( float, FLOAT ) + else if itkWriteRawBytesAfterSwappingMacro( double, DOUBLE ) ; //------------------------------------------- - + file.close(); } //// diff --git a/common/clitkVoxImageIOFactory.cxx b/common/clitkVoxImageIOFactory.cxx index b9b2489..110a7ba 100644 --- a/common/clitkVoxImageIOFactory.cxx +++ b/common/clitkVoxImageIOFactory.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkVoxImageIOFactory.cxx * @author David Sarrut * @date 03 Jul 2006 11:29:10 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ #include "clitkVoxImageIOFactory.h" @@ -33,13 +33,13 @@ #include //==================================================================== -clitk::VoxImageIOFactory::VoxImageIOFactory() +clitk::VoxImageIOFactory::VoxImageIOFactory() { - this->RegisterOverride("itkImageIOBase", - "VoxImageIO", - "Vox Image IO", - 1, - itk::CreateObjectFunction::New()); + this->RegisterOverride("itkImageIOBase", + "VoxImageIO", + "Vox Image IO", + 1, + itk::CreateObjectFunction::New()); } diff --git a/common/clitkXdrImageIOFactory.cxx b/common/clitkXdrImageIOFactory.cxx index ffc66ab..760936d 100644 --- a/common/clitkXdrImageIOFactory.cxx +++ b/common/clitkXdrImageIOFactory.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -33,11 +33,11 @@ //==================================================================== clitk::XdrImageIOFactory::XdrImageIOFactory() { - this->RegisterOverride("itkImageIOBase", - "XdrImageIO", - "Xdr Image IO", - 1, - itk::CreateObjectFunction::New()); + this->RegisterOverride("itkImageIOBase", + "XdrImageIO", + "Xdr Image IO", + 1, + itk::CreateObjectFunction::New()); } diff --git a/common/clitkXdrImageIOReader.cxx b/common/clitkXdrImageIOReader.cxx index 6f651b5..bc3a24a 100644 --- a/common/clitkXdrImageIOReader.cxx +++ b/common/clitkXdrImageIOReader.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -55,30 +55,29 @@ /* DEFINES, ENUMERATED TYPES AND CONSTANTS */ /************************************************************************/ enum { - OK, - ER_ILLCOMMFUNCT, - ER_INARGUMENTS, - ER_XDR_NDIM, - ER_XDR_DIM, - ER_XDR_NSPACE, - ER_XDR_VECLEN, - ER_XDR_DATA, - ER_XDR_FIELD, - ER_XDR_OPEN, - ER_XDR_NOCTRLL, - ER_XDR_READ, - ER_OUTOFMEMORY, - ER_DECOMPRESSION, - ER_NOT_HANDLED + OK, + ER_ILLCOMMFUNCT, + ER_INARGUMENTS, + ER_XDR_NDIM, + ER_XDR_DIM, + ER_XDR_NSPACE, + ER_XDR_VECLEN, + ER_XDR_DATA, + ER_XDR_FIELD, + ER_XDR_OPEN, + ER_XDR_NOCTRLL, + ER_XDR_READ, + ER_OUTOFMEMORY, + ER_DECOMPRESSION, + ER_NOT_HANDLED }; -typedef struct -{ - unsigned int iOrgSize; - unsigned int iMode; - unsigned int iCompressedSize; - unsigned int iOrgCRC; - unsigned int iCompressedCRC; /* Excluding this header */ +typedef struct { + unsigned int iOrgSize; + unsigned int iMode; + unsigned int iCompressedSize; + unsigned int iOrgCRC; + unsigned int iCompressedCRC; /* Excluding this header */ } NKI_MODE2; @@ -86,68 +85,68 @@ typedef struct /* GLOBAL VARIABLES */ /************************************************************************/ const char* gl_ErrorMsg[] = { - "", - "Command or function not supported in this way.", - "Error in arguments", - "XDR file header NDIM error", - "XDR file header DIMn error", - "XDR file header NSPACE error", - "XDR file header VECLEN error", - "XDR file header DATA(type) error", - "XDR file header FIELD(coordinate type) error", - "XDR file could not be opened", - "XDR file header contains no ^L", - "XDR file reading error", - "Out of memory", - "Decompression failed", - "Format not handled by clitkXdrImageIO (RECTILINEAR or IRREGULAR field)" + "", + "Command or function not supported in this way.", + "Error in arguments", + "XDR file header NDIM error", + "XDR file header DIMn error", + "XDR file header NSPACE error", + "XDR file header VECLEN error", + "XDR file header DATA(type) error", + "XDR file header FIELD(coordinate type) error", + "XDR file could not be opened", + "XDR file header contains no ^L", + "XDR file reading error", + "Out of memory", + "Decompression failed", + "Format not handled by clitkXdrImageIO (RECTILINEAR or IRREGULAR field)" }; static const unsigned long CRC32_table[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; @@ -163,66 +162,63 @@ static const unsigned long CRC32_table[256] = { static char *scan_header(const char *file, const char *name, int offset, int removespaces) { - int i, j, iStringLength; - static char temp[512]; - FILE *f; - char *p, *q; - - if ((f = fopen(file, "rt")) == NULL) return NULL; - if (offset) fseek(f, offset, SEEK_SET); - - for (i=0; i<200; ) - { - if (fgets(temp, 500, f) == NULL ) break; /* end of file */ - - if (removespaces) - { - temp[500] = 0; - p = q = temp; /* remove spaces */ - iStringLength = strlen(temp); - for (j=0; jiOrgSize; - iMode = pHeader->iMode; // safety: this value is checked in case statement - - if (npixels<1) return 0; // safety: check for invalid npixels value - - /* Up till now only Mode=1, 2, 3, and 4 are supported */ - - switch (iMode) - { - case 1: - save = src; - - src += 8; // mode 1 only has 8 bytes header: iOrgSize and iMode - end = src + size - 3; // for overflow check if we are close to end of input buffer - - *dest = *(short int *)src; - src += 2; - npixels--; - - do - { - if (src > end) // check whether the last few messages fit in input buffer - { - if (src= -64 && val <= 63) mode = 1; // 7 bit difference - else if (val==0x7f) mode = 3; // 16 bit value - else if ((val&0xff)==0x80) mode = 2; // run length encoding - else mode = 2; - - if (src+mode > end+3) - return 0; // safety: overflow input data - } - - val = *src; - - if (val >= -64 && val <= 63) // 7 bit difference - { - dest[1] = dest[0] + val; - dest++; - src++; - } - else if (val==0x7f) // 16 bit value - { - dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; - dest++; - src+=3; - } - else if ((val&0xff)==0x80) // run length encoding - { - mode = ((unsigned char *)src)[1]; - npixels -= mode-1; - if (npixels<=0) return 0; // safety: overflow output data - do - { - dest[1] = dest[0]; - dest++; - } - while (--mode); - src+=2; - } - else - { - signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]); - dest[1] = dest[0] + diff; // 15 bit difference - dest++; - src+=2; - } - } - while (--npixels); + int npixels, retvalue, mode, iMode, val, j; + NKI_MODE2* pHeader = (NKI_MODE2*)src; + unsigned long iCRC=0, iCRC2=0; + //unsigned char* pDestStart = (unsigned char*)dest; + signed char *save, *end; + + retvalue = npixels = pHeader->iOrgSize; + iMode = pHeader->iMode; // safety: this value is checked in case statement + + if (npixels<1) return 0; // safety: check for invalid npixels value + + /* Up till now only Mode=1, 2, 3, and 4 are supported */ + + switch (iMode) { + case 1: + save = src; + + src += 8; // mode 1 only has 8 bytes header: iOrgSize and iMode + end = src + size - 3; // for overflow check if we are close to end of input buffer + + *dest = *(short int *)src; + src += 2; + npixels--; + + do { + if (src > end) { // check whether the last few messages fit in input buffer + if (src= -64 && val <= 63) mode = 1; // 7 bit difference + else if (val==0x7f) mode = 3; // 16 bit value + else if ((val&0xff)==0x80) mode = 2; // run length encoding + else mode = 2; + + if (src+mode > end+3) + return 0; // safety: overflow input data + } + + val = *src; + + if (val >= -64 && val <= 63) { // 7 bit difference + dest[1] = dest[0] + val; + dest++; + src++; + } else if (val==0x7f) { // 16 bit value + dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; + dest++; + src+=3; + } else if ((val&0xff)==0x80) { // run length encoding + mode = ((unsigned char *)src)[1]; + npixels -= mode-1; + if (npixels<=0) return 0; // safety: overflow output data + do { + dest[1] = dest[0]; + dest++; + } while (--mode); + src+=2; + } else { + signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]); + dest[1] = dest[0] + diff; // 15 bit difference + dest++; + src+=2; + } + } while (--npixels); + + global_len = src-save; + + break; + + case 2: + src += sizeof(NKI_MODE2); + save = src; + end = src + pHeader->iCompressedSize - 3; + + if (end > src + size - 3) + end = src + size - 3; // may occur if pHeader is corrupted - global_len = src-save; + *dest = val = *(short int *)src; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + src+=2; - break; + npixels--; - case 2: - src += sizeof(NKI_MODE2); - save = src; - end = src + pHeader->iCompressedSize - 3; + do { + if (src > end) { // check whether the last few messages fit in input buffer + if (src src + size - 3) - end = src + size - 3; // may occur if pHeader is corrupted + if (val >= -64 && val <= 63) mode = 1; // 7 bit difference + else if (val==0x7f) mode = 3; // 16 bit value + else if ((val&0xff)==0x80) mode = 2; // run length encoding + else mode = 2; - *dest = val = *(short int *)src; + if (src+mode > end+3) + break; // safety: overflow input data + } + + val = *src; + + if (val >= -64 && val <= 63) { // 7 bits difference + dest[1] = val = dest[0] + val; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; + src++; + } else if (val==0x7f) { // 16 bit value + dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; + + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; + src+=3; + } else if ((val&0xff)==0x80) { // run length encoding + mode = ((unsigned char *)src)[1]; + npixels -= mode-1; + if (npixels<=0) break; // safety: overflow output data + do { + dest[1] = val = dest[0]; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; + } while (--mode); + src+=2; + } else { + signed short diff = ((val^0x40)<<8) + ((unsigned char *)src)[1]; + dest[1] = val = dest[0] + diff; // 15 bit difference iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; src+=2; + } + } while (--npixels); + + if (iCRC2 != pHeader->iOrgCRC) { // if error in output CRC: + src = save; // check input CRC + while (src < end) { + iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)src[0]] ^ ((iCRC >> 8)); + src++; + } + + if (iCRC != pHeader->iCompressedCRC) { + AVSerror("XDR decompression: the file is corrupted"); + retvalue=0; + } else { + AVSerror("XDR decompression: internal error"); + retvalue=0; + } + } - npixels--; - - do - { - if (src > end) // check whether the last few messages fit in input buffer - { - if (src= -64 && val <= 63) mode = 1; // 7 bit difference - else if (val==0x7f) mode = 3; // 16 bit value - else if ((val&0xff)==0x80) mode = 2; // run length encoding - else mode = 2; - - if (src+mode > end+3) - break; // safety: overflow input data - } - - val = *src; - - if (val >= -64 && val <= 63) // 7 bits difference - { - dest[1] = val = dest[0] + val; - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - src++; - } - else if (val==0x7f) // 16 bit value - { - dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; - - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - src+=3; - } - else if ((val&0xff)==0x80) // run length encoding - { - mode = ((unsigned char *)src)[1]; - npixels -= mode-1; - if (npixels<=0) break; // safety: overflow output data - do - { - dest[1] = val = dest[0]; - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - } - while (--mode); - src+=2; - } - else - { - signed short diff = ((val^0x40)<<8) + ((unsigned char *)src)[1]; - dest[1] = val = dest[0] + diff; // 15 bit difference - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - src+=2; - } - } - while (--npixels); - - if (iCRC2 != pHeader->iOrgCRC) // if error in output CRC: - { - src = save; // check input CRC - while (src < end) - { - iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)src[0]] ^ ((iCRC >> 8)); - src++; - } - - if (iCRC != pHeader->iCompressedCRC) - { - AVSerror("XDR decompression: the file is corrupted"); - retvalue=0; - } - else - { - AVSerror("XDR decompression: internal error"); - retvalue=0; - } - } + global_len = sizeof(NKI_MODE2) + pHeader->iCompressedSize; + + break; + + case 3: + save = src; + + src += 8; // mode 3 only has 8 bytes header: iOrgSize and iMode + end = src + size - 3; // for overflow check if we are close to end of input buffer + + *dest = *(short int *)src; + src += 2; + npixels--; + + do { + if (src > end) { // check whether the last few messages fit in input buffer + if (src= -63 && val <= 63) mode = 1; // 7 bit difference + else if (val==0x7f) mode = 3; // 16 bit value + else if ((val&0xff)==0x80) mode = 2; // run length encoding + else if ((val&0xff)==0xC0) mode = 2; // 4 bit encoding + else mode = 2; + + if (src+mode > end+3) + return 0; // safety: overflow input data + } + + val = *src; + + if (val >= -63 && val <= 63) { // 7 bit difference + dest[1] = dest[0] + val; + dest++; + src++; + } else if (val==0x7f) { // 16 bit value + dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; + dest++; + src+=3; + } else if ((val&0xff)==0x80) { // run length encoding + mode = ((unsigned char *)src)[1]; + npixels -= mode-1; + if (npixels<=0) return 0; // safety: overflow output data + do { + dest[1] = dest[0]; + dest++; + } while (--mode); + src+=2; + } else if ((val&0xff)==0xC0) { // 4 bit run + mode = ((unsigned char *)src)[1]; + npixels -= mode-1; + mode/=2; + src+=2; + if (npixels<=0) return 0; // safety: overflow output data + do { + val = *src++; + dest[1] = dest[0] + (val>>4); + dest++; + if (val&8) val |= 0xfffffff0; + else val &= 0x0f; + dest[1] = dest[0] + val; + dest++; + } while (--mode); + } else { + signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]); + dest[1] = dest[0] + diff; // 15 bit difference + dest++; + src+=2; + } + } while (--npixels); - global_len = sizeof(NKI_MODE2) + pHeader->iCompressedSize; - - break; - - case 3: - save = src; - - src += 8; // mode 3 only has 8 bytes header: iOrgSize and iMode - end = src + size - 3; // for overflow check if we are close to end of input buffer - - *dest = *(short int *)src; - src += 2; - npixels--; - - do - { - if (src > end) // check whether the last few messages fit in input buffer - { - if (src= -63 && val <= 63) mode = 1; // 7 bit difference - else if (val==0x7f) mode = 3; // 16 bit value - else if ((val&0xff)==0x80) mode = 2; // run length encoding - else if ((val&0xff)==0xC0) mode = 2; // 4 bit encoding - else mode = 2; - - if (src+mode > end+3) - return 0; // safety: overflow input data - } - - val = *src; - - if (val >= -63 && val <= 63) // 7 bit difference - { - dest[1] = dest[0] + val; - dest++; - src++; - } - else if (val==0x7f) // 16 bit value - { - dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; - dest++; - src+=3; - } - else if ((val&0xff)==0x80) // run length encoding - { - mode = ((unsigned char *)src)[1]; - npixels -= mode-1; - if (npixels<=0) return 0; // safety: overflow output data - do - { - dest[1] = dest[0]; - dest++; - } - while (--mode); - src+=2; - } - else if ((val&0xff)==0xC0) // 4 bit run - { - mode = ((unsigned char *)src)[1]; - npixels -= mode-1; - mode/=2; - src+=2; - if (npixels<=0) return 0; // safety: overflow output data - do - { - val = *src++; - dest[1] = dest[0] + (val>>4); - dest++; - if (val&8) val |= 0xfffffff0; - else val &= 0x0f; - dest[1] = dest[0] + val; - dest++; - } - while (--mode); - } - else - { - signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]); - dest[1] = dest[0] + diff; // 15 bit difference - dest++; - src+=2; - } - } - while (--npixels); + global_len = src-save; + + break; + + case 4: + src += sizeof(NKI_MODE2); + save = src; + end = src + pHeader->iCompressedSize - 3; + + if (end > src + size - 3) + end = src + size - 3; // may occur if pHeader is corrupted - global_len = src-save; + *dest = val = *(short int *)src; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + src += 2; + npixels--; - break; + do { + if (src > end) { // check whether the last few messages fit in input buffer + if (srciCompressedSize - 3; + if (val >= -63 && val <= 63) mode = 1; // 7 bit difference + else if (val==0x7f) mode = 3; // 16 bit value + else if ((val&0xff)==0x80) mode = 2; // run length encoding + else if ((val&0xff)==0xC0) mode = 2; // 4 bit encoding + else mode = 2; - if (end > src + size - 3) - end = src + size - 3; // may occur if pHeader is corrupted + if (src+mode > end+3) + return 0; // safety: overflow input data + } - *dest = val = *(short int *)src; + val = *src; + + if (val >= -63 && val <= 63) { // 7 bit difference + dest[1] = val = dest[0] + val; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - src += 2; - npixels--; - - do - { - if (src > end) // check whether the last few messages fit in input buffer - { - if (src= -63 && val <= 63) mode = 1; // 7 bit difference - else if (val==0x7f) mode = 3; // 16 bit value - else if ((val&0xff)==0x80) mode = 2; // run length encoding - else if ((val&0xff)==0xC0) mode = 2; // 4 bit encoding - else mode = 2; - - if (src+mode > end+3) - return 0; // safety: overflow input data - } - - val = *src; - - if (val >= -63 && val <= 63) // 7 bit difference - { - dest[1] = val = dest[0] + val; - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - src++; - } - else if (val==0x7f) // 16 bit value - { - dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - src+=3; - } - else if ((val&0xff)==0x80) // run length encoding - { - mode = ((unsigned char *)src)[1]; - npixels -= mode-1; - if (npixels<=0) return 0; // safety: overflow output data - do - { - dest[1] = val = dest[0]; - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - } - while (--mode); - src+=2; - } - else if ((val&0xff)==0xC0) // 4 bit run - { - mode = ((unsigned char *)src)[1]; - npixels -= mode-1; - mode/=2; - src+=2; - if (npixels<=0) return 0; // safety: overflow output data - do - { - val = *src++; - dest[1] = j = dest[0] + (val>>4); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)j] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(j>>8)] ^ ((iCRC2 >> 8)); - dest++; - if (val&8) val |= 0xfffffff0; - else val &= 0x0f; - dest[1] = j = dest[0] + val; - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)j] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(j>>8)] ^ ((iCRC2 >> 8)); - dest++; - } - while (--mode); - } - else - { - signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]); - dest[1] = val = dest[0] + diff; // 15 bit difference - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); - iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); - dest++; - src+=2; - } - } - while (--npixels); + dest++; + src++; + } else if (val==0x7f) { // 16 bit value + dest[1] = val = ((int)(((unsigned char *)src)[1])<<8) + ((unsigned char*)src)[2]; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; + src+=3; + } else if ((val&0xff)==0x80) { // run length encoding + mode = ((unsigned char *)src)[1]; + npixels -= mode-1; + if (npixels<=0) return 0; // safety: overflow output data + do { + dest[1] = val = dest[0]; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; + } while (--mode); + src+=2; + } else if ((val&0xff)==0xC0) { // 4 bit run + mode = ((unsigned char *)src)[1]; + npixels -= mode-1; + mode/=2; + src+=2; + if (npixels<=0) return 0; // safety: overflow output data + do { + val = *src++; + dest[1] = j = dest[0] + (val>>4); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)j] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(j>>8)] ^ ((iCRC2 >> 8)); + dest++; + if (val&8) val |= 0xfffffff0; + else val &= 0x0f; + dest[1] = j = dest[0] + val; + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)j] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(j>>8)] ^ ((iCRC2 >> 8)); + dest++; + } while (--mode); + } else { + signed short diff = ((val^0x40)<<8) + (unsigned char)(src[1]); + dest[1] = val = dest[0] + diff; // 15 bit difference + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val] ^ ((iCRC2 >> 8)); + iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); + dest++; + src+=2; + } + } while (--npixels); - if (iCRC2 != pHeader->iOrgCRC) // if error in output CRC: - retvalue=0; + if (iCRC2 != pHeader->iOrgCRC) // if error in output CRC: + retvalue=0; - global_len = sizeof(NKI_MODE2) + pHeader->iCompressedSize; + global_len = sizeof(NKI_MODE2) + pHeader->iCompressedSize; - break; + break; - default: - AVSerror("XDR decompression: unsupported mode"); - return 0; - } + default: + AVSerror("XDR decompression: unsupported mode"); + return 0; + } - return retvalue; + return retvalue; } @@ -641,404 +575,379 @@ static int nki_private_decompress(short int *dest, signed char *src, int size) // Read image information (copied from XDRreader) int clitk::XdrImageIO::ReadImageInformationWithError() { - int offset=0; - itk::Vector dim; - int veclen=1; - int total=1; - unsigned int coords=0,i,j,ndim,nspace; - char temp[512]; - FILE *fstream; - char *c; - - long swap_test = 0x1000000; /* first byte is 1 when low-endian */ - forcenoswap=0; - char *file = const_cast(m_FileName.c_str()); - AVSType field=UNIFORM; - - - fstream = fopen(file, "rt"); + int offset=0; + itk::Vector dim; + int veclen=1; + int total=1; + unsigned int coords=0,i,j,ndim,nspace; + char temp[512]; + FILE *fstream; + char *c; + + long swap_test = 0x1000000; /* first byte is 1 when low-endian */ + forcenoswap=0; + char *file = const_cast(m_FileName.c_str()); + AVSType field=UNIFORM; + + + fstream = fopen(file, "rt"); + if (fstream == NULL) return ER_XDR_OPEN; + + fgets(temp, 500, fstream); + fclose(fstream); + + if (memcmp(temp, "# AVS field file (produced by avs_nfwrite.c)", 44)==0) forcenoswap=1; + + c = scan_header(file, "ndim", offset, 1); + if (!c) return ER_XDR_NDIM; + + ndim = atoi(c); + if (ndim<1 || ndim>MAXDIM) return ER_XDR_NDIM; + SetNumberOfDimensions(ndim); + + nspace = ndim; + + for (i=0; i MAXDIM) return ER_XDR_NSPACE; + if (nspace != ndim) return ER_NOT_HANDLED; + + c = scan_header(file, "veclen", offset, 1); + if (c) veclen = atoi(c); + if (veclen<0 /*|| veclen>1000*/) return ER_XDR_VECLEN; + SetNumberOfComponents(veclen); + if (veclen==1) SetPixelType(itk::ImageIOBase::SCALAR); + else SetPixelType(itk::ImageIOBase::VECTOR); + + c = scan_header(file, "data", offset, 1); + if (c) { + if (memicmp(c, "byte", 4) == 0 || memicmp(c, "xdr_byte", 8) == 0) SetComponentType(itk::ImageIOBase::CHAR); + else if (memicmp(c, "short", 5) == 0 || memicmp(c, "xdr_short", 9) == 0) SetComponentType(itk::ImageIOBase::SHORT); + else if (memicmp(c, "int" , 3) == 0 || memicmp(c, "xdr_int" , 7) == 0) SetComponentType(itk::ImageIOBase::INT); + else if (memicmp(c, "real", 4) == 0 || memicmp(c, "xdr_real", 8) == 0) SetComponentType(itk::ImageIOBase::FLOAT); + else if (memicmp(c, "float", 5) == 0 || memicmp(c, "xdr_float", 9) == 0) SetComponentType(itk::ImageIOBase::FLOAT); + else if (memicmp(c, "double",6) == 0 || memicmp(c, "xdr_double",10)== 0) SetComponentType(itk::ImageIOBase::DOUBLE); + else return ER_XDR_DATA; + + if (memicmp(c, "xdr_", 4) == 0) forcenoswap=0; + } + + //Read coords here + c = scan_header(file, "field", offset, 1); + if (c) { + if (memicmp(c, "unifo", 5) == 0) field=UNIFORM, coords=nspace *2; + else if (memicmp(c, "recti", 5) == 0) field=RECTILINEAR; + else if (memicmp(c, "irreg", 5) == 0) field=IRREGULAR, coords=total*nspace; + else return ER_XDR_FIELD; + } else + coords=0; + + if (coords) { /* expect AVS coordinates ? */ + coords *= sizeof(float); + fstream = fopen(m_FileName.c_str(), "rb"); if (fstream == NULL) return ER_XDR_OPEN; - fgets(temp, 500, fstream); - fclose(fstream); - - if (memcmp(temp, "# AVS field file (produced by avs_nfwrite.c)", 44)==0) forcenoswap=1; - - c = scan_header(file, "ndim", offset, 1); - if (!c) return ER_XDR_NDIM; - - ndim = atoi(c); - if (ndim<1 || ndim>MAXDIM) return ER_XDR_NDIM; - SetNumberOfDimensions(ndim); - - nspace = ndim; - - for (i=0; i MAXDIM) return ER_XDR_NSPACE; - if (nspace != ndim) return ER_NOT_HANDLED; - - c = scan_header(file, "veclen", offset, 1); - if (c) veclen = atoi(c); - if (veclen<0 /*|| veclen>1000*/) return ER_XDR_VECLEN; - SetNumberOfComponents(veclen); - if (veclen==1) SetPixelType(itk::ImageIOBase::SCALAR); - else SetPixelType(itk::ImageIOBase::VECTOR); - - c = scan_header(file, "data", offset, 1); - if (c) - { - if (memicmp(c, "byte", 4) == 0 || memicmp(c, "xdr_byte", 8) == 0) SetComponentType(itk::ImageIOBase::CHAR); - else if (memicmp(c, "short", 5) == 0 || memicmp(c, "xdr_short", 9) == 0) SetComponentType(itk::ImageIOBase::SHORT); - else if (memicmp(c, "int" , 3) == 0 || memicmp(c, "xdr_int" , 7) == 0) SetComponentType(itk::ImageIOBase::INT); - else if (memicmp(c, "real", 4) == 0 || memicmp(c, "xdr_real", 8) == 0) SetComponentType(itk::ImageIOBase::FLOAT); - else if (memicmp(c, "float", 5) == 0 || memicmp(c, "xdr_float", 9) == 0) SetComponentType(itk::ImageIOBase::FLOAT); - else if (memicmp(c, "double",6) == 0 || memicmp(c, "xdr_double",10)== 0) SetComponentType(itk::ImageIOBase::DOUBLE); - else return ER_XDR_DATA; - - if (memicmp(c, "xdr_", 4) == 0) forcenoswap=0; - } - - //Read coords here - c = scan_header(file, "field", offset, 1); - if (c) - { - if (memicmp(c, "unifo", 5) == 0) field=UNIFORM, coords=nspace *2; - else if (memicmp(c, "recti", 5) == 0) field=RECTILINEAR; - else if (memicmp(c, "irreg", 5) == 0) field=IRREGULAR, coords=total*nspace; - else return ER_XDR_FIELD; - } - else - coords=0; - - if (coords) /* expect AVS coordinates ? */ - { - coords *= sizeof(float); - fstream = fopen(m_FileName.c_str(), "rb"); - if (fstream == NULL) return ER_XDR_OPEN; - - float *points = (float *)malloc(coords); - if (points == NULL) return ER_OUTOFMEMORY; - - //Seek to coordinates position in file - if (fseek(fstream,-static_cast(coords),SEEK_END)) return ER_XDR_READ; - if (fread( /*(*output)->*/points, 1, coords, fstream ) == coords) - { /* swap data if read-ok and required (xdr is low-endian) */ - if (!(*(char *)(&swap_test)) && !forcenoswap) - { - c = (char *)/*(*output)->*/points; - for (i=0; i(coords),SEEK_END)) return ER_XDR_READ; + if (fread( /*(*output)->*/points, 1, coords, fstream ) == coords) { + /* swap data if read-ok and required (xdr is low-endian) */ + if (!(*(char *)(&swap_test)) && !forcenoswap) { + c = (char *)/*(*output)->*/points; + for (i=0; i0.1) { - free(points); - fclose(fstream); - return ER_NOT_HANDLED; - } - } - points += (int)GetDimensions(i); - } - for (i=0; i0.1) { free(points); fclose(fstream); return ER_NOT_HANDLED; + } } - free(points); - fclose(fstream); + points += (int)GetDimensions(i); + } + for (i=0; i(m_FileName.c_str()); - int offset=0; - AVSType field=UNIFORM; - - for (i=0; i(m_FileName.c_str()); + int offset=0; + AVSType field=UNIFORM; + + for (i=0; i(i)+2-static_cast(iNumRead), SEEK_CUR); - if (temp[0] == 12) - { - fseek(fstream, -2, SEEK_CUR); - break; - } /* ^L end of header */ + if (total && iNkiCompression) { + long iCurPos; + unsigned long iSize; + signed char* pCompressed; - if (temp[0] != '#') break; - } + /* Read or guess the size of the compressed data */ + iCurPos = ftell(fstream); + iSize = get_nki_compressed_size(fstream); - buff = (char*)malloc(HeaderSize); - if (buff == NULL) - { - return ER_OUTOFMEMORY; - } - memset(buff, 0, HeaderSize); - iNumRead = fread(buff, 1, HeaderSize, fstream); - if (iNumRead < 1) - { - free(buff); - fclose(fstream); - return ER_XDR_READ; - } + if (iSize==0) { + fseek(fstream, 0, SEEK_END); + iSize = ftell(fstream); + iSize = iSize - iCurPos - coords; - for (i=0; itotal && offset) iSize=total+8; } - free(buff); - - if (i==iNumRead) return ER_XDR_NOCTRLL; - - total = GetImageSizeInBytes(); - - //We add casts because the resulting quantity can be negative. - //There is no risk of looping because i and iNumRead are about the size of the header - fseek(fstream, static_cast(i)+2-static_cast(iNumRead), SEEK_CUR); - - if (total && iNkiCompression) - { - long iCurPos; - unsigned long iSize; - signed char* pCompressed; - - /* Read or guess the size of the compressed data */ - iCurPos = ftell(fstream); - iSize = get_nki_compressed_size(fstream); - - if (iSize==0) - { - fseek(fstream, 0, SEEK_END); - iSize = ftell(fstream); - iSize = iSize - iCurPos - coords; + fseek(fstream, iCurPos, SEEK_SET); - // Get compressed size from header if possible; else use uncompressed size as safe estimate - if (iSize>total && offset) iSize=total+8; - } + /* Allocate space for the compressed pixels */ + pCompressed = (signed char*)malloc(iSize); + if (!pCompressed) { + fclose(fstream); + return ER_OUTOFMEMORY; + } - fseek(fstream, iCurPos, SEEK_SET); + /* Read the compressed pixels */ + if (fread( (void *)pCompressed, 1, iSize, fstream ) != iSize) { + fclose(fstream); + return ER_XDR_READ; + } - /* Allocate space for the compressed pixels */ - pCompressed = (signed char*)malloc(iSize); - if (!pCompressed) - { - fclose(fstream); - return ER_OUTOFMEMORY; - } + if (!nki_private_decompress((short*)buffer, pCompressed, iSize)) { + fclose(fstream); + return ER_DECOMPRESSION; + } - /* Read the compressed pixels */ - if (fread( (void *)pCompressed, 1, iSize, fstream ) != iSize) - { - fclose(fstream); - return ER_XDR_READ; - } + // if (offset) + fseek(fstream, iCurPos + global_len, SEEK_SET); - if (!nki_private_decompress((short*)buffer, pCompressed, iSize)) - { - fclose(fstream); - return ER_DECOMPRESSION; - } + free(pCompressed); + goto READ_COORDS; + } - // if (offset) - fseek(fstream, iCurPos + global_len, SEEK_SET); - free(pCompressed); - goto READ_COORDS; + if (total) { + if (fread( (void *)buffer, 1, total, fstream ) != total) { + fclose(fstream); + return ER_XDR_READ; } - - - if (total) - { - if (fread( (void *)buffer, 1, total, fstream ) != total) - { - fclose(fstream); - return ER_XDR_READ; - } - } - - /* swap data if required (xdr is low-endian) */ - - datasize = GetComponentSize(); - if (!(*(char *)(&swap_test)) && !forcenoswap) - { - if (datasize==2) - { - c = (char *)buffer; - for (i=0; i(""); +{ + char *s = const_cast(""); WriteImage( m_FileName.c_str(), s, s, 0, -1, 0, 2, 0, 0, 0, 0, buffer); } @@ -104,7 +106,7 @@ void clitk::XdrImageIO::Write(const void* buffer) #include #ifdef WIN32 -// don't use min() and max() macros indirectly defined by windows.h, +// don't use min() and max() macros indirectly defined by windows.h, // but use portable std::min() and std:max() instead #ifndef NOMINMAX #define NOMINMAX @@ -127,8 +129,7 @@ void clitk::XdrImageIO::Write(const void* buffer) // // Compression modes 1 and 3 (without CRCs) only use the first 2 members (iOrgSize and iMode). -typedef struct -{ +typedef struct { unsigned int iOrgSize; /* in pixels (i.e. shorts) */ unsigned int iMode; /* 1, 2, 3 or 4 */ unsigned int iCompressedSize; /* in bytes, excluding header */ @@ -136,16 +137,15 @@ typedef struct unsigned int iCompressedCRC; /* CRC of the compressed data, excluding this header */ } NKI_MODE2; -typedef struct -{ +typedef struct { unsigned int iOrgSize; /* in pixels (i.e. shorts) */ unsigned int iMode; /* 1, 2, 3 or 4 */ unsigned int iCompressedSize; /* in bytes, excluding header */ unsigned int iOrgCRC; /* CRC of the data (no coords etc) */ unsigned int iCompressedCRC; /* CRC of the compressed data, excluding this header */ unsigned int iPad; /* unused */ - Q_UINT64 i64OrgSize; /* used for more than UINT_MAX pixels, indicated by iOrgSize==0 (0-vector not compressed) */ - Q_UINT64 i64CompressedSize; /* value in BYTES, used for more than UINT_MAX PIXELS, indicated by iCompressedSize==0 */ + Q_UINT64 i64OrgSize; /* used for more than UINT_MAX pixels, indicated by iOrgSize==0 (0-vector not compressed) */ + Q_UINT64 i64CompressedSize; /* value in BYTES, used for more than UINT_MAX PIXELS, indicated by iCompressedSize==0 */ Q_UINT64 i64Future1; Q_UINT64 i64Future2; } NKI_MODE2_64BITS; @@ -166,49 +166,49 @@ typedef struct /************************************************************************/ static const unsigned long CRC32_table[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, + 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, + 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, + 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, + 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, + 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, + 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, + 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, + 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, + 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, + 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, + 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, + 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, + 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, + 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, + 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, + 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, + 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, + 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, + 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, + 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, + 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, + 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, + 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, + 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, + 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, + 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, + 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, + 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; /************************************************************************/ @@ -219,10 +219,11 @@ static const unsigned long CRC32_table[256] = { _WCRTLINK #endif int writefix(int file, const void *buf, unsigned int count) -{ int j, k, total=0; +{ + int j, k, total=0; - for (unsigned i=0; i16384) j=16384; k=write(file, (char *)buf+i, j); @@ -251,34 +252,33 @@ int writefix(int file, const void *buf, unsigned int count) static int wxdr_write(int handle, const void * buf, unsigned len) { // if (handle == 1) // stdout - if (handle == fileno(stdout)) - { + if (handle == fileno(stdout)) { #ifdef WIN32 // Behave as C standard library write(): return number of bytes // written or -1 and errno set on error. fflush(stdout); DWORD dwBytesWritten; if (!WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, len, - &dwBytesWritten, NULL)) - { + &dwBytesWritten, NULL)) { // There is no simple 1-to-1 mapping between GetLastError() // values that WriteFile() can return (quite a lot) and the two // errno values that write() can return. So return EACCES in // almost all cases. - switch (GetLastError()) - { case ERROR_INVALID_HANDLE: - errno = EBADF ; break; - default: - errno = EACCES; break; + switch (GetLastError()) { + case ERROR_INVALID_HANDLE: + errno = EBADF ; + break; + default: + errno = EACCES; + break; } return -1; - } - else + } else return (int)dwBytesWritten; // May still be < len! - // And... write() may write a maximum of UINT_MAX-1 bytes, whereas - // WriteFile() may write UINT_MAX bytes at once. But since - // int(UINT_MAX) == -1 this will pose an actual problem in the - // (far?) future. + // And... write() may write a maximum of UINT_MAX-1 bytes, whereas + // WriteFile() may write UINT_MAX bytes at once. But since + // int(UINT_MAX) == -1 this will pose an actual problem in the + // (far?) future. #else // !WIN32 //const int oldmode = setmode(handle, O_BINARY);//commented out by joel const int iBytesWritten = write(handle, buf, len); @@ -287,8 +287,7 @@ static int wxdr_write(int handle, const void * buf, unsigned len) errno = saveerrno; return iBytesWritten; #endif // !WIN32 - } - else + } else return write(handle, buf, len); } @@ -323,22 +322,22 @@ static int wxdr_write(int handle, const void * buf, unsigned len) !!! SIDE EFFECT !!! Note that checked_write() takes a size_t for len, whereas write() takes - an unsigned int of 4 bytes. On a 64 bits OS a size_t will be an 8 byte integer, + an unsigned int of 4 bytes. On a 64 bits OS a size_t will be an 8 byte integer, enabling more than UINT_MAX bytes to write at once. */ static bool checked_write(int handle, const void * buf, size_t len, char **buffer) -{ if (buffer && !handle) - { memcpy(*buffer, buf, len); +{ + if (buffer && !handle) { + memcpy(*buffer, buf, len); (*buffer) += len; return true; } - if (buffer && handle) - { (*buffer) += len; + if (buffer && handle) { + (*buffer) += len; return true; - } - else - { for(int i=0; i<2; i++) - { int byteswritten; + } else { + for(int i=0; i<2; i++) { + int byteswritten; size_t remaining; int chunksize; @@ -348,12 +347,12 @@ static bool checked_write(int handle, const void * buf, size_t len, char **buffe // that is larger than 64 MB in Visual C++ 2005, // in Visual C++ .NET 2003, or in Visual C++ .NET 2002" // NB: same thing for write function in binary mode - if (i==0) - { remaining = len; - // call wxdr_write (for handle!=fileno(stdout) a wrapper for write) several times + if (i==0) { + remaining = len; + // call wxdr_write (for handle!=fileno(stdout) a wrapper for write) several times // to interpret the signed 32-bit return value correctly - while (remaining>0) - { chunksize = (int)std::min(remaining, (size_t)INT_MAX); + while (remaining>0) { + chunksize = (int)std::min(remaining, (size_t)INT_MAX); byteswritten = wxdr_write(handle, buf, chunksize); if (byteswritten == chunksize) remaining -= chunksize; @@ -362,18 +361,17 @@ static bool checked_write(int handle, const void * buf, size_t len, char **buffe } if (remaining == 0) return true; - } - else - { remaining = len; - // call writefix (in mbfield.c) several times to interpret the signed 32-bit + } else { + remaining = len; + // call writefix (in mbfield.c) several times to interpret the signed 32-bit // return value correctly. writefix uses chunks of 16384 bytes - while (remaining>0) - { chunksize = (int)std::min(remaining, (size_t)INT_MAX); + while (remaining>0) { + chunksize = (int)std::min(remaining, (size_t)INT_MAX); byteswritten = writefix(handle, buf, chunksize); if (byteswritten == chunksize) remaining -= chunksize; else - break; // even writefix failed: return error + break; // even writefix failed: return error } if (remaining == 0) return true; @@ -434,7 +432,8 @@ static bool checked_write(int handle, const void * buf, size_t len, char **buffe // This internal routine converts an 8 bit difference string into a 4 bit one static signed char *recompress4bit(int n, signed char *dest) -{ signed char *p, *q; +{ + signed char *p, *q; int val; n = n & 0xfe; @@ -446,8 +445,8 @@ static signed char *recompress4bit(int n, signed char *dest) *dest++ = (signed char)n; q = dest++; n -= 2; - while(n>0) - { *dest++ = (signed char)((((int)p[0])<<4) | (p[1]&15)); + while(n>0) { + *dest++ = (signed char)((((int)p[0])<<4) | (p[1]&15)); p += 2; n -= 2; } @@ -458,7 +457,8 @@ static signed char *recompress4bit(int n, signed char *dest) static size_t nki_private_compress(signed char *dest, short int *src, size_t npixels, int iMode) -{ unsigned long iCRC; +{ + unsigned long iCRC; unsigned long iCRC2; unsigned int iHeaderSize=8; // value for iMode==1 and iMode==3 register int val; @@ -476,14 +476,13 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n /* Create the header */ pHeader->iMode = iMode; - if (sizeof(int*)>sizeof(int) && npixels>UINT_MAX) // On a 64 bits OS we want to store files>4GB - { pHeader_64bits->iOrgSize = 0; // This indicates>4GB file (0-vector is not compressed) - pHeader_64bits->i64OrgSize = npixels; + if (sizeof(int*)>sizeof(int) && npixels>UINT_MAX) { // On a 64 bits OS we want to store files>4GB + pHeader_64bits->iOrgSize = 0; // This indicates>4GB file (0-vector is not compressed) + pHeader_64bits->i64OrgSize = npixels; iHeaderSize = sizeof(NKI_MODE2_64BITS); dest += sizeof(NKI_MODE2_64BITS); - } - else - { pHeader->iOrgSize = (unsigned int)(npixels & UINT_MAX); // store 32 bit number as first member + } else { + pHeader->iOrgSize = (unsigned int)(npixels & UINT_MAX); // store 32 bit number as first member if (iMode==2 || iMode==4) iHeaderSize = sizeof(NKI_MODE2); @@ -492,23 +491,23 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n /* Create the compressed image */ - if (iMode == 1) - { *(short int *)dest = *src; + if (iMode == 1) { + *(short int *)dest = *src; dest+=2; npixels--; - do - { val = src[1] - src[0]; + do { + val = src[1] - src[0]; src++; - if (val == 0) /* run length-encode zero differences */ - { for (i=2;; i++) - { if (i>=npixels || src[i-1]!=src[-1] || i==256) - { if (i==2) + if (val == 0) { /* run length-encode zero differences */ + for (i=2;; i++) { + if (i>=npixels || src[i-1]!=src[-1] || i==256) { + if (i==2) *dest++=0; - else - { *dest++ = -128; // hexadecimal 0x80 + else { + *dest++ = -128; // hexadecimal 0x80 *dest++ = (signed char)(i-1); npixels -= (i-2); src += (i-2); @@ -516,30 +515,26 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n break; } } - } - else if (val >= -64 && val <= 63) /* small difference coded as one byte */ - { *dest = (signed char)val; + } else if (val >= -64 && val <= 63) { /* small difference coded as one byte */ + *dest = (signed char)val; dest++; - } - else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */ - { dest[0] = (signed char)((val>>8) ^ 0x40); + } else if (val >= -0x3F00 && val <= 0x3EFF) { /* large differences coded as two bytes */ + dest[0] = (signed char)((val>>8) ^ 0x40); dest[1] = (signed char)val; dest+=2; - } - else /* if very large differences code abs val as three bytes */ - { *dest++ = 0x7F; + } else { /* if very large differences code abs val as three bytes */ + *dest++ = 0x7F; *dest++ = (signed char)(src[0]>>8); *dest++ = (signed char)(src[0]); } /* Are we beyond the allocated memory? */ if ((size_t)(dest - (signed char*)pHeader) > iBufferSize) - return 0; - } - while (--npixels); + return 0; + } while (--npixels); } - else if (iMode == 2) - { iCRC = 0; + else if (iMode == 2) { + iCRC = 0; iCRC2 = 0; *(short int *)dest = val = *src; @@ -550,28 +545,27 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n dest+=2; npixels--; - do - { val = src[1] - src[0]; + do { + val = src[1] - src[0]; src++; iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) src[0] ] ^ ((iCRC >> 8)); iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8)); - if (val == 0) /* run length-encode zero differences */ - { for (i=2;; i++) - { if (i>=npixels || src[i-1]!=src[-1] || i==256) - { if (i==2) - { *dest++=0; + if (val == 0) { /* run length-encode zero differences */ + for (i=2;; i++) { + if (i>=npixels || src[i-1]!=src[-1] || i==256) { + if (i==2) { + *dest++=0; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0 ] ^ ((iCRC2 >> 8)); - } - else - { *dest++ = -128; // hexadecimal 0x80 + } else { + *dest++ = -128; // hexadecimal 0x80 iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0x80 ] ^ ((iCRC2 >> 8)); *dest++ = (signed char)(i-1); iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (i-1)] ^ ((iCRC2 >> 8)); npixels -= (i-2); - for (j=0; j> 8)); iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8)); } @@ -579,44 +573,40 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n break; } } - } - else if (val >= -64 && val <= 63) /* small difference coded as one byte */ - { *dest = (signed char)val; + } else if (val >= -64 && val <= 63) { /* small difference coded as one byte */ + *dest = (signed char)val; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val ] ^ ((iCRC2 >> 8)); dest++; - } - else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */ - { dest[0] = (signed char)((val>>8) ^ 0x40); + } else if (val >= -0x3F00 && val <= 0x3EFF) { /* large differences coded as two bytes */ + dest[0] = (signed char)((val>>8) ^ 0x40); iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)dest[0] ] ^ ((iCRC2 >> 8)); dest[1] = (signed char)val; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val ] ^ ((iCRC2 >> 8)); dest+=2; - } - else /* if very large differences code abs val as three bytes */ - { dest[0] = 0x7F; + } else { /* if very large differences code abs val as three bytes */ + dest[0] = 0x7F; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0x7f ] ^ ((iCRC2 >> 8)); - val = src[0]; + val = src[0]; dest[1] = (signed char)(val>>8); iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)(val>>8)] ^ ((iCRC2 >> 8)); dest[2] = (signed char)val; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ (unsigned char)val ] ^ ((iCRC2 >> 8)); - dest+=3; + dest+=3; } /* Are we beyond the allocated memory? */ if ((size_t)(dest - (signed char*)pHeader) > iBufferSize) - return 0; - } - while (--npixels); - + return 0; + } while (--npixels); + if ((dest - (signed char*)pHeader - iHeaderSize)iCompressedSize = + pHeader->iCompressedSize = (unsigned int)(dest - (signed char*)pHeader - iHeaderSize); else // store 64 bit number in extended structure pHeader_64bits->i64CompressedSize = dest - (signed char*)pHeader -iHeaderSize; /* Pad it to get an even length */ - if (pHeader->iCompressedSize & 1) - { *dest++ = 0; + if (pHeader->iCompressedSize & 1) { + *dest++ = 0; iCRC2 = CRC32_table[(unsigned char)iCRC2 ^ 0] ^ ((iCRC2 >> 8)); pHeader->iCompressedSize++; } @@ -627,32 +617,31 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n /* Create the compressed image - compressor with added 4 bit run */ - else if (iMode == 3) - { int n4bit=0; + else if (iMode == 3) { + int n4bit=0; *(short int *)dest = *src; dest+=2; npixels--; - do - { val = src[1] - src[0]; + do { + val = src[1] - src[0]; src++; - if (val == 0) /* run length-encode zero differences */ - { for (i=2;; i++) - { if (i>=npixels || src[i-1]!=src[-1] || i==256) - { if (i<=MINZEROS) /* too short run -> write zeros */ - { for (j=0; j=npixels || src[i-1]!=src[-1] || i==256) { + if (i<=MINZEROS) { /* too short run -> write zeros */ + for (j=0; j=254) /* maximum length 4 bit run */ - { dest = recompress4bit(n4bit, dest); + if(n4bit>=254) { /* maximum length 4 bit run */ + dest = recompress4bit(n4bit, dest); n4bit = 0; } } - } - else - { if (n4bit>=MIN4BIT) /* end (and write) 4 bit run */ + } else { + if (n4bit>=MIN4BIT) /* end (and write) 4 bit run */ dest = recompress4bit(n4bit, dest); n4bit=0; @@ -665,30 +654,26 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n break; } } - } - else if (val >= -63 && val <= 63) /* small difference coded as one byte */ - { if (val >= -8 && val <= 7) - { *dest++ = (signed char)val; + } else if (val >= -63 && val <= 63) { /* small difference coded as one byte */ + if (val >= -8 && val <= 7) { + *dest++ = (signed char)val; n4bit++; - if(n4bit>=254) /* maximum length 4 bit run */ - { dest = recompress4bit(n4bit, dest); + if(n4bit>=254) { /* maximum length 4 bit run */ + dest = recompress4bit(n4bit, dest); n4bit=0; } - } - else if(n4bit>=MIN4BIT) /* end and write 4 bit run */ - { j = val; + } else if(n4bit>=MIN4BIT) { /* end and write 4 bit run */ + j = val; dest = recompress4bit(n4bit, dest); n4bit=0; *dest++ = (signed char)j; + } else { + *dest++ = (signed char)val; /* end 4 bit run */ + n4bit = 0; } - else - { *dest++ = (signed char)val; /* end 4 bit run */ - n4bit = 0; - } - } - else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */ - { j = val; + } else if (val >= -0x3F00 && val <= 0x3EFF) { /* large differences coded as two bytes */ + j = val; if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */ dest = recompress4bit(n4bit, dest); @@ -697,9 +682,8 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n dest[0] = (signed char)((j>>8) ^ 0x40); dest[1] = (signed char)j; dest+=2; - } - else /* if very large differences code abs val as three bytes */ - { j = src[0]; + } else { /* if very large differences code abs val as three bytes */ + j = src[0]; if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */ dest = recompress4bit(n4bit, dest); @@ -711,15 +695,14 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n } /* Are we beyond the allocated memory? */ if ((size_t)(dest - (signed char*)pHeader) > iBufferSize) - return 0; - } - while (--npixels); + return 0; + } while (--npixels); } /* Create the compressed image - compressor with added 4 bit run and CRC */ - else if (iMode == 4) - { int n4bit=0; + else if (iMode == 4) { + int n4bit=0; iCRC = 0; *(short int *)dest = val = *src; @@ -728,28 +711,27 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n dest+=2; npixels--; - do - { val = src[1] - src[0]; + do { + val = src[1] - src[0]; src++; iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char) src[0] ] ^ ((iCRC >> 8)); iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8)); - if (val == 0) /* run length-encode zero differences */ - { for (i=2;; i++) - { if (i>=npixels || src[i-1]!=src[-1] || i==256) - { if (i<=MINZEROS) /* too short run -> write zeros */ - { for (j=0; j=npixels || src[i-1]!=src[-1] || i==256) { + if (i<=MINZEROS) { /* too short run -> write zeros */ + for (j=0; j=254) /* maximum length 4 bit run */ - { dest = recompress4bit(n4bit, dest); + if(n4bit>=254) { /* maximum length 4 bit run */ + dest = recompress4bit(n4bit, dest); n4bit = 0; } } - } - else - { if (n4bit>=MIN4BIT) /* end (and write) 4 bit run */ + } else { + if (n4bit>=MIN4BIT) /* end (and write) 4 bit run */ dest = recompress4bit(n4bit, dest); n4bit=0; @@ -758,38 +740,34 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n } npixels -= (i-2); - for (j=0; j> 8)); iCRC = CRC32_table[(unsigned char)iCRC ^ (unsigned char)(src[0]>>8)] ^ ((iCRC >> 8)); } break; } } - } - else if (val >= -63 && val <= 63) /* small difference coded as one byte */ - { if (val >= -8 && val <= 7) - { *dest++ = (signed char)val; + } else if (val >= -63 && val <= 63) { /* small difference coded as one byte */ + if (val >= -8 && val <= 7) { + *dest++ = (signed char)val; n4bit++; - if(n4bit>=254) /* maximum length 4 bit run */ - { dest = recompress4bit(n4bit, dest); + if(n4bit>=254) { /* maximum length 4 bit run */ + dest = recompress4bit(n4bit, dest); n4bit=0; } - } - else if(n4bit>=MIN4BIT) /* end and write 4 bit run */ - { j = val; + } else if(n4bit>=MIN4BIT) { /* end and write 4 bit run */ + j = val; dest = recompress4bit(n4bit, dest); n4bit=0; *dest++ = (signed char)j; + } else { + *dest++ = (signed char)val; /* end 4 bit run */ + n4bit = 0; } - else - { *dest++ = (signed char)val; /* end 4 bit run */ - n4bit = 0; - } - } - else if (val >= -0x3F00 && val <= 0x3EFF) /* large differences coded as two bytes */ - { j = val; + } else if (val >= -0x3F00 && val <= 0x3EFF) { /* large differences coded as two bytes */ + j = val; if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */ dest = recompress4bit(n4bit, dest); @@ -798,9 +776,8 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n dest[0] = (signed char)((j>>8) ^ 0x40); dest[1] = (signed char)j; dest+=2; - } - else /* if very large differences code abs val as three bytes */ - { j = src[0]; + } else { /* if very large differences code abs val as three bytes */ + j = src[0]; if(n4bit>=MIN4BIT) /* end (and write) 4 bit run */ dest = recompress4bit(n4bit, dest); @@ -812,21 +789,20 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n } /* Are we beyond the allocated memory? */ if ((size_t)(dest - (signed char*)pHeader) > iBufferSize) - return 0; - } - while (--npixels); + return 0; + } while (--npixels); if ((dest - (signed char*)pHeader - iHeaderSize)iCompressedSize = + pHeader->iCompressedSize = (unsigned int)(dest - (signed char*)pHeader - iHeaderSize); - else // store 64 bit number in extended structure - { pHeader_64bits->iCompressedSize = 0; + else { // store 64 bit number in extended structure + pHeader_64bits->iCompressedSize = 0; pHeader_64bits->i64CompressedSize = dest - (signed char*)pHeader -iHeaderSize; } /* Pad it to get an even length */ - if (pHeader->iCompressedSize & 1) - { *dest++ = 0; + if (pHeader->iCompressedSize & 1) { + *dest++ = 0; pHeader->iCompressedSize++; } @@ -841,7 +817,8 @@ static size_t nki_private_compress(signed char *dest, short int *src, size_t n void clitk::XdrImageIO::WriteImage(const char* file, char* headerinfo, char* headerfile, int raw, int offset, char bLittleEndian, int iNkiCompression, int wcoords, int append, int getsize, char *tobuffer, const void* data) -{ AVSINT total=1; +{ + AVSINT total=1; unsigned int i; AVSINT coords=0; int f=0; @@ -860,102 +837,100 @@ void clitk::XdrImageIO::WriteImage(const char* file, char* headerinfo, char* hea if (bLittleEndian) swap_test = 0x00000001; - if (getsize) - { swap_test = 0xffffffff; // never swap to save time + if (getsize) { + swap_test = 0xffffffff; // never swap to save time buffer = (char **) &len; f = 1; } - if (tobuffer) - { buf2 = (char *)tobuffer; + if (tobuffer) { + buf2 = (char *)tobuffer; buffer = &buf2; f = 0; } - for (i=0; i 0) && - (GetComponentType() == itk::ImageIOBase::SHORT) && - (GetPixelType() == itk::ImageIOBase::SCALAR)) - { pCompressed = (signed char *)malloc((total/2) * 3 + sizeof(NKI_MODE2_64BITS) + 10); - if (pCompressed==NULL) - { iNkiCompression = 0; + (GetComponentType() == itk::ImageIOBase::SHORT) && + (GetPixelType() == itk::ImageIOBase::SCALAR)) { + pCompressed = (signed char *)malloc((total/2) * 3 + sizeof(NKI_MODE2_64BITS) + 10); + if (pCompressed==NULL) { + iNkiCompression = 0; AVSwarning("Avs_wxdr: not enough memory to compress data, saving uncompressed"); } } - if (!(tobuffer || getsize)) - { if (offset != -1) - { f = open(file, O_RDWR, 0); - if (f < 0) - { + if (!(tobuffer || getsize)) { + if (offset != -1) { + f = open(file, O_RDWR, 0); + if (f < 0) { AVSerror("Avs_wxdr: Opening " << file << "failed.\n" << strerror(errno)); free(pCompressed); return AVS_ERROR; } lseek(f, offset, SEEK_SET); - } - else - { if (strlen(file)==0) + } else { + if (strlen(file)==0) f = fileno(stdout); - else - { if (append) + else { + if (append) f = open(file, O_RDWR | O_APPEND, 0); else f = creat(file, S_IWRITE | S_IREAD); } - if (f < 0) - { AVSerror("Avs_wxdr: Creating " << file << " failed.\n" << strerror(errno)); + if (f < 0) { + AVSerror("Avs_wxdr: Creating " << file << " failed.\n" << strerror(errno)); free(pCompressed); return AVS_ERROR; } } } - if (!raw) - { sprintf(temp, "# AVS wants to have the first line starting with its name\n"); + if (!raw) { + sprintf(temp, "# AVS wants to have the first line starting with its name\n"); slen = strlen(temp); - if (!checked_write(f, temp, slen, buffer)) - { free(pCompressed); + if (!checked_write(f, temp, slen, buffer)) { + free(pCompressed); return AVS_ERROR; } FilePos += slen; slen = strlen(headerinfo); - if (slen && !checked_write(f, headerinfo, slen, buffer)) - { free(pCompressed); + if (slen && !checked_write(f, headerinfo, slen, buffer)) { + free(pCompressed); return AVS_ERROR; } FilePos += slen; - if (!checked_write(f, "\n", 1, buffer)) - { free(pCompressed); + if (!checked_write(f, "\n", 1, buffer)) { + free(pCompressed); return AVS_ERROR; } FilePos++; - if (strlen(headerfile)) - { fp = fopen(headerfile, "rt"); - if (fp) - { for (;;) - { if (fgets(temp, 255, fp) == NULL) break; + if (strlen(headerfile)) { + fp = fopen(headerfile, "rt"); + if (fp) { + for (;;) { + if (fgets(temp, 255, fp) == NULL) break; slen = strlen(temp); - if (!checked_write(f, temp, slen, buffer)) - { fclose(fp); + if (!checked_write(f, temp, slen, buffer)) { + fclose(fp); free(pCompressed); return AVS_ERROR; } FilePos += slen; } fclose(fp); - if (!checked_write(f, "\n", 1, buffer)) - { free(pCompressed); + if (!checked_write(f, "\n", 1, buffer)) { + free(pCompressed); return AVS_ERROR; } FilePos++; @@ -964,55 +939,66 @@ void clitk::XdrImageIO::WriteImage(const char* file, char* headerinfo, char* hea sprintf(temp, "ndim=%d\n", GetNumberOfDimensions()); slen = strlen(temp); - if (!checked_write(f, temp, slen, buffer)) - { free(pCompressed); + if (!checked_write(f, temp, slen, buffer)) { + free(pCompressed); return AVS_ERROR; } FilePos += slen; } - for (i=0; iuniform) - //{ case UNIFORM : + //{ case UNIFORM : strcpy(temp, "field=uniform\n"); coords = GetNumberOfDimensions() * 2; - // break; + // break; // case RECTILINEAR : strcpy(temp, "field=rectilinear\n"); - // break; + // break; // case IRREGULAR : strcpy(temp, "field=irregular\n"); - // coords = total * input->nspace; - // break; + // coords = total * input->nspace; + // break; // default : if (f != fileno(stdout)) close(f); // free(pCompressed); // return; //} - if (!raw) - { if (!checked_write(f, temp, strlen(temp), buffer)) - { free(pCompressed); + if (!raw) { + if (!checked_write(f, temp, strlen(temp), buffer)) { + free(pCompressed); return AVS_ERROR; } if ((iNkiCompression > 0) && - (GetComponentType() == itk::ImageIOBase::SHORT) && - (GetPixelType() == itk::ImageIOBase::SCALAR)) - { sprintf(temp, "nki_compression=%d", iNkiCompression); - if (!checked_write(f, temp, strlen(temp), buffer)) - { free(pCompressed); + (GetComponentType() == itk::ImageIOBase::SHORT) && + (GetPixelType() == itk::ImageIOBase::SCALAR)) { + sprintf(temp, "nki_compression=%d", iNkiCompression); + if (!checked_write(f, temp, strlen(temp), buffer)) { + free(pCompressed); return AVS_ERROR; } } temp[0] = temp[1] = 12; - if (!checked_write(f, temp, 2, buffer)) - { free(pCompressed); + if (!checked_write(f, temp, 2, buffer)) { + free(pCompressed); return AVS_ERROR; } } @@ -1064,17 +1050,17 @@ ONCE_AGAIN: total *= GetPixelSize(); if ((!raw) && (iNkiCompression > 0) && - (GetComponentType() == itk::ImageIOBase::SHORT) && - (GetPixelType() == itk::ImageIOBase::SCALAR)) - { size_t iCompressedLength; + (GetComponentType() == itk::ImageIOBase::SHORT) && + (GetPixelType() == itk::ImageIOBase::SCALAR)) { + size_t iCompressedLength; iCompressedLength = nki_private_compress(pCompressed, - (short int *)(data), total/2, iNkiCompression); + (short int *)(data), total/2, iNkiCompression); - if (iCompressedLength > 0) - { if (!checked_write(f, pCompressed, iCompressedLength, buffer)) - { free(pCompressed); - return AVS_ERROR; + if (iCompressedLength > 0) { + if (!checked_write(f, pCompressed, iCompressedLength, buffer)) { + free(pCompressed); + return AVS_ERROR; } free(pCompressed); goto WRITE_COORDS; @@ -1091,59 +1077,83 @@ ONCE_AGAIN: /* swap data if required (xdr is low-endian) */ - if (!(*(char *)(&swap_test))) - { if (GetComponentSize()==2) - { c = (char *)data; - for (i=0; i * @date 29 june 2009 - * - * @brief - * + * + * @brief + * ===================================================*/ #include "clitkBinarizeImageGenericFilter.h" diff --git a/filters/clitkBinarizeImageGenericFilter.txx b/filters/clitkBinarizeImageGenericFilter.txx index 26d324c..61a4277 100644 --- a/filters/clitkBinarizeImageGenericFilter.txx +++ b/filters/clitkBinarizeImageGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -29,78 +29,81 @@ namespace clitk { - - //-------------------------------------------------------------------- - template - BinarizeImageGenericFilter::BinarizeImageGenericFilter(): - ImageToImageGenericFilter("Binarize") { - InitializeImageType<2>(); - InitializeImageType<3>(); - InitializeImageType<4>(); - } - //-------------------------------------------------------------------- +//-------------------------------------------------------------------- +template +BinarizeImageGenericFilter::BinarizeImageGenericFilter(): + ImageToImageGenericFilter("Binarize") +{ + InitializeImageType<2>(); + InitializeImageType<3>(); + InitializeImageType<4>(); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +template +void BinarizeImageGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +void BinarizeImageGenericFilter::SetArgsInfo(const args_info_type & a) +{ + mArgsInfo=a; + SetIOVerbose(mArgsInfo.verbose_flag); + if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); - //-------------------------------------------------------------------- - template - template - void BinarizeImageGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); + if (mArgsInfo.input_given) { + SetInputFilename(mArgsInfo.input_arg); } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - template - void BinarizeImageGenericFilter::SetArgsInfo(const args_info_type & a) { - mArgsInfo=a; - SetIOVerbose(mArgsInfo.verbose_flag); - if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); - - if (mArgsInfo.input_given) { - SetInputFilename(mArgsInfo.input_arg); - } - if (mArgsInfo.output_given) { - SetOutputFilename(mArgsInfo.output_arg); - } + if (mArgsInfo.output_given) { + SetOutputFilename(mArgsInfo.output_arg); } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //-------------------------------------------------------------------- - template - template - void - BinarizeImageGenericFilter::UpdateWithInputImageType() - { - - // Reading input - typename InputImageType::Pointer input = this->template GetInput(0); - - // Main filter - typedef typename InputImageType::PixelType PixelType; - typedef itk::Image OutputImageType; - - // Filter - typedef itk::BinaryThresholdImageFilter BinaryThresholdImageFilterType; - typename BinaryThresholdImageFilterType::Pointer thresholdFilter=BinaryThresholdImageFilterType::New(); - thresholdFilter->SetInput(input); - thresholdFilter->SetInsideValue(mArgsInfo.fg_arg); - - if (mArgsInfo.lower_given) thresholdFilter->SetLowerThreshold(static_cast(mArgsInfo.lower_arg)); - if (mArgsInfo.upper_given) thresholdFilter->SetUpperThreshold(static_cast(mArgsInfo.upper_arg)); - - // DD(mArgsInfo.lower_given); - // DD(mArgsInfo.upper_given); - // DD(mArgsInfo.lower_arg); - // DD(mArgsInfo.upper_arg); - // DD(mArgsInfo.fg_arg); - // DD(mArgsInfo.bg_arg); - // DD(mArgsInfo.fg_given); - // DD(mArgsInfo.bg_given); - // DD(mArgsInfo.mode_arg); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//-------------------------------------------------------------------- +template +template +void +BinarizeImageGenericFilter::UpdateWithInputImageType() +{ + + // Reading input + typename InputImageType::Pointer input = this->template GetInput(0); + + // Main filter + typedef typename InputImageType::PixelType PixelType; + typedef itk::Image OutputImageType; + + // Filter + typedef itk::BinaryThresholdImageFilter BinaryThresholdImageFilterType; + typename BinaryThresholdImageFilterType::Pointer thresholdFilter=BinaryThresholdImageFilterType::New(); + thresholdFilter->SetInput(input); + thresholdFilter->SetInsideValue(mArgsInfo.fg_arg); + + if (mArgsInfo.lower_given) thresholdFilter->SetLowerThreshold(static_cast(mArgsInfo.lower_arg)); + if (mArgsInfo.upper_given) thresholdFilter->SetUpperThreshold(static_cast(mArgsInfo.upper_arg)); + + // DD(mArgsInfo.lower_given); + // DD(mArgsInfo.upper_given); + // DD(mArgsInfo.lower_arg); + // DD(mArgsInfo.upper_arg); + // DD(mArgsInfo.fg_arg); + // DD(mArgsInfo.bg_arg); + // DD(mArgsInfo.fg_given); + // DD(mArgsInfo.bg_given); + // DD(mArgsInfo.mode_arg); // DD(mArgsInfo.useFG_flag); // DD(mArgsInfo.useBG_flag); @@ -122,46 +125,44 @@ namespace clitk // // If setFG -> FG BG have been changed // if (mArgsInfo.useBG_flag && mArgsInfo.useFG_flag) { // ======= - /* Three modes : - - FG -> only use FG value for pixel in the Foreground (or Inside), keep input values for outside - - BG -> only use BG value for pixel in the Background (or Outside), keep input values for inside - - both -> use FG and BG (real binary image) - */ - if (mArgsInfo.mode_arg == std::string("both")) { - thresholdFilter->SetOutsideValue(mArgsInfo.bg_arg); - thresholdFilter->Update(); - //>>>>>>> 1.5 - typename OutputImageType::Pointer outputImage = thresholdFilter->GetOutput(); - this->template SetNextOutput(outputImage); - } - else { - typename InputImageType::Pointer outputImage; - thresholdFilter->SetOutsideValue(0); - if (mArgsInfo.mode_arg == std::string("BG")) { - typedef itk::MaskImageFilter maskFilterType; - typename maskFilterType::Pointer maskFilter = maskFilterType::New(); - maskFilter->SetInput1(input); - maskFilter->SetInput2(thresholdFilter->GetOutput()); - maskFilter->SetOutsideValue(mArgsInfo.bg_arg); - maskFilter->Update(); - outputImage = maskFilter->GetOutput(); - } - else { - typedef itk::MaskNegatedImageFilter maskFilterType; - typename maskFilterType::Pointer maskFilter = maskFilterType::New(); - maskFilter->SetInput1(input); - maskFilter->SetInput2(thresholdFilter->GetOutput()); - maskFilter->SetOutsideValue(mArgsInfo.fg_arg); - maskFilter->Update(); - outputImage = maskFilter->GetOutput(); - } - // Write/Save results - this->template SetNextOutput(outputImage); + /* Three modes : + - FG -> only use FG value for pixel in the Foreground (or Inside), keep input values for outside + - BG -> only use BG value for pixel in the Background (or Outside), keep input values for inside + - both -> use FG and BG (real binary image) + */ + if (mArgsInfo.mode_arg == std::string("both")) { + thresholdFilter->SetOutsideValue(mArgsInfo.bg_arg); + thresholdFilter->Update(); + //>>>>>>> 1.5 + typename OutputImageType::Pointer outputImage = thresholdFilter->GetOutput(); + this->template SetNextOutput(outputImage); + } else { + typename InputImageType::Pointer outputImage; + thresholdFilter->SetOutsideValue(0); + if (mArgsInfo.mode_arg == std::string("BG")) { + typedef itk::MaskImageFilter maskFilterType; + typename maskFilterType::Pointer maskFilter = maskFilterType::New(); + maskFilter->SetInput1(input); + maskFilter->SetInput2(thresholdFilter->GetOutput()); + maskFilter->SetOutsideValue(mArgsInfo.bg_arg); + maskFilter->Update(); + outputImage = maskFilter->GetOutput(); + } else { + typedef itk::MaskNegatedImageFilter maskFilterType; + typename maskFilterType::Pointer maskFilter = maskFilterType::New(); + maskFilter->SetInput1(input); + maskFilter->SetInput2(thresholdFilter->GetOutput()); + maskFilter->SetOutsideValue(mArgsInfo.fg_arg); + maskFilter->Update(); + outputImage = maskFilter->GetOutput(); } + // Write/Save results + this->template SetNextOutput(outputImage); } - //-------------------------------------------------------------------- +} +//-------------------------------------------------------------------- }//end clitk - + #endif //#define clitkBinarizeImageGenericFilter_txx diff --git a/filters/clitkFooImageGenericFilter.txx b/filters/clitkFooImageGenericFilter.txx index d0967af..51bc4d5 100644 --- a/filters/clitkFooImageGenericFilter.txx +++ b/filters/clitkFooImageGenericFilter.txx @@ -39,10 +39,11 @@ namespace clitk //-------------------------------------------------------------------- template FooImageGenericFilter::FooImageGenericFilter(): - ImageToImageGenericFilter("FooImage") { - InitializeImageType<2>(); - InitializeImageType<3>(); - InitializeImageType<4>(); + ImageToImageGenericFilter("FooImage") +{ + InitializeImageType<2>(); + InitializeImageType<3>(); + InitializeImageType<4>(); } //-------------------------------------------------------------------- @@ -50,25 +51,27 @@ FooImageGenericFilter::FooImageGenericFilter(): //-------------------------------------------------------------------- template template -void FooImageGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); +void FooImageGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -void FooImageGenericFilter::SetArgsInfo(const args_info_type & a) { - mArgsInfo=a; - SetIOVerbose(mArgsInfo.verbose_flag); - if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); - - if (mArgsInfo.input_given) { - SetInputFilename(mArgsInfo.input_arg); - } - if (mArgsInfo.output_given) { - SetOutputFilename(mArgsInfo.output_arg); - } +void FooImageGenericFilter::SetArgsInfo(const args_info_type & a) +{ + mArgsInfo=a; + SetIOVerbose(mArgsInfo.verbose_flag); + if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); + + if (mArgsInfo.input_given) { + SetInputFilename(mArgsInfo.input_arg); + } + if (mArgsInfo.output_given) { + SetOutputFilename(mArgsInfo.output_arg); + } } //-------------------------------------------------------------------- @@ -81,53 +84,51 @@ void FooImageGenericFilter::UpdateWithInputImageType() { - // Reading input - typename InputImageType::Pointer input = this->template GetInput(0); - - // Main filter - typedef typename InputImageType::PixelType PixelType; - typedef itk::Image OutputImageType; - - // Filter - typedef itk::BinaryThresholdImageFilter BinaryThresholdImageFilterType; - typename BinaryThresholdImageFilterType::Pointer thresholdFilter=BinaryThresholdImageFilterType::New(); - thresholdFilter->SetInput(input); - thresholdFilter->SetInsideValue(mArgsInfo.fg_arg); - - if (mArgsInfo.lower_given) thresholdFilter->SetLowerThreshold(static_cast(mArgsInfo.lower_arg)); - if (mArgsInfo.upper_given) thresholdFilter->SetUpperThreshold(static_cast(mArgsInfo.upper_arg)); - - if (mArgsInfo.mode_arg == std::string("both")) { - thresholdFilter->SetOutsideValue(mArgsInfo.bg_arg); - thresholdFilter->Update(); - - typename OutputImageType::Pointer outputImage = thresholdFilter->GetOutput(); - this->template SetNextOutput(outputImage); - } - else { - typename InputImageType::Pointer outputImage; - thresholdFilter->SetOutsideValue(0); - if (mArgsInfo.mode_arg == std::string("BG")) { - typedef itk::MaskImageFilter maskFilterType; - typename maskFilterType::Pointer maskFilter = maskFilterType::New(); - maskFilter->SetInput1(input); - maskFilter->SetInput2(thresholdFilter->GetOutput()); - maskFilter->SetOutsideValue(mArgsInfo.bg_arg); - maskFilter->Update(); - outputImage = maskFilter->GetOutput(); - } - else { - typedef itk::MaskNegatedImageFilter maskFilterType; - typename maskFilterType::Pointer maskFilter = maskFilterType::New(); - maskFilter->SetInput1(input); - maskFilter->SetInput2(thresholdFilter->GetOutput()); - maskFilter->SetOutsideValue(mArgsInfo.fg_arg); - maskFilter->Update(); - outputImage = maskFilter->GetOutput(); - } - // Write/Save results - this->template SetNextOutput(outputImage); + // Reading input + typename InputImageType::Pointer input = this->template GetInput(0); + + // Main filter + typedef typename InputImageType::PixelType PixelType; + typedef itk::Image OutputImageType; + + // Filter + typedef itk::BinaryThresholdImageFilter BinaryThresholdImageFilterType; + typename BinaryThresholdImageFilterType::Pointer thresholdFilter=BinaryThresholdImageFilterType::New(); + thresholdFilter->SetInput(input); + thresholdFilter->SetInsideValue(mArgsInfo.fg_arg); + + if (mArgsInfo.lower_given) thresholdFilter->SetLowerThreshold(static_cast(mArgsInfo.lower_arg)); + if (mArgsInfo.upper_given) thresholdFilter->SetUpperThreshold(static_cast(mArgsInfo.upper_arg)); + + if (mArgsInfo.mode_arg == std::string("both")) { + thresholdFilter->SetOutsideValue(mArgsInfo.bg_arg); + thresholdFilter->Update(); + + typename OutputImageType::Pointer outputImage = thresholdFilter->GetOutput(); + this->template SetNextOutput(outputImage); + } else { + typename InputImageType::Pointer outputImage; + thresholdFilter->SetOutsideValue(0); + if (mArgsInfo.mode_arg == std::string("BG")) { + typedef itk::MaskImageFilter maskFilterType; + typename maskFilterType::Pointer maskFilter = maskFilterType::New(); + maskFilter->SetInput1(input); + maskFilter->SetInput2(thresholdFilter->GetOutput()); + maskFilter->SetOutsideValue(mArgsInfo.bg_arg); + maskFilter->Update(); + outputImage = maskFilter->GetOutput(); + } else { + typedef itk::MaskNegatedImageFilter maskFilterType; + typename maskFilterType::Pointer maskFilter = maskFilterType::New(); + maskFilter->SetInput1(input); + maskFilter->SetInput2(thresholdFilter->GetOutput()); + maskFilter->SetOutsideValue(mArgsInfo.fg_arg); + maskFilter->Update(); + outputImage = maskFilter->GetOutput(); } + // Write/Save results + this->template SetNextOutput(outputImage); + } } //-------------------------------------------------------------------- diff --git a/filters/clitkGuerreroVentilationGenericFilter.cxx b/filters/clitkGuerreroVentilationGenericFilter.cxx index 04c1e93..ad3b6d9 100644 --- a/filters/clitkGuerreroVentilationGenericFilter.cxx +++ b/filters/clitkGuerreroVentilationGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -21,7 +21,7 @@ * @author Joël Schaerer * @date 20 April 2009 - * @brief + * @brief -------------------------------------------------------------------*/ #include "clitkGuerreroVentilationGenericFilter.h" @@ -30,8 +30,9 @@ #include //-------------------------------------------------------------------- -clitk::GuerreroVentilationGenericFilter::GuerreroVentilationGenericFilter() - :ImageToImageGenericFilter("GuerreroVentilationGenericFilter") { +clitk::GuerreroVentilationGenericFilter::GuerreroVentilationGenericFilter() + :ImageToImageGenericFilter("GuerreroVentilationGenericFilter") +{ blood_mass_factor=1.; InitializeImageType<2>(); InitializeImageType<3>(); @@ -40,7 +41,8 @@ clitk::GuerreroVentilationGenericFilter::GuerreroVentilationGenericFilter() //-------------------------------------------------------------------- template -void clitk::GuerreroVentilationGenericFilter::InitializeImageType() { +void clitk::GuerreroVentilationGenericFilter::InitializeImageType() +{ ADD_IMAGE_TYPE(Dim, short); } //-------------------------------------------------------------------- @@ -48,30 +50,31 @@ void clitk::GuerreroVentilationGenericFilter::InitializeImageType() { //-------------------------------------------------------------------- template -void clitk::GuerreroVentilationGenericFilter::UpdateWithInputImageType() { +void clitk::GuerreroVentilationGenericFilter::UpdateWithInputImageType() +{ - // Input should be 2 - assert(mInputFilenames.size() == 2); + // Input should be 2 + assert(mInputFilenames.size() == 2); - // Reading input - typedef ImageType InputImageType; - typename InputImageType::Pointer input = this->template GetInput(0); - typename InputImageType::Pointer ref = this->template GetInput(1); + // Reading input + typedef ImageType InputImageType; + typename InputImageType::Pointer input = this->template GetInput(0); + typename InputImageType::Pointer ref = this->template GetInput(1); - typedef itk::Image OutputImageType; - // typename ImageType::Pointer input = clitk::readImage(mInputFilenames[0], mIOVerbose); - //typename ImageType::Pointer ref = clitk::readImage(mInputFilenames[1], mIOVerbose); + typedef itk::Image OutputImageType; + // typename ImageType::Pointer input = clitk::readImage(mInputFilenames[0], mIOVerbose); + //typename ImageType::Pointer ref = clitk::readImage(mInputFilenames[1], mIOVerbose); - typedef itk::BinaryGuerreroFilter GFilterType; - typename GFilterType::Pointer filter = GFilterType::New(); - filter->SetInput1(ref); - filter->SetInput2(input); - filter->SetBloodCorrectionFactor(blood_mass_factor); - filter->SetUseCorrectFormula(use_correct_formula); - filter->Update(); + typedef itk::BinaryGuerreroFilter GFilterType; + typename GFilterType::Pointer filter = GFilterType::New(); + filter->SetInput1(ref); + filter->SetInput2(input); + filter->SetBloodCorrectionFactor(blood_mass_factor); + filter->SetUseCorrectFormula(use_correct_formula); + filter->Update(); - this->SetNextOutput(filter->GetOutput()); - //clitk::writeImage(filter->GetOutput(), mOutputFilename, mIOVerbose); - //std::cout << "Warning: removed " << filter->GetFunctor().aberant_voxels << " aberant voxels from the ventilation image" - //<< std::endl; + this->SetNextOutput(filter->GetOutput()); + //clitk::writeImage(filter->GetOutput(), mOutputFilename, mIOVerbose); + //std::cout << "Warning: removed " << filter->GetFunctor().aberant_voxels << " aberant voxels from the ventilation image" + //<< std::endl; } diff --git a/filters/clitkImageArithmGenericFilter.cxx b/filters/clitkImageArithmGenericFilter.cxx index 59f0bc0..104b5d3 100644 --- a/filters/clitkImageArithmGenericFilter.cxx +++ b/filters/clitkImageArithmGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,7 +23,7 @@ * @author David Sarrut * @date 23 Feb 2008 - * @brief + * @brief -------------------------------------------------------------------*/ #include "clitkImageArithmGenericFilter.h" diff --git a/filters/clitkImageArithmGenericFilter.txx b/filters/clitkImageArithmGenericFilter.txx index 9679d02..99f7f32 100644 --- a/filters/clitkImageArithmGenericFilter.txx +++ b/filters/clitkImageArithmGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -19,313 +19,347 @@ #define CLITKIMAGEARITHMGENERICFILTER_TXX namespace clitk { - - //-------------------------------------------------------------------- - template - ImageArithmGenericFilter::ImageArithmGenericFilter() - :ImageToImageGenericFilter("ImageArithmGenericFilter"),mTypeOfOperation(0) { - InitializeImageType<2>(); - InitializeImageType<3>(); - InitializeImageType<4>(); - mIsOperationUseASecondImage = false; - mOverwriteInputImage = true; - } - //-------------------------------------------------------------------- +//-------------------------------------------------------------------- +template +ImageArithmGenericFilter::ImageArithmGenericFilter() + :ImageToImageGenericFilter("ImageArithmGenericFilter"),mTypeOfOperation(0) +{ + InitializeImageType<2>(); + InitializeImageType<3>(); + InitializeImageType<4>(); + mIsOperationUseASecondImage = false; + mOverwriteInputImage = true; +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - template - void ImageArithmGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); - } - //-------------------------------------------------------------------- +//-------------------------------------------------------------------- +template +template +void ImageArithmGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - void ImageArithmGenericFilter::EnableOverwriteInputImage(bool b) { - mOverwriteInputImage = b; - } - //-------------------------------------------------------------------- + +//-------------------------------------------------------------------- +template +void ImageArithmGenericFilter::EnableOverwriteInputImage(bool b) +{ + mOverwriteInputImage = b; +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - void ImageArithmGenericFilter::SetArgsInfo(const args_info_type & a) { - mArgsInfo=a; +//-------------------------------------------------------------------- +template +void ImageArithmGenericFilter::SetArgsInfo(const args_info_type & a) +{ + mArgsInfo=a; - // Set value - SetIOVerbose(mArgsInfo.verbose_flag); - mTypeOfOperation = mArgsInfo.operation_arg; - mDefaultPixelValue = mArgsInfo.pixelValue_arg; - mScalar = mArgsInfo.scalar_arg; - mOutputIsFloat = mArgsInfo.setFloatOutput_flag; + // Set value + SetIOVerbose(mArgsInfo.verbose_flag); + mTypeOfOperation = mArgsInfo.operation_arg; + mDefaultPixelValue = mArgsInfo.pixelValue_arg; + mScalar = mArgsInfo.scalar_arg; + mOutputIsFloat = mArgsInfo.setFloatOutput_flag; - if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); + if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); - if (mArgsInfo.input1_given) AddInputFilename(mArgsInfo.input1_arg); - if (mArgsInfo.input2_given) { - mIsOperationUseASecondImage = true; - AddInputFilename(mArgsInfo.input2_arg); - } - - if (mArgsInfo.output_given) SetOutputFilename(mArgsInfo.output_arg); + if (mArgsInfo.input1_given) AddInputFilename(mArgsInfo.input1_arg); + if (mArgsInfo.input2_given) { + mIsOperationUseASecondImage = true; + AddInputFilename(mArgsInfo.input2_arg); + } + + if (mArgsInfo.output_given) SetOutputFilename(mArgsInfo.output_arg); - // Check type of operation (with scalar or with other image) - if ((mArgsInfo.input2_given) && (mArgsInfo.scalar_given)) { - std::cerr << "ERROR : you cannot provide both --scalar and --input2 option" << std::endl; + // Check type of operation (with scalar or with other image) + if ((mArgsInfo.input2_given) && (mArgsInfo.scalar_given)) { + std::cerr << "ERROR : you cannot provide both --scalar and --input2 option" << std::endl; + exit(-1); + } + if ((!mArgsInfo.input2_given) && (!mArgsInfo.scalar_given)) { + if (mArgsInfo.operation_arg < 5) { + std::cerr << "Such operation need the --scalar option." << std::endl; exit(-1); } - if ((!mArgsInfo.input2_given) && (!mArgsInfo.scalar_given)) { - if (mArgsInfo.operation_arg < 5) { - std::cerr << "Such operation need the --scalar option." << std::endl; - exit(-1); - } - } } - //-------------------------------------------------------------------- +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - template - void ImageArithmGenericFilter::UpdateWithInputImageType() { - // Read input1 - typename ImageType::Pointer input1 = this->template GetInput(0); +//-------------------------------------------------------------------- +template +template +void ImageArithmGenericFilter::UpdateWithInputImageType() +{ + // Read input1 + typename ImageType::Pointer input1 = this->template GetInput(0); - // Set input image iterator - typedef itk::ImageRegionIterator IteratorType; - IteratorType it(input1, input1->GetLargestPossibleRegion()); + // Set input image iterator + typedef itk::ImageRegionIterator IteratorType; + IteratorType it(input1, input1->GetLargestPossibleRegion()); - // typedef input2 - typename ImageType::Pointer input2 = this->template GetInput(1); - IteratorType it2; + // typedef input2 + typename ImageType::Pointer input2 = this->template GetInput(1); + IteratorType it2; - if (mIsOperationUseASecondImage) { - // Read input2 - input2 = this->template GetInput(1); - // Set input image iterator - it2 = IteratorType(input2, input2->GetLargestPossibleRegion()); - } + if (mIsOperationUseASecondImage) { + // Read input2 + input2 = this->template GetInput(1); + // Set input image iterator + it2 = IteratorType(input2, input2->GetLargestPossibleRegion()); + } - // Check if overwrite and outputisfloat and pixeltype is not float -> do not overwrite - if (mOverwriteInputImage && mOutputIsFloat && (typeid(typename ImageType::PixelType) != typeid(float))) { - // std::cerr << "Warning. Could not use both mOverwriteInputImage and mOutputIsFloat, because input is " - // << typeid(PixelType).name() - // << std::endl; - mOverwriteInputImage = false; - } + // Check if overwrite and outputisfloat and pixeltype is not float -> do not overwrite + if (mOverwriteInputImage && mOutputIsFloat && (typeid(typename ImageType::PixelType) != typeid(float))) { + // std::cerr << "Warning. Could not use both mOverwriteInputImage and mOutputIsFloat, because input is " + // << typeid(PixelType).name() + // << std::endl; + mOverwriteInputImage = false; + } + + // ---------------- Overwrite input Image --------------------- + if (mOverwriteInputImage) { + // Set output iterator (to input1) + IteratorType ito = IteratorType(input1, input1->GetLargestPossibleRegion()); + if (mIsOperationUseASecondImage) ComputeImage(it, it2, ito); + else ComputeImage(it, ito); + this->template SetNextOutput(input1); + } - // ---------------- Overwrite input Image --------------------- - if (mOverwriteInputImage) { - // Set output iterator (to input1) - IteratorType ito = IteratorType(input1, input1->GetLargestPossibleRegion()); + // ---------------- Create new output Image --------------------- + else { + if (mOutputIsFloat) { + // Create output image + typedef itk::Image OutputImageType; + typename OutputImageType::Pointer output = OutputImageType::New(); + output->SetRegions(input1->GetLargestPossibleRegion()); + output->SetOrigin(input1->GetOrigin()); + output->SetSpacing(input1->GetSpacing()); + output->Allocate(); + // Set output iterator + typedef itk::ImageRegionIterator IteratorOutputType; + IteratorOutputType ito = IteratorOutputType(output, output->GetLargestPossibleRegion()); if (mIsOperationUseASecondImage) ComputeImage(it, it2, ito); else ComputeImage(it, ito); - this->template SetNextOutput(input1); - } - - // ---------------- Create new output Image --------------------- - else { - if (mOutputIsFloat) { - // Create output image - typedef itk::Image OutputImageType; - typename OutputImageType::Pointer output = OutputImageType::New(); - output->SetRegions(input1->GetLargestPossibleRegion()); - output->SetOrigin(input1->GetOrigin()); - output->SetSpacing(input1->GetSpacing()); - output->Allocate(); - // Set output iterator - typedef itk::ImageRegionIterator IteratorOutputType; - IteratorOutputType ito = IteratorOutputType(output, output->GetLargestPossibleRegion()); - if (mIsOperationUseASecondImage) ComputeImage(it, it2, ito); - else ComputeImage(it, ito); - this->template SetNextOutput(output); - } - else { - // Create output image - typedef ImageType OutputImageType; - typename OutputImageType::Pointer output = OutputImageType::New(); - output->SetRegions(input1->GetLargestPossibleRegion()); - output->SetOrigin(input1->GetOrigin()); - output->SetSpacing(input1->GetSpacing()); - output->Allocate(); - // Set output iterator - typedef itk::ImageRegionIterator IteratorOutputType; - IteratorOutputType ito = IteratorOutputType(output, output->GetLargestPossibleRegion()); - if (mIsOperationUseASecondImage) ComputeImage(it, it2, ito); - else ComputeImage(it, ito); - this->template SetNextOutput(output); - } + this->template SetNextOutput(output); + } else { + // Create output image + typedef ImageType OutputImageType; + typename OutputImageType::Pointer output = OutputImageType::New(); + output->SetRegions(input1->GetLargestPossibleRegion()); + output->SetOrigin(input1->GetOrigin()); + output->SetSpacing(input1->GetSpacing()); + output->Allocate(); + // Set output iterator + typedef itk::ImageRegionIterator IteratorOutputType; + IteratorOutputType ito = IteratorOutputType(output, output->GetLargestPossibleRegion()); + if (mIsOperationUseASecondImage) ComputeImage(it, it2, ito); + else ComputeImage(it, ito); + this->template SetNextOutput(output); } } - //-------------------------------------------------------------------- +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - template - void ImageArithmGenericFilter::ComputeImage(Iter1 it1, Iter2 it2, Iter3 ito) { - it1.GoToBegin(); - it2.GoToBegin(); - ito.GoToBegin(); - typedef typename Iter3::PixelType PixelType; - - switch (mTypeOfOperation) { - case 0: // Addition - while (!ito.IsAtEnd()) { - ito.Set(PixelTypeDownCast((double)it1.Get() + (double)it2.Get()) ); - ++it1; ++it2; ++ito; - } - break; - case 1: // Multiply - while (!ito.IsAtEnd()) { - ito.Set(PixelTypeDownCast((double)it1.Get() * (double)it2.Get()) ); - ++it1; ++it2; ++ito; - } - break; - case 2: // Divide - while (!ito.IsAtEnd()) { - if (it1.Get() != 0) - ito.Set(PixelTypeDownCast((double)it1.Get() / (double)it2.Get())); - else ito.Set(mDefaultPixelValue); - ++it1; ++it2; ++ito; - } - break; - case 3: // Max - while (!ito.IsAtEnd()) { - if (it1.Get() < it2.Get()) ito.Set(PixelTypeDownCast(it2.Get())); - ++it1; ++it2; ++ito; - } - break; - case 4: // Min - while (!ito.IsAtEnd()) { - if (it1.Get() > it2.Get()) ito.Set(PixelTypeDownCast(it2.Get())); - ++it1; ++it2; ++ito; - } - break; - case 5: // Absolute difference - while (!ito.IsAtEnd()) { - ito.Set(PixelTypeDownCast(fabs((double)it2.Get()-(double)it1.Get()))); - ++it1; ++it2; ++ito; - } - break; - case 6: // Squared differences - while (!ito.IsAtEnd()) { - ito.Set(PixelTypeDownCast(pow((double)it1.Get()-(double)it2.Get(),2))); - ++it1; ++it2; ++ito; - } - break; - case 7: // Difference - while (!ito.IsAtEnd()) { - ito.Set(PixelTypeDownCast((double)it1.Get()-(double)it2.Get())); - ++it1; ++it2; ++ito; - } - break; - case 8: // Relative Difference - while (!ito.IsAtEnd()) { - if (it1.Get() != 0) ito.Set(PixelTypeDownCast(((double)it1.Get()-(double)it2.Get()))/(double)it1.Get()); - else ito.Set(0.0); - ++it1; ++it2; ++ito; - } - break; - default: // error ? - std::cerr << "ERROR : the operation number (" << mTypeOfOperation << ") is not known." << std::endl; - exit(-1); +//-------------------------------------------------------------------- +template +template +void ImageArithmGenericFilter::ComputeImage(Iter1 it1, Iter2 it2, Iter3 ito) +{ + it1.GoToBegin(); + it2.GoToBegin(); + ito.GoToBegin(); + typedef typename Iter3::PixelType PixelType; + + switch (mTypeOfOperation) { + case 0: // Addition + while (!ito.IsAtEnd()) { + ito.Set(PixelTypeDownCast((double)it1.Get() + (double)it2.Get()) ); + ++it1; + ++it2; + ++ito; + } + break; + case 1: // Multiply + while (!ito.IsAtEnd()) { + ito.Set(PixelTypeDownCast((double)it1.Get() * (double)it2.Get()) ); + ++it1; + ++it2; + ++ito; + } + break; + case 2: // Divide + while (!ito.IsAtEnd()) { + if (it1.Get() != 0) + ito.Set(PixelTypeDownCast((double)it1.Get() / (double)it2.Get())); + else ito.Set(mDefaultPixelValue); + ++it1; + ++it2; + ++ito; + } + break; + case 3: // Max + while (!ito.IsAtEnd()) { + if (it1.Get() < it2.Get()) ito.Set(PixelTypeDownCast(it2.Get())); + ++it1; + ++it2; + ++ito; } + break; + case 4: // Min + while (!ito.IsAtEnd()) { + if (it1.Get() > it2.Get()) ito.Set(PixelTypeDownCast(it2.Get())); + ++it1; + ++it2; + ++ito; + } + break; + case 5: // Absolute difference + while (!ito.IsAtEnd()) { + ito.Set(PixelTypeDownCast(fabs((double)it2.Get()-(double)it1.Get()))); + ++it1; + ++it2; + ++ito; + } + break; + case 6: // Squared differences + while (!ito.IsAtEnd()) { + ito.Set(PixelTypeDownCast(pow((double)it1.Get()-(double)it2.Get(),2))); + ++it1; + ++it2; + ++ito; + } + break; + case 7: // Difference + while (!ito.IsAtEnd()) { + ito.Set(PixelTypeDownCast((double)it1.Get()-(double)it2.Get())); + ++it1; + ++it2; + ++ito; + } + break; + case 8: // Relative Difference + while (!ito.IsAtEnd()) { + if (it1.Get() != 0) ito.Set(PixelTypeDownCast(((double)it1.Get()-(double)it2.Get()))/(double)it1.Get()); + else ito.Set(0.0); + ++it1; + ++it2; + ++ito; + } + break; + default: // error ? + std::cerr << "ERROR : the operation number (" << mTypeOfOperation << ") is not known." << std::endl; + exit(-1); } - //-------------------------------------------------------------------- +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - template - void clitk::ImageArithmGenericFilter::ComputeImage(Iter1 it, Iter2 ito) { - ito.GoToBegin(); - it.GoToBegin(); - typedef typename Iter2::PixelType PixelType; +//-------------------------------------------------------------------- +template +template +void clitk::ImageArithmGenericFilter::ComputeImage(Iter1 it, Iter2 ito) +{ + ito.GoToBegin(); + it.GoToBegin(); + typedef typename Iter2::PixelType PixelType; - // Perform operation - switch (mTypeOfOperation) { - case 0: // Addition - while (!it.IsAtEnd()) { - ito.Set(clitk::PixelTypeDownCast((double)it.Get() + mScalar) ); - ++it; ++ito; - } - break; - case 1: // Multiply - while (!it.IsAtEnd()) { - ito.Set(PixelTypeDownCast((double)it.Get() * mScalar) ); - ++it; ++ito; - } - break; - case 2: // Inverse - while (!it.IsAtEnd()) { - if (it.Get() != 0) - ito.Set(PixelTypeDownCast(mScalar / (double)it.Get())); - else ito.Set(mDefaultPixelValue); - ++it; ++ito; - } - break; - case 3: // Max - while (!it.IsAtEnd()) { - if (it.Get() < mScalar) ito.Set(PixelTypeDownCast(mScalar)); - else ito.Set(PixelTypeDownCast(it.Get())); - ++it; ++ito; - } - break; - case 4: // Min - while (!it.IsAtEnd()) { - if (it.Get() > mScalar) ito.Set(PixelTypeDownCast(mScalar)); - else ito.Set(PixelTypeDownCast(it.Get())); - ++it; ++ito; - } - break; - case 5: // Absolute value - while (!it.IsAtEnd()) { - if (it.Get() <= 0) ito.Set(PixelTypeDownCast(-it.Get())); - // <= zero to avoid warning for unsigned types - else ito.Set(PixelTypeDownCast(it.Get())); - ++it; ++ito; - } - break; - case 6: // Squared value - while (!it.IsAtEnd()) { - ito.Set(PixelTypeDownCast((double)it.Get()*(double)it.Get())); - ++it; ++ito; - } - break; - case 7: // Log - while (!it.IsAtEnd()) { - if (it.Get() > 0) - ito.Set(PixelTypeDownCast(log((double)it.Get()))); + // Perform operation + switch (mTypeOfOperation) { + case 0: // Addition + while (!it.IsAtEnd()) { + ito.Set(clitk::PixelTypeDownCast((double)it.Get() + mScalar) ); + ++it; + ++ito; + } + break; + case 1: // Multiply + while (!it.IsAtEnd()) { + ito.Set(PixelTypeDownCast((double)it.Get() * mScalar) ); + ++it; + ++ito; + } + break; + case 2: // Inverse + while (!it.IsAtEnd()) { + if (it.Get() != 0) + ito.Set(PixelTypeDownCast(mScalar / (double)it.Get())); + else ito.Set(mDefaultPixelValue); + ++it; + ++ito; + } + break; + case 3: // Max + while (!it.IsAtEnd()) { + if (it.Get() < mScalar) ito.Set(PixelTypeDownCast(mScalar)); + else ito.Set(PixelTypeDownCast(it.Get())); + ++it; + ++ito; + } + break; + case 4: // Min + while (!it.IsAtEnd()) { + if (it.Get() > mScalar) ito.Set(PixelTypeDownCast(mScalar)); + else ito.Set(PixelTypeDownCast(it.Get())); + ++it; + ++ito; + } + break; + case 5: // Absolute value + while (!it.IsAtEnd()) { + if (it.Get() <= 0) ito.Set(PixelTypeDownCast(-it.Get())); + // <= zero to avoid warning for unsigned types + else ito.Set(PixelTypeDownCast(it.Get())); + ++it; + ++ito; + } + break; + case 6: // Squared value + while (!it.IsAtEnd()) { + ito.Set(PixelTypeDownCast((double)it.Get()*(double)it.Get())); + ++it; + ++ito; + } + break; + case 7: // Log + while (!it.IsAtEnd()) { + if (it.Get() > 0) + ito.Set(PixelTypeDownCast(log((double)it.Get()))); + else ito.Set(mDefaultPixelValue); + ++it; + ++ito; + } + break; + case 8: // exp + while (!it.IsAtEnd()) { + ito.Set(PixelTypeDownCast(exp((double)it.Get()))); + ++it; + ++ito; + } + break; + case 9: // sqrt + while (!it.IsAtEnd()) { + if (it.Get() > 0) + ito.Set(PixelTypeDownCast(sqrt((double)it.Get()))); + else { + if (it.Get() ==0) ito.Set(0); else ito.Set(mDefaultPixelValue); - ++it; ++ito; - } - break; - case 8: // exp - while (!it.IsAtEnd()) { - ito.Set(PixelTypeDownCast(exp((double)it.Get()))); - ++it; ++ito; } - break; - case 9: // sqrt - while (!it.IsAtEnd()) { - if (it.Get() > 0) - ito.Set(PixelTypeDownCast(sqrt((double)it.Get()))); - else { - if (it.Get() ==0) ito.Set(0); - else ito.Set(mDefaultPixelValue); - } - ++it; ++ito; - } - break; - default: // error ? - std::cerr << "ERROR : the operation number (" << mTypeOfOperation << ") is not known." << std::endl; - exit(-1); + ++it; + ++ito; } + break; + default: // error ? + std::cerr << "ERROR : the operation number (" << mTypeOfOperation << ") is not known." << std::endl; + exit(-1); } - //-------------------------------------------------------------------- +} +//-------------------------------------------------------------------- } // end namespace diff --git a/filters/clitkImageConvertGenericFilter.cxx b/filters/clitkImageConvertGenericFilter.cxx index c6afba8..944ec8c 100644 --- a/filters/clitkImageConvertGenericFilter.cxx +++ b/filters/clitkImageConvertGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,29 +22,32 @@ //-------------------------------------------------------------------- clitk::ImageConvertGenericFilter::ImageConvertGenericFilter(): - clitk::ImageToImageGenericFilter("ImageConvert") { + clitk::ImageToImageGenericFilter("ImageConvert") +{ mOutputPixelTypeName = "NotSpecified"; mWarningOccur = false; mWarning = ""; mDisplayWarning = true; InitializeImageType<2>(); - InitializeImageType<3>(); - InitializeImageType<4>(); + InitializeImageType<3>(); + InitializeImageType<4>(); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -void clitk::ImageConvertGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); +void clitk::ImageConvertGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -void clitk::ImageConvertGenericFilter::UpdateWithInputImageType() { +void clitk::ImageConvertGenericFilter::UpdateWithInputImageType() +{ // Verbose stuff if (mIOVerbose) { @@ -53,13 +56,12 @@ void clitk::ImageConvertGenericFilter::UpdateWithInputImageType() { itk::ImageIOBase::Pointer header = clitk::readImageHeader(mInputFilenames[0]); printImageHeader(header, std::cout); std::cout << std::endl; - } - else { + } else { for(unsigned int i=0; i is "; - itk::ImageIOBase::Pointer h = clitk::readImageHeader(mInputFilenames[i]); - printImageHeader(h, std::cout); - std::cout << std::endl; + std::cout << "Input image " << i << " <" << mInputFilenames[i] << "> is "; + itk::ImageIOBase::Pointer h = clitk::readImageHeader(mInputFilenames[i]); + printImageHeader(h, std::cout); + std::cout << std::endl; } } } @@ -70,8 +72,7 @@ void clitk::ImageConvertGenericFilter::UpdateWithInputImageType() { typename InputImageType::Pointer input = this->template GetInput(0); //clitk::writeImage(input, mOutputFilename, mIOVerbose); this->SetNextOutput(input); - } - else { + } else { #define TRY_TYPE(TYPE) \ if (IsSameType(mOutputPixelTypeName)) { UpdateWithOutputType(); return; } TRY_TYPE(char); @@ -85,16 +86,17 @@ void clitk::ImageConvertGenericFilter::UpdateWithInputImageType() { #undef TRY_TYPE std::string list = CreateListOfTypes(); - std::cerr << "Error, I don't know the output type '" << mOutputPixelTypeName - << "'. " << std::endl << "Known types are " << list << "." << std::endl; + std::cerr << "Error, I don't know the output type '" << mOutputPixelTypeName + << "'. " << std::endl << "Known types are " << list << "." << std::endl; exit(0); - } + } } //==================================================================== //==================================================================== template -void clitk::ImageConvertGenericFilter::UpdateWithOutputType() { +void clitk::ImageConvertGenericFilter::UpdateWithOutputType() +{ // Read typename InputImageType::Pointer input =this->template GetInput(0); @@ -105,15 +107,15 @@ void clitk::ImageConvertGenericFilter::UpdateWithOutputType() { std::ostringstream osstream; if (std::numeric_limits::is_signed) { if (!std::numeric_limits::is_signed) { - osstream << "Warning, input type is signed (" << mPixelTypeName << ") while output type is not (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; - mWarningOccur = true; + osstream << "Warning, input type is signed (" << mPixelTypeName << ") while output type is not (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + mWarningOccur = true; } } if (!std::numeric_limits::is_integer) { if (std::numeric_limits::is_integer) { - osstream << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + osstream << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; mWarningOccur = true; } } @@ -121,14 +123,14 @@ void clitk::ImageConvertGenericFilter::UpdateWithOutputType() { // DD(std::numeric_limits::digits10); if (!std::numeric_limits::is_integer) { if (std::numeric_limits::is_integer) { - osstream << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + osstream << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; mWarningOccur = true; } } if (std::numeric_limits::digits10 > std::numeric_limits::digits10) { - osstream << "Warning, possible loss of precision : input type is (" << mPixelTypeName << ") while output type is (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + osstream << "Warning, possible loss of precision : input type is (" << mPixelTypeName << ") while output type is (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; mWarningOccur = true; } diff --git a/filters/clitkImageConvertGenericFilter.txx b/filters/clitkImageConvertGenericFilter.txx index 8f2ed03..1d055e1 100644 --- a/filters/clitkImageConvertGenericFilter.txx +++ b/filters/clitkImageConvertGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,47 +22,48 @@ * @file clitkImageConvertGenericFilter.txx * @author David Sarrut * @date 05 May 2008 11:14:20 - * - * @brief - * - * + * + * @brief + * + * =================================================*/ #include //==================================================================== template -void ImageConvertGenericFilter::Update_WithDim() { +void ImageConvertGenericFilter::Update_WithDim() +{ #define TRY_TYPE(TYPE) \ - if (IsSameType(mPixelTypeName)) { Update_WithDimAndPixelType(); return; } + if (IsSameType(mPixelTypeName)) { Update_WithDimAndPixelType(); return; } // TRY_TYPE(signed char); TRY_TYPE(char); TRY_TYPE(uchar); TRY_TYPE(short); TRY_TYPE(ushort); - TRY_TYPE(int); - TRY_TYPE(unsigned int); + TRY_TYPE(int); + TRY_TYPE(unsigned int); TRY_TYPE(float); TRY_TYPE(double); #undef TRY_TYPE std::string list = CreateListOfTypes(); std::cerr << "Error, I don't know the type '" << mPixelTypeName << "' for the input image '" - << mInputFilenames[0] << "'." << std::endl << "Known types are " << list << std::endl; + << mInputFilenames[0] << "'." << std::endl << "Known types are " << list << std::endl; exit(0); } //==================================================================== //==================================================================== template -void ImageConvertGenericFilter::Update_WithDimAndPixelType() { +void ImageConvertGenericFilter::Update_WithDimAndPixelType() +{ if ((mPixelTypeName == mOutputPixelTypeName) || (mOutputPixelTypeName == "NotSpecified")) { typedef itk::Image InputImageType; typename InputImageType::Pointer input = clitk::readImage(mInputFilenames); //clitk::writeImage(input, mOutputFilename, mIOVerbose); this->SetNextOutput(input); - } - else { + } else { #define TRY_TYPE(TYPE) \ if (IsSameType(mOutputPixelTypeName)) { Update_WithDimAndPixelTypeAndOutputType(); return; } TRY_TYPE(char); @@ -76,16 +77,17 @@ void ImageConvertGenericFilter::Update_WithDimAndPixelType() { #undef TRY_TYPE std::string list = CreateListOfTypes(); - std::cerr << "Error, I don't know the output type '" << mOutputPixelTypeName - << "'. " << std::endl << "Known types are " << list << "." << std::endl; + std::cerr << "Error, I don't know the output type '" << mOutputPixelTypeName + << "'. " << std::endl << "Known types are " << list << "." << std::endl; exit(0); - } + } } //==================================================================== //==================================================================== template -void ImageConvertGenericFilter::Update_WithDimAndPixelTypeAndOutputType() { +void ImageConvertGenericFilter::Update_WithDimAndPixelTypeAndOutputType() +{ // Read typedef itk::Image InputImageType; typename InputImageType::Pointer input = clitk::readImage(mInputFilenames); @@ -93,27 +95,27 @@ void ImageConvertGenericFilter::Update_WithDimAndPixelTypeAndOutputType() { // Warning if (std::numeric_limits::is_signed) { if (!std::numeric_limits::is_signed) { - std::cerr << "Warning, input type is signed (" << mPixelTypeName << ") while output type is not (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + std::cerr << "Warning, input type is signed (" << mPixelTypeName << ") while output type is not (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; } } if (!std::numeric_limits::is_integer) { if (std::numeric_limits::is_integer) { - std::cerr << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + std::cerr << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; } } // DD(std::numeric_limits::digits10); // DD(std::numeric_limits::digits10); if (!std::numeric_limits::is_integer) { if (std::numeric_limits::is_integer) { - std::cerr << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + std::cerr << "Warning, input type is not integer (" << mPixelTypeName << ") while output type is (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; } } if (std::numeric_limits::digits10 > std::numeric_limits::digits10) { - std::cerr << "Warning, possible loss of precision : input type is (" << mPixelTypeName << ") while output type is (" - << mOutputPixelTypeName << "), use at your own responsability." << std::endl; + std::cerr << "Warning, possible loss of precision : input type is (" << mPixelTypeName << ") while output type is (" + << mOutputPixelTypeName << "), use at your own responsability." << std::endl; } // Cast diff --git a/filters/clitkImageFillRegionGenericFilter.cxx b/filters/clitkImageFillRegionGenericFilter.cxx index 167c043..dd5a51a 100644 --- a/filters/clitkImageFillRegionGenericFilter.cxx +++ b/filters/clitkImageFillRegionGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,26 +23,28 @@ * @author David Sarrut * @date 23 Feb 2008 - * @brief + * @brief -------------------------------------------------------------------*/ #include "clitkImageFillRegionGenericFilter.h" //-------------------------------------------------------------------- clitk::ImageFillRegionGenericFilter::ImageFillRegionGenericFilter(): - clitk::ImageToImageGenericFilter("ImageFillRegion") { + clitk::ImageToImageGenericFilter("ImageFillRegion") +{ InitializeImageType<2>(); - InitializeImageType<3>(); + InitializeImageType<3>(); mPixelValue = 0; m_IsCentered=false; - mSphericRegion=false; + mSphericRegion=false; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -void clitk::ImageFillRegionGenericFilter::InitializeImageType() { +void clitk::ImageFillRegionGenericFilter::InitializeImageType() +{ // ADD_IMAGE_TYPE(Dim, char); ADD_IMAGE_TYPE(Dim, short); // ADD_IMAGE_TYPE(Dim, unsigned short); @@ -56,7 +58,8 @@ void clitk::ImageFillRegionGenericFilter::InitializeImageType() { //-------------------------------------------------------------------- template -void clitk::ImageFillRegionGenericFilter::UpdateWithInputImageType() { +void clitk::ImageFillRegionGenericFilter::UpdateWithInputImageType() +{ // Typedef typedef typename ImageType::PixelType PixelType; @@ -69,7 +72,7 @@ void clitk::ImageFillRegionGenericFilter::UpdateWithInputImageType() { typename ImageType::Pointer input = GetInput(0); // Get pixel value in correct type - PixelType value = PixelTypeDownCast(mPixelValue); + PixelType value = PixelTypeDownCast(mPixelValue); // Get region typedef typename ImageType::RegionType RegionType; @@ -101,7 +104,8 @@ void clitk::ImageFillRegionGenericFilter::UpdateWithInputImageType() { //-------------------------------------------------------------------- template -void clitk::ImageFillRegionGenericFilter::Update_WithDimAndPixelType_SphericRegion() { +void clitk::ImageFillRegionGenericFilter::Update_WithDimAndPixelType_SphericRegion() +{ // Read input typedef itk::Image ImageType; @@ -109,48 +113,46 @@ void clitk::ImageFillRegionGenericFilter::Update_WithDimAndPixelType_SphericRegi typename ImageType::Pointer input = GetInput(0); // Get pixel value in correct type - PixelType value = PixelTypeDownCast(mPixelValue); + PixelType value = PixelTypeDownCast(mPixelValue); // Centered? - if(m_IsCentered) - { - typename ImageType::SizeType size= input->GetLargestPossibleRegion().GetSize(); - typename ImageType::SpacingType spacing= input->GetSpacing(); - typename ImageType::PointType origin= input->GetOrigin(); - mCenter.resize(Dim); - for (unsigned int i=0; iGetLargestPossibleRegion().GetSize(); + typename ImageType::SpacingType spacing= input->GetSpacing(); + typename ImageType::PointType origin= input->GetOrigin(); + mCenter.resize(Dim); + for (unsigned int i=0; i IteratorType; IteratorType it(input, input->GetLargestPossibleRegion()); it.GoToBegin(); - typename ImageType::PointType point; - //typename itk::Vector distance; + typename ImageType::PointType point; + //typename itk::Vector distance; typename ImageType::IndexType index; //bool inside; double distance; - - while (!it.IsAtEnd()) - { - // inside=true; - index=it.GetIndex(); - input->TransformIndexToPhysicalPoint(index, point); - distance=0.0; - for(unsigned int i=0; iTransformIndexToPhysicalPoint(index, point); + distance=0.0; + for(unsigned int i=0; i(input); @@ -161,10 +163,10 @@ void clitk::ImageFillRegionGenericFilter::Update_WithDimAndPixelType_SphericRegi //-------------------------------------------------------------------- -void clitk::ImageFillRegionGenericFilter::SetSphericRegion(std::vector & radius, - std::vector & center) +void clitk::ImageFillRegionGenericFilter::SetSphericRegion(std::vector & radius, + std::vector & center) { - mRadius.clear(); + mRadius.clear(); mRadius.resize(radius.size()); std::copy(radius.begin(), radius.end(), mRadius.begin()); mCenter.clear(); @@ -174,8 +176,9 @@ void clitk::ImageFillRegionGenericFilter::SetSphericRegion(std::vector & m_IsCentered=false; } -void clitk::ImageFillRegionGenericFilter::SetSphericRegion(std::vector & radius) { - mRadius.clear(); +void clitk::ImageFillRegionGenericFilter::SetSphericRegion(std::vector & radius) +{ + mRadius.clear(); mRadius.resize(radius.size()); std::copy(radius.begin(), radius.end(), mRadius.begin()); m_IsCentered=true; diff --git a/filters/clitkImageFillRegionGenericFilter.txx b/filters/clitkImageFillRegionGenericFilter.txx index b6dd04c..817ef8f 100644 --- a/filters/clitkImageFillRegionGenericFilter.txx +++ b/filters/clitkImageFillRegionGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,7 +22,7 @@ * @file clitkImageFillRegionGenericFilter.txx * @author Cristina Gimenez * @date 9 August 2006 - * + * -------------------------------------------------*/ #endif //#define CLITKIMAGEFILLREGIONGENERICFILTER_TXX diff --git a/filters/clitkImageResampleGenericFilter.cxx b/filters/clitkImageResampleGenericFilter.cxx index 3e4e28e..81d0d61 100644 --- a/filters/clitkImageResampleGenericFilter.cxx +++ b/filters/clitkImageResampleGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,7 +23,7 @@ * @author David Sarrut * @date 23 Feb 2008 08:37:53 - * @brief + * @brief -------------------------------------------------------------------*/ @@ -45,7 +45,8 @@ //-------------------------------------------------------------------- clitk::ImageResampleGenericFilter::ImageResampleGenericFilter(): - ImageToImageGenericFilter("ImageResample") { + ImageToImageGenericFilter("ImageResample") +{ mApplyGaussianFilterBefore = false; mDefaultPixelValue = 0.0; mInterpolatorName = "NN"; @@ -59,7 +60,8 @@ clitk::ImageResampleGenericFilter::ImageResampleGenericFilter(): //-------------------------------------------------------------------- template -void clitk::ImageResampleGenericFilter::InitializeImageTypeWithDim() { +void clitk::ImageResampleGenericFilter::InitializeImageTypeWithDim() +{ ADD_DEFAULT_IMAGE_TYPES(Dim); } //-------------------------------------------------------------------- @@ -67,7 +69,8 @@ void clitk::ImageResampleGenericFilter::InitializeImageTypeWithDim() { //-------------------------------------------------------------------- template -void clitk::ImageResampleGenericFilter::UpdateWithInputImageType() { +void clitk::ImageResampleGenericFilter::UpdateWithInputImageType() +{ // Some typedefs typedef typename InputImageType::SizeType SizeType; @@ -105,7 +108,7 @@ void clitk::ImageResampleGenericFilter::UpdateWithInputImageType() { // Create Image Filter typedef itk::ResampleImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); - + // Instance of the transform object to be passed to the resample // filter. By default, identity transform is applied typedef itk::AffineTransform TransformType; @@ -129,36 +132,32 @@ void clitk::ImageResampleGenericFilter::UpdateWithInputImageType() { // Select interpolator if (mInterpolatorName == "nn") { - typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; + typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); filter->SetInterpolator(interpolator); - } - else { + } else { if (mInterpolatorName == "linear") { - typedef itk::LinearInterpolateImageFunction InterpolatorType; + typedef itk::LinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); filter->SetInterpolator(interpolator); - } - else { + } else { if (mInterpolatorName == "bspline") { - typedef itk::BSplineInterpolateImageFunction InterpolatorType; - typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); - interpolator->SetSplineOrder(mBSplineOrder); - filter->SetInterpolator(interpolator); - } - else { - if (mInterpolatorName == "blut") { - typedef itk::BSplineInterpolateImageFunctionWithLUT InterpolatorType; - typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); - interpolator->SetSplineOrder(mBSplineOrder); - interpolator->SetLUTSamplingFactor(mSamplingFactors[0]); - filter->SetInterpolator(interpolator); - } - else { - std::cerr << "Sorry, I do not know the interpolator '" << mInterpolatorName - << "'. Known interpolators are : nn, linear, bspline, blut" << std::endl; - exit(0); - } + typedef itk::BSplineInterpolateImageFunction InterpolatorType; + typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); + interpolator->SetSplineOrder(mBSplineOrder); + filter->SetInterpolator(interpolator); + } else { + if (mInterpolatorName == "blut") { + typedef itk::BSplineInterpolateImageFunctionWithLUT InterpolatorType; + typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); + interpolator->SetSplineOrder(mBSplineOrder); + interpolator->SetLUTSamplingFactor(mSamplingFactors[0]); + filter->SetInterpolator(interpolator); + } else { + std::cerr << "Sorry, I do not know the interpolator '" << mInterpolatorName + << "'. Known interpolators are : nn, linear, bspline, blut" << std::endl; + exit(0); + } } } } @@ -180,23 +179,21 @@ void clitk::ImageResampleGenericFilter::UpdateWithInputImageType() { else gaussianFilters[i]->SetInput(gaussianFilters[i-1]->GetOutput()); } filter->SetInput(gaussianFilters[InputImageType::ImageDimension-1]->GetOutput()); - } - else { + } else { filter->SetInput(input); } // Go ! - try { + try { filter->Update(); - } - catch( itk::ExceptionObject & err ) { - std::cerr << "Error while filtering " << mInputFilenames[0].c_str() - << " " << err << std::endl; + } catch( itk::ExceptionObject & err ) { + std::cerr << "Error while filtering " << mInputFilenames[0].c_str() + << " " << err << std::endl; exit(0); } // Get result - typename InputImageType::Pointer outputImage = filter->GetOutput(); + typename InputImageType::Pointer outputImage = filter->GetOutput(); // Write/save results this->SetNextOutput(outputImage); @@ -206,27 +203,31 @@ void clitk::ImageResampleGenericFilter::UpdateWithInputImageType() { //-------------------------------------------------------------------- -void clitk::ImageResampleGenericFilter::SetOutputSize(const std::vector & size) { +void clitk::ImageResampleGenericFilter::SetOutputSize(const std::vector & size) +{ mOutputSize.resize(size.size()); std::copy(size.begin(), size.end(), mOutputSize.begin()); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageResampleGenericFilter::SetOutputSpacing(const std::vector & spacing) { +void clitk::ImageResampleGenericFilter::SetOutputSpacing(const std::vector & spacing) +{ mOutputSpacing.resize(spacing.size()); std::copy(spacing.begin(), spacing.end(), mOutputSpacing.begin()); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageResampleGenericFilter::SetInterpolationName(const std::string & inter) { +void clitk::ImageResampleGenericFilter::SetInterpolationName(const std::string & inter) +{ mInterpolatorName = inter; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::ImageResampleGenericFilter::SetGaussianSigma(const std::vector & sigma) { +void clitk::ImageResampleGenericFilter::SetGaussianSigma(const std::vector & sigma) +{ mApplyGaussianFilterBefore = true; mSigma.resize(sigma.size()); std::copy(sigma.begin(), sigma.end(), mSigma.begin()); diff --git a/filters/clitkImageResampleGenericFilter.txx b/filters/clitkImageResampleGenericFilter.txx index 1dcfefe..705ee4c 100644 --- a/filters/clitkImageResampleGenericFilter.txx +++ b/filters/clitkImageResampleGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkImageResampleGenericFilter.txx * @author David Sarrut * @date 23 Feb 2008 08:40:11 - * - * @brief - * - * + * + * @brief + * + * ------------------------------------------------=*/ diff --git a/filters/clitkMedianImageGenericFilter.cxx b/filters/clitkMedianImageGenericFilter.cxx index 1a766a0..adee05d 100644 --- a/filters/clitkMedianImageGenericFilter.cxx +++ b/filters/clitkMedianImageGenericFilter.cxx @@ -4,10 +4,10 @@ /* ================================================= * @file clitkMedianImageGenericFilter.cxx * @author Bharath Navalpakkam - * @date 20.03.2010 - * - * @brief - * + * @date 20.03.2010 + * + * @brief + * ===================================================*/ #include "clitkMedianImageGenericFilter.h" diff --git a/filters/clitkMedianImageGenericFilter.txx b/filters/clitkMedianImageGenericFilter.txx index 292997b..07ce074 100644 --- a/filters/clitkMedianImageGenericFilter.txx +++ b/filters/clitkMedianImageGenericFilter.txx @@ -1,13 +1,13 @@ - #ifndef clitkMedianImageGenericFilter_txx +#ifndef clitkMedianImageGenericFilter_txx #define clitkMedianImageGenericFilter_txx /* ================================================= * @file clitkMedianImageGenericFilter.txx * @author Bharath Navalapakkam * @date 20 March 2010 - * - * @brief - * + * + * @brief + * ===================================================*/ // itk include @@ -16,88 +16,91 @@ namespace clitk { - - //-------------------------------------------------------------------- - template - MedianImageGenericFilter::MedianImageGenericFilter(): - ImageToImageGenericFilter("MedianImage") { - InitializeImageType<2>(); - InitializeImageType<3>(); - InitializeImageType<4>(); - } - //-------------------------------------------------------------------- +//-------------------------------------------------------------------- +template +MedianImageGenericFilter::MedianImageGenericFilter(): + ImageToImageGenericFilter("MedianImage") +{ + InitializeImageType<2>(); + InitializeImageType<3>(); + InitializeImageType<4>(); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +template +void MedianImageGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - template - void MedianImageGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); - } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - template - void MedianImageGenericFilter::SetArgsInfo(const args_info_type & a) { - mArgsInfo=a; - SetIOVerbose(mArgsInfo.verbose_flag); - - if (mArgsInfo.input_given) { - SetInputFilename(mArgsInfo.input_arg); - } - if (mArgsInfo.output_given) { - SetOutputFilename(mArgsInfo.output_arg); - } +//-------------------------------------------------------------------- +template +void MedianImageGenericFilter::SetArgsInfo(const args_info_type & a) +{ + mArgsInfo=a; + SetIOVerbose(mArgsInfo.verbose_flag); + + if (mArgsInfo.input_given) { + SetInputFilename(mArgsInfo.input_arg); } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //-------------------------------------------------------------------- - template - template - void - MedianImageGenericFilter::UpdateWithInputImageType() - { - // Reading input - typename InputImageType::Pointer input = this->template GetInput(0); - // Typedef - typedef typename InputImageType::PixelType PixelType; - - // typedef itk::Image OutputImageType; - - // Main filter - typedef itk::Image OutputImageType; - typename InputImageType::SizeType indexRadius; - - // Filter - typedef itk::MedianImageFilter MedianImageFilterType; - typename MedianImageFilterType::Pointer thresholdFilter=MedianImageFilterType::New(); - thresholdFilter->SetInput(input); - - indexRadius[0]=mArgsInfo.radius_arg[0]; - indexRadius[1]=mArgsInfo.radius_arg[1]; - indexRadius[2]=mArgsInfo.radius_arg[2]; - - // indexRadius[0] = 1; - // indexRadius[1] = 1; - - thresholdFilter->SetRadius( indexRadius ); - - typename OutputImageType::Pointer outputImage = thresholdFilter->GetOutput(); - thresholdFilter->Update(); - - // Write/Save results - this->template SetNextOutput(outputImage); + if (mArgsInfo.output_given) { + SetOutputFilename(mArgsInfo.output_arg); } - - //-------------------------------------------------------------------- + +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//-------------------------------------------------------------------- +template +template +void +MedianImageGenericFilter::UpdateWithInputImageType() +{ + // Reading input + typename InputImageType::Pointer input = this->template GetInput(0); + // Typedef + typedef typename InputImageType::PixelType PixelType; + + // typedef itk::Image OutputImageType; + + // Main filter + typedef itk::Image OutputImageType; + typename InputImageType::SizeType indexRadius; + + // Filter + typedef itk::MedianImageFilter MedianImageFilterType; + typename MedianImageFilterType::Pointer thresholdFilter=MedianImageFilterType::New(); + thresholdFilter->SetInput(input); + + indexRadius[0]=mArgsInfo.radius_arg[0]; + indexRadius[1]=mArgsInfo.radius_arg[1]; + indexRadius[2]=mArgsInfo.radius_arg[2]; + + // indexRadius[0] = 1; + // indexRadius[1] = 1; + + thresholdFilter->SetRadius( indexRadius ); + + typename OutputImageType::Pointer outputImage = thresholdFilter->GetOutput(); + thresholdFilter->Update(); + + // Write/Save results + this->template SetNextOutput(outputImage); +} + +//-------------------------------------------------------------------- }//end clitk - + #endif //#define clitkMedianImageGenericFilter_txx diff --git a/filters/clitkResampleImageGenericFilter.txx b/filters/clitkResampleImageGenericFilter.txx index a380824..5cee0d9 100644 --- a/filters/clitkResampleImageGenericFilter.txx +++ b/filters/clitkResampleImageGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,155 +22,155 @@ // clitk #include "clitkResampleImageWithOptionsFilter.h" -namespace clitk { - - //-------------------------------------------------------------------- - template - ResampleImageGenericFilter::ResampleImageGenericFilter(): - ImageToImageGenericFilter("Resample") { - InitializeImageType<2>(); - InitializeImageType<3>(); - InitializeImageType<4>(); - } - //-------------------------------------------------------------------- +namespace clitk +{ + +//-------------------------------------------------------------------- +template +ResampleImageGenericFilter::ResampleImageGenericFilter(): + ImageToImageGenericFilter("Resample") +{ + InitializeImageType<2>(); + InitializeImageType<3>(); + InitializeImageType<4>(); +} +//-------------------------------------------------------------------- - //-------------------------------------------------------------------- - template - template - void ResampleImageGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); - //ADD_IMAGE_TYPE(Dim, short); +//-------------------------------------------------------------------- +template +template +void ResampleImageGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); + //ADD_IMAGE_TYPE(Dim, short); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +void ResampleImageGenericFilter::SetArgsInfo(const args_info_type & a) +{ + mArgsInfo=a; + if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); + SetIOVerbose(mArgsInfo.verbose_flag); + if (mArgsInfo.input_given) { + SetInputFilename(mArgsInfo.input_arg); } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - template - void ResampleImageGenericFilter::SetArgsInfo(const args_info_type & a) { - mArgsInfo=a; - if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); - SetIOVerbose(mArgsInfo.verbose_flag); - if (mArgsInfo.input_given) { - SetInputFilename(mArgsInfo.input_arg); - } - if (mArgsInfo.output_given) { - SetOutputFilename(mArgsInfo.output_arg); - } + if (mArgsInfo.output_given) { + SetOutputFilename(mArgsInfo.output_arg); } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //-------------------------------------------------------------------- - template - template - void - ResampleImageGenericFilter::UpdateWithInputImageType() { - - // Reading input - typename InputImageType::Pointer input = this->template GetInput(0); - - // Main filter - typedef typename InputImageType::PixelType PixelType; - typedef InputImageType OutputImageType; // to change to float is user ask it (?) - - // Filter - typedef clitk::ResampleImageWithOptionsFilter ResampleImageFilterType; - typename ResampleImageFilterType::Pointer filter = ResampleImageFilterType::New(); - filter->SetInput(input); - - // Set Verbose - filter->SetVerboseOptions(mArgsInfo.verbose_flag); - - // Set size / spacing - static const unsigned int dim = OutputImageType::ImageDimension; - typename OutputImageType::SpacingType spacing; - typename OutputImageType::SizeType size; - if (mArgsInfo.spacing_given == 1) { - filter->SetOutputIsoSpacing(mArgsInfo.spacing_arg[0]); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//-------------------------------------------------------------------- +template +template +void +ResampleImageGenericFilter::UpdateWithInputImageType() +{ + + // Reading input + typename InputImageType::Pointer input = this->template GetInput(0); + + // Main filter + typedef typename InputImageType::PixelType PixelType; + typedef InputImageType OutputImageType; // to change to float is user ask it (?) + + // Filter + typedef clitk::ResampleImageWithOptionsFilter ResampleImageFilterType; + typename ResampleImageFilterType::Pointer filter = ResampleImageFilterType::New(); + filter->SetInput(input); + + // Set Verbose + filter->SetVerboseOptions(mArgsInfo.verbose_flag); + + // Set size / spacing + static const unsigned int dim = OutputImageType::ImageDimension; + typename OutputImageType::SpacingType spacing; + typename OutputImageType::SizeType size; + if (mArgsInfo.spacing_given == 1) { + filter->SetOutputIsoSpacing(mArgsInfo.spacing_arg[0]); + } else { + if ((mArgsInfo.spacing_given != 0) && (mArgsInfo.size_given != 0)) { + std::cerr << "Error: use spacing or size, not both." << std::endl; + exit(0); } - else { - if ((mArgsInfo.spacing_given != 0) && (mArgsInfo.size_given != 0)) { - std::cerr << "Error: use spacing or size, not both." << std::endl; - exit(0); - } - if (!((mArgsInfo.spacing_given == 0) && (mArgsInfo.size_given == 0))) { - - if ((mArgsInfo.spacing_given != 0) && (mArgsInfo.spacing_given != dim)) { - std::cerr << "Error: spacing should have one or " << dim << " values." << std::endl; - exit(0); - } - if ((mArgsInfo.size_given != 0) && (mArgsInfo.size_given != dim)) { - std::cerr << "Error: size should have " << dim << " values." << std::endl; - exit(0); - } - if (mArgsInfo.spacing_given) - for(unsigned int i=0; iSetOutputSpacing(spacing); - filter->SetOutputSize(size); + if (!((mArgsInfo.spacing_given == 0) && (mArgsInfo.size_given == 0))) { + + if ((mArgsInfo.spacing_given != 0) && (mArgsInfo.spacing_given != dim)) { + std::cerr << "Error: spacing should have one or " << dim << " values." << std::endl; + exit(0); } - } - - // Set temporal dimension - filter->SetLastDimensionIsTime(mArgsInfo.time_flag); - - // Set Gauss - filter->SetGaussianFilteringEnabled(mArgsInfo.autogauss_flag); - if (mArgsInfo.gauss_given != 0) { - typename ResampleImageFilterType::GaussianSigmaType g; - for(unsigned int i=0; iSetGaussianSigma(g); + if (mArgsInfo.spacing_given) + for(unsigned int i=0; iSetOutputSpacing(spacing); + filter->SetOutputSize(size); } - - // Set Interpolation - std::string interp = std::string(mArgsInfo.interp_arg); - if (interp == "nn") { - filter->SetInterpolationType(ResampleImageFilterType::NearestNeighbor); + } + + // Set temporal dimension + filter->SetLastDimensionIsTime(mArgsInfo.time_flag); + + // Set Gauss + filter->SetGaussianFilteringEnabled(mArgsInfo.autogauss_flag); + if (mArgsInfo.gauss_given != 0) { + typename ResampleImageFilterType::GaussianSigmaType g; + for(unsigned int i=0; iSetInterpolationType(ResampleImageFilterType::Linear); - } - else { - if (interp == "bspline") { - filter->SetInterpolationType(ResampleImageFilterType::BSpline); - } - else { - if (interp == "blut") { - filter->SetInterpolationType(ResampleImageFilterType::B_LUT); - } - else { - std::cerr << "Error. I do not know interpolation '" << mArgsInfo.interp_arg - << "'. Choose among: nn, linear, bspline, blut" << std::endl; - exit(0); - } + filter->SetGaussianSigma(g); + } + + // Set Interpolation + std::string interp = std::string(mArgsInfo.interp_arg); + if (interp == "nn") { + filter->SetInterpolationType(ResampleImageFilterType::NearestNeighbor); + } else { + if (interp == "linear") { + filter->SetInterpolationType(ResampleImageFilterType::Linear); + } else { + if (interp == "bspline") { + filter->SetInterpolationType(ResampleImageFilterType::BSpline); + } else { + if (interp == "blut") { + filter->SetInterpolationType(ResampleImageFilterType::B_LUT); + } else { + std::cerr << "Error. I do not know interpolation '" << mArgsInfo.interp_arg + << "'. Choose among: nn, linear, bspline, blut" << std::endl; + exit(0); } } } - - // Set default pixel value - filter->SetDefaultPixelValue(mArgsInfo.default_arg); + } - // Set thread - if (mArgsInfo.thread_given) { - filter->SetNumberOfThreads(mArgsInfo.thread_arg); - } + // Set default pixel value + filter->SetDefaultPixelValue(mArgsInfo.default_arg); - // Go ! - filter->Update(); - typename OutputImageType::Pointer outputImage = filter->GetOutput(); - this->template SetNextOutput(outputImage); + // Set thread + if (mArgsInfo.thread_given) { + filter->SetNumberOfThreads(mArgsInfo.thread_arg); } - //-------------------------------------------------------------------- + + // Go ! + filter->Update(); + typename OutputImageType::Pointer outputImage = filter->GetOutput(); + this->template SetNextOutput(outputImage); +} +//-------------------------------------------------------------------- } diff --git a/filters/clitkSplitImageGenericFilter.cxx b/filters/clitkSplitImageGenericFilter.cxx index e887b04..2b95024 100644 --- a/filters/clitkSplitImageGenericFilter.cxx +++ b/filters/clitkSplitImageGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -21,7 +21,7 @@ * @author Joël Schaerer * @date 20 April 2009 - * @brief + * @brief -------------------------------------------------------------------*/ #include "clitkSplitImageGenericFilter.h" @@ -29,7 +29,8 @@ #include "clitkSplitImageGenericFilter.txx" //-------------------------------------------------------------------- clitk::SplitImageGenericFilter::SplitImageGenericFilter(): - clitk::ImageToImageGenericFilter("SplitImage") { + clitk::ImageToImageGenericFilter("SplitImage") +{ mSplitDimension = 0; InitializeImageType<3>(); InitializeImageType<4>(); @@ -39,7 +40,8 @@ clitk::SplitImageGenericFilter::SplitImageGenericFilter(): //-------------------------------------------------------------------- template -void clitk::SplitImageGenericFilter::InitializeImageType() { +void clitk::SplitImageGenericFilter::InitializeImageType() +{ ADD_DEFAULT_IMAGE_TYPES(Dim); ADD_VEC_IMAGE_TYPE(Dim, 3,float); } @@ -47,7 +49,8 @@ void clitk::SplitImageGenericFilter::InitializeImageType() { //-------------------------------------------------------------------- template -void clitk::SplitImageGenericFilter::UpdateWithInputImageType() { +void clitk::SplitImageGenericFilter::UpdateWithInputImageType() +{ // Read input typedef typename ImageType::PixelType PixelType; @@ -67,17 +70,16 @@ void clitk::SplitImageGenericFilter::UpdateWithInputImageType() { typename ImageType::IndexType index=input->GetLargestPossibleRegion().GetIndex(); std::string base_filename=GetOutputFilename(); unsigned int number_of_output_images=input->GetLargestPossibleRegion().GetSize()[mSplitDimension]; - for (unsigned int i=0;iSetExtractionRegion(extracted_region); - filter->Update(); - SetOutputFilename(base_filename+"_"+ss.str()+".mhd"); - typename OutputImageType::Pointer output=filter->GetOutput(); - SetNextOutput(output); + for (unsigned int i=0; iSetExtractionRegion(extracted_region); + filter->Update(); + SetOutputFilename(base_filename+"_"+ss.str()+".mhd"); + typename OutputImageType::Pointer output=filter->GetOutput(); + SetNextOutput(output); } } //-------------------------------------------------------------------- diff --git a/filters/clitkSplitImageGenericFilter.txx b/filters/clitkSplitImageGenericFilter.txx index f5d2aae..189c4ed 100644 --- a/filters/clitkSplitImageGenericFilter.txx +++ b/filters/clitkSplitImageGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr diff --git a/filters/clitkUnsharpMaskGenericFilter.txx b/filters/clitkUnsharpMaskGenericFilter.txx index ce7c181..d178da0 100644 --- a/filters/clitkUnsharpMaskGenericFilter.txx +++ b/filters/clitkUnsharpMaskGenericFilter.txx @@ -38,10 +38,11 @@ namespace clitk //-------------------------------------------------------------------- template UnsharpMaskGenericFilter::UnsharpMaskGenericFilter(): - ImageToImageGenericFilter("UnsharpMask") { - InitializeImageType<2>(); - InitializeImageType<3>(); - //InitializeImageType<4>(); + ImageToImageGenericFilter("UnsharpMask") +{ + InitializeImageType<2>(); + InitializeImageType<3>(); + //InitializeImageType<4>(); } //-------------------------------------------------------------------- @@ -49,25 +50,27 @@ UnsharpMaskGenericFilter::UnsharpMaskGenericFilter(): //-------------------------------------------------------------------- template template -void UnsharpMaskGenericFilter::InitializeImageType() { - ADD_DEFAULT_IMAGE_TYPES(Dim); +void UnsharpMaskGenericFilter::InitializeImageType() +{ + ADD_DEFAULT_IMAGE_TYPES(Dim); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -void UnsharpMaskGenericFilter::SetArgsInfo(const args_info_type & a) { - mArgsInfo=a; - SetIOVerbose(mArgsInfo.verbose_flag); - if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); - - if (mArgsInfo.input_given) { - SetInputFilename(mArgsInfo.input_arg); - } - if (mArgsInfo.output_given) { - SetOutputFilename(mArgsInfo.output_arg); - } +void UnsharpMaskGenericFilter::SetArgsInfo(const args_info_type & a) +{ + mArgsInfo=a; + SetIOVerbose(mArgsInfo.verbose_flag); + if (mArgsInfo.imagetypes_flag) this->PrintAvailableImageTypes(); + + if (mArgsInfo.input_given) { + SetInputFilename(mArgsInfo.input_arg); + } + if (mArgsInfo.output_given) { + SetOutputFilename(mArgsInfo.output_arg); + } } //-------------------------------------------------------------------- @@ -80,26 +83,26 @@ void UnsharpMaskGenericFilter::UpdateWithInputImageType() { - // Reading input - typename InputImageType::Pointer input = this->template GetInput(0); + // Reading input + typename InputImageType::Pointer input = this->template GetInput(0); - // Main filter - typedef typename InputImageType::PixelType PixelType; - typedef itk::Image OutputImageType; + // Main filter + typedef typename InputImageType::PixelType PixelType; + typedef itk::Image OutputImageType; - // Filter - typedef itk::RecursiveGaussianImageFilter RecursiveGaussianImageFilterType; - typename RecursiveGaussianImageFilterType::Pointer gaussianFilter=RecursiveGaussianImageFilterType::New(); - gaussianFilter->SetInput(input); - gaussianFilter->SetSigma(mArgsInfo.sigma_arg); + // Filter + typedef itk::RecursiveGaussianImageFilter RecursiveGaussianImageFilterType; + typename RecursiveGaussianImageFilterType::Pointer gaussianFilter=RecursiveGaussianImageFilterType::New(); + gaussianFilter->SetInput(input); + gaussianFilter->SetSigma(mArgsInfo.sigma_arg); - typedef itk::SubtractImageFilter SubtractFilterType; - typename SubtractFilterType::Pointer subtractFilter = SubtractFilterType::New(); - subtractFilter->SetInput1(input); - subtractFilter->SetInput2(gaussianFilter->GetOutput()); - subtractFilter->Update(); + typedef itk::SubtractImageFilter SubtractFilterType; + typename SubtractFilterType::Pointer subtractFilter = SubtractFilterType::New(); + subtractFilter->SetInput1(input); + subtractFilter->SetInput2(gaussianFilter->GetOutput()); + subtractFilter->Update(); - this->template SetNextOutput(subtractFilter->GetOutput()); + this->template SetNextOutput(subtractFilter->GetOutput()); } //-------------------------------------------------------------------- diff --git a/filters/clitkVFResampleGenericFilter.cxx b/filters/clitkVFResampleGenericFilter.cxx index 554f3a2..2137c3f 100644 --- a/filters/clitkVFResampleGenericFilter.cxx +++ b/filters/clitkVFResampleGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,7 +23,7 @@ * @author David Sarrut * @date 23 Feb 2008 08:37:53 - * @brief + * @brief -------------------------------------------------------------------*/ @@ -31,7 +31,8 @@ //-------------------------------------------------------------------- clitk::VFResampleGenericFilter::VFResampleGenericFilter(): - clitk::ImageToImageGenericFilter("VFResample") { + clitk::ImageToImageGenericFilter("VFResample") +{ InitializeImageType<2>(); InitializeImageType<3>(); InitializeImageType<4>(); @@ -45,7 +46,8 @@ clitk::VFResampleGenericFilter::VFResampleGenericFilter(): //-------------------------------------------------------------------- template -void clitk::VFResampleGenericFilter::InitializeImageType() { +void clitk::VFResampleGenericFilter::InitializeImageType() +{ ADD_IMAGE_TYPE(Dim, float); } //-------------------------------------------------------------------- @@ -53,23 +55,25 @@ void clitk::VFResampleGenericFilter::InitializeImageType() { //-------------------------------------------------------------------- template -void clitk::VFResampleGenericFilter::UpdateWithInputImageType() { +void clitk::VFResampleGenericFilter::UpdateWithInputImageType() +{ - if (mNbOfComponents == 1) { + if (mNbOfComponents == 1) { std::cerr << "Error, only one components ? Use clitkImageResample instead." << std::endl; exit(0); } typedef typename ImageType::PixelType PixelType; if (mNbOfComponents == 2) Update_WithDimAndPixelTypeAndComponent(); - if (mNbOfComponents == 3) Update_WithDimAndPixelTypeAndComponent(); - if (mNbOfComponents == 4) Update_WithDimAndPixelTypeAndComponent(); + if (mNbOfComponents == 3) Update_WithDimAndPixelTypeAndComponent(); + if (mNbOfComponents == 4) Update_WithDimAndPixelTypeAndComponent(); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- template -void clitk::VFResampleGenericFilter::Update_WithDimAndPixelTypeAndComponent() { +void clitk::VFResampleGenericFilter::Update_WithDimAndPixelTypeAndComponent() +{ // Reading input typedef itk::Vector DisplacementType; typedef itk::Image< DisplacementType, Dim > ImageType; @@ -86,8 +90,9 @@ void clitk::VFResampleGenericFilter::Update_WithDimAndPixelTypeAndComponent() { //-------------------------------------------------------------------- template -typename ImageType::Pointer -clitk::VFResampleGenericFilter::ComputeImage(typename ImageType::Pointer inputImage) { +typename ImageType::Pointer +clitk::VFResampleGenericFilter::ComputeImage(typename ImageType::Pointer inputImage) +{ // Check options static unsigned int dim = ImageType::ImageDimension; @@ -114,7 +119,7 @@ clitk::VFResampleGenericFilter::ComputeImage(typename ImageType::Pointer inputIm // Create Image Filter typedef itk::VectorResampleImageFilter FilterType; typename FilterType::Pointer filter = FilterType::New(); - + // Instance of the transform object to be passed to the resample // filter. By default, identity transform is applied typedef itk::AffineTransform TransformType; @@ -138,18 +143,16 @@ clitk::VFResampleGenericFilter::ComputeImage(typename ImageType::Pointer inputIm // Select interpolator if (mInterpolatorName == "nn") { - typedef itk::VectorNearestNeighborInterpolateImageFunction InterpolatorType; + typedef itk::VectorNearestNeighborInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); filter->SetInterpolator(interpolator); - } - else { + } else { if (mInterpolatorName == "linear") { - typedef itk::VectorLinearInterpolateImageFunction InterpolatorType; + typedef itk::VectorLinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); filter->SetInterpolator(interpolator); - } - else { - std::cerr << "Sorry, I do not know the interpolator (for vector field) '" << mInterpolatorName + } else { + std::cerr << "Sorry, I do not know the interpolator (for vector field) '" << mInterpolatorName << "'. Known interpolators are : nn, linear" << std::endl; exit(0); } @@ -172,50 +175,52 @@ clitk::VFResampleGenericFilter::ComputeImage(typename ImageType::Pointer inputIm else gaussianFilters[i]->SetInput(gaussianFilters[i-1]->GetOutput()); } filter->SetInput(gaussianFilters[ImageType::ImageDimension-1]->GetOutput()); - } - else { + } else { filter->SetInput(inputImage); } // Go ! - try { + try { filter->Update(); - } - catch( itk::ExceptionObject & err ) { - std::cerr << "Error while filtering " << mInputFilenames[0].c_str() - << " " << err << std::endl; + } catch( itk::ExceptionObject & err ) { + std::cerr << "Error while filtering " << mInputFilenames[0].c_str() + << " " << err << std::endl; exit(0); } // Return result return filter->GetOutput(); - + } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::VFResampleGenericFilter::SetOutputSize(const std::vector & size) { +void clitk::VFResampleGenericFilter::SetOutputSize(const std::vector & size) +{ mOutputSize.resize(size.size()); std::copy(size.begin(), size.end(), mOutputSize.begin()); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::VFResampleGenericFilter::SetOutputSpacing(const std::vector & spacing) { +void clitk::VFResampleGenericFilter::SetOutputSpacing(const std::vector & spacing) +{ mOutputSpacing.resize(spacing.size()); std::copy(spacing.begin(), spacing.end(), mOutputSpacing.begin()); } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::VFResampleGenericFilter::SetInterpolationName(const std::string & inter) { +void clitk::VFResampleGenericFilter::SetInterpolationName(const std::string & inter) +{ mInterpolatorName = inter; } //-------------------------------------------------------------------- //-------------------------------------------------------------------- -void clitk::VFResampleGenericFilter::SetGaussianSigma(const std::vector & sigma) { +void clitk::VFResampleGenericFilter::SetGaussianSigma(const std::vector & sigma) +{ mApplyGaussianFilterBefore = true; mSigma.resize(sigma.size()); std::copy(sigma.begin(), sigma.end(), mSigma.begin()); diff --git a/filters/clitkVFResampleGenericFilter.txx b/filters/clitkVFResampleGenericFilter.txx index 2cd9379..5efd0ec 100644 --- a/filters/clitkVFResampleGenericFilter.txx +++ b/filters/clitkVFResampleGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkVFResampleGenericFilter.txx * @author David Sarrut * @date 23 Feb 2008 08:40:11 - * - * @brief - * - * + * + * @brief + * + * ------------------------------------------------=*/ //-------------------------------------------------------------------- diff --git a/itk/clitkForwardWarpImageFilter.txx b/itk/clitkForwardWarpImageFilter.txx index 38836be..c3d46be 100644 --- a/itk/clitkForwardWarpImageFilter.txx +++ b/itk/clitkForwardWarpImageFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,382 +23,363 @@ // Put the helper classes in an anonymous namespace so that it is not // exposed to the user -namespace -{//nameless namespace - - //========================================================================================================================= - //helper class 1 to allow a threaded execution: add contributions of input to output and update weights - //========================================================================================================================= - template class HelperClass1 : public itk::ImageToImageFilter - { - - public: - /** Standard class typedefs. */ - typedef HelperClass1 Self; - typedef itk::ImageToImageFilter Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods) */ - itkTypeMacro( HelperClass1, ImageToImageFilter ); - - /** Constants for the image dimensions */ - itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); - - - //Typedefs - typedef typename OutputImageType::PixelType OutputPixelType; - typedef itk::Image WeightsImageType; - typedef itk::Image MutexImageType; - //=================================================================================== - //Set methods - void SetWeights(const typename WeightsImageType::Pointer input) - { - m_Weights = input; - this->Modified(); - } - void SetDeformationField(const typename DeformationFieldType::Pointer input) - { - m_DeformationField=input; - this->Modified(); - } - void SetMutexImage(const typename MutexImageType::Pointer input) - { - m_MutexImage=input; - this->Modified(); - m_ThreadSafe=true; +namespace +{ +//nameless namespace + +//========================================================================================================================= +//helper class 1 to allow a threaded execution: add contributions of input to output and update weights +//========================================================================================================================= +template class HelperClass1 : public itk::ImageToImageFilter +{ + +public: + /** Standard class typedefs. */ + typedef HelperClass1 Self; + typedef itk::ImageToImageFilter Superclass; + typedef itk::SmartPointer Pointer; + typedef itk::SmartPointer ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods) */ + itkTypeMacro( HelperClass1, ImageToImageFilter ); + + /** Constants for the image dimensions */ + itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); + + + //Typedefs + typedef typename OutputImageType::PixelType OutputPixelType; + typedef itk::Image WeightsImageType; + typedef itk::Image MutexImageType; + //=================================================================================== + //Set methods + void SetWeights(const typename WeightsImageType::Pointer input) { + m_Weights = input; + this->Modified(); + } + void SetDeformationField(const typename DeformationFieldType::Pointer input) { + m_DeformationField=input; + this->Modified(); + } + void SetMutexImage(const typename MutexImageType::Pointer input) { + m_MutexImage=input; + this->Modified(); + m_ThreadSafe=true; + } + + //Get methods + typename WeightsImageType::Pointer GetWeights() { + return m_Weights; + } + + /** Typedef to describe the output image region type. */ + typedef typename OutputImageType::RegionType OutputImageRegionType; + +protected: + HelperClass1(); + ~HelperClass1() {}; + + //the actual processing + void BeforeThreadedGenerateData(); + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); + + //member data + typename itk::Image< double, ImageDimension>::Pointer m_Weights; + typename DeformationFieldType::Pointer m_DeformationField; + typename MutexImageType::Pointer m_MutexImage; + bool m_ThreadSafe; + +}; + + + +//========================================================================================================================= +//Member functions of the helper class 1 +//========================================================================================================================= + + +//========================================================================================================================= +//Empty constructor +template +HelperClass1::HelperClass1() +{ + m_ThreadSafe=false; +} + + +//========================================================================================================================= +//Before threaded data +template +void HelperClass1::BeforeThreadedGenerateData() +{ + //Since we will add, put to zero! + this->GetOutput()->FillBuffer(itk::NumericTraits::Zero); + this->GetWeights()->FillBuffer(itk::NumericTraits::Zero); +} + + +//========================================================================================================================= +//update the output for the outputRegionForThread +template +void HelperClass1::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) +{ + + //Get pointer to the input + typename InputImageType::ConstPointer inputPtr = this->GetInput(); + + //Get pointer to the output + typename OutputImageType::Pointer outputPtr = this->GetOutput(); + typename OutputImageType::SizeType size=outputPtr->GetLargestPossibleRegion().GetSize(); + + //Iterators over input and deformation field + typedef itk::ImageRegionConstIteratorWithIndex InputImageIteratorType; + typedef itk::ImageRegionIterator DeformationFieldIteratorType; + + //define them over the outputRegionForThread + InputImageIteratorType inputIt(inputPtr, outputRegionForThread); + DeformationFieldIteratorType fieldIt(m_DeformationField,outputRegionForThread); + + //Initialize + typename InputImageType::IndexType index; + itk::ContinuousIndex contIndex; + typename InputImageType::PointType point; + typedef typename DeformationFieldType::PixelType DisplacementType; + DisplacementType displacement; + fieldIt.GoToBegin(); + inputIt.GoToBegin(); + + //define some temp variables + signed long baseIndex[ImageDimension]; + double distance[ImageDimension]; + unsigned int dim, counter, upper; + double overlap, totalOverlap; + typename OutputImageType::IndexType neighIndex; + + //Find the number of neighbors + unsigned int neighbors = 1 << ImageDimension; + + + //================================================================================================== + //Loop over the region and add the intensities to the output and the weight to the weights + //================================================================================================== + while( !inputIt.IsAtEnd() ) { + + // get the input image index + index = inputIt.GetIndex(); + inputPtr->TransformIndexToPhysicalPoint( index, point ); + + // get the required displacement + displacement = fieldIt.Get(); + + // compute the required output image point + for(unsigned int j = 0; j < ImageDimension; j++ ) point[j] += displacement[j]; + + + // Update the output and the weights + if(outputPtr->TransformPhysicalPointToContinuousIndex(point, contIndex ) ) { + for(dim = 0; dim < ImageDimension; dim++) { + // The following block is equivalent to the following line without + // having to call floor. For positive inputs!!! + // baseIndex[dim] = (long) vcl_floor(contIndex[dim] ); + baseIndex[dim] = (long) contIndex[dim]; + distance[dim] = contIndex[dim] - double( baseIndex[dim] ); + } + + //Add contribution for each neighbor + totalOverlap = itk::NumericTraits::Zero; + for( counter = 0; counter < neighbors ; counter++ ) { + overlap = 1.0; // fraction overlap + upper = counter; // each bit indicates upper/lower neighbour + + // get neighbor index and overlap fraction + for( dim = 0; dim < 3; dim++ ) { + if ( upper & 1 ) { + neighIndex[dim] = baseIndex[dim] + 1; + overlap *= distance[dim]; + } else { + neighIndex[dim] = baseIndex[dim]; + overlap *= 1.0 - distance[dim]; + } + upper >>= 1; + } + + //Set neighbor value only if overlap is not zero + if( (overlap>0.0)) // && + // (static_cast(neighIndex[0])(neighIndex[1])(neighIndex[2])=0) && + // (neighIndex[1]>=0) && + // (neighIndex[2]>=0) ) + { + + if (! m_ThreadSafe) { + //Set the pixel and weight at neighIndex + outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * static_cast(inputIt.Get())); + m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); + + } else { + //Entering critilal section: shared memory + m_MutexImage->GetPixel(neighIndex).Lock(); + + //Set the pixel and weight at neighIndex + outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * static_cast(inputIt.Get())); + m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); + + //Unlock + m_MutexImage->GetPixel(neighIndex).Unlock(); + + } + //Add to total overlap + totalOverlap += overlap; + } + + //check for totaloverlap: not very likely + if( totalOverlap == 1.0 ) { + // finished + break; + } + } } - - //Get methods - typename WeightsImageType::Pointer GetWeights(){return m_Weights;} - - /** Typedef to describe the output image region type. */ - typedef typename OutputImageType::RegionType OutputImageRegionType; - - protected: - HelperClass1(); - ~HelperClass1(){}; - - //the actual processing - void BeforeThreadedGenerateData(); - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); - - //member data - typename itk::Image< double, ImageDimension>::Pointer m_Weights; - typename DeformationFieldType::Pointer m_DeformationField; - typename MutexImageType::Pointer m_MutexImage; - bool m_ThreadSafe; - - }; - - - - //========================================================================================================================= - //Member functions of the helper class 1 - //========================================================================================================================= - - - //========================================================================================================================= - //Empty constructor - template - HelperClass1::HelperClass1() - { - m_ThreadSafe=false; + + ++fieldIt; + ++inputIt; } - //========================================================================================================================= - //Before threaded data - template - void HelperClass1::BeforeThreadedGenerateData() - { - //Since we will add, put to zero! - this->GetOutput()->FillBuffer(itk::NumericTraits::Zero); - this->GetWeights()->FillBuffer(itk::NumericTraits::Zero); +} + + + +//========================================================================================================================= +//helper class 2 to allow a threaded execution of normalisation by the weights +//========================================================================================================================= +template +class HelperClass2 : public itk::ImageToImageFilter +{ + +public: + /** Standard class typedefs. */ + typedef HelperClass2 Self; + typedef itk::ImageToImageFilter Superclass; + typedef itk::SmartPointer Pointer; + typedef itk::SmartPointer ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods) */ + itkTypeMacro( HelperClass2, ImageToImageFilter ); + + /** Constants for the image dimensions */ + itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); + + //Typedefs + typedef typename InputImageType::PixelType InputPixelType; + typedef typename OutputImageType::PixelType OutputPixelType; + typedef itk::Image WeightsImageType; + + + //Set methods + void SetWeights(const typename WeightsImageType::Pointer input) { + m_Weights = input; + this->Modified(); } - - - //========================================================================================================================= - //update the output for the outputRegionForThread - template - void HelperClass1::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) - { - - //Get pointer to the input - typename InputImageType::ConstPointer inputPtr = this->GetInput(); - - //Get pointer to the output - typename OutputImageType::Pointer outputPtr = this->GetOutput(); - typename OutputImageType::SizeType size=outputPtr->GetLargestPossibleRegion().GetSize(); - - //Iterators over input and deformation field - typedef itk::ImageRegionConstIteratorWithIndex InputImageIteratorType; - typedef itk::ImageRegionIterator DeformationFieldIteratorType; - - //define them over the outputRegionForThread - InputImageIteratorType inputIt(inputPtr, outputRegionForThread); - DeformationFieldIteratorType fieldIt(m_DeformationField,outputRegionForThread); - - //Initialize - typename InputImageType::IndexType index; - itk::ContinuousIndex contIndex; - typename InputImageType::PointType point; - typedef typename DeformationFieldType::PixelType DisplacementType; - DisplacementType displacement; - fieldIt.GoToBegin(); - inputIt.GoToBegin(); - - //define some temp variables - signed long baseIndex[ImageDimension]; - double distance[ImageDimension]; - unsigned int dim, counter, upper; - double overlap, totalOverlap; - typename OutputImageType::IndexType neighIndex; - - //Find the number of neighbors - unsigned int neighbors = 1 << ImageDimension; - - - //================================================================================================== - //Loop over the region and add the intensities to the output and the weight to the weights - //================================================================================================== - while( !inputIt.IsAtEnd() ) - { - - // get the input image index - index = inputIt.GetIndex(); - inputPtr->TransformIndexToPhysicalPoint( index, point ); - - // get the required displacement - displacement = fieldIt.Get(); - - // compute the required output image point - for(unsigned int j = 0; j < ImageDimension; j++ ) point[j] += displacement[j]; - - - // Update the output and the weights - if(outputPtr->TransformPhysicalPointToContinuousIndex(point, contIndex ) ) - { - for(dim = 0; dim < ImageDimension; dim++) - { - // The following block is equivalent to the following line without - // having to call floor. For positive inputs!!! - // baseIndex[dim] = (long) vcl_floor(contIndex[dim] ); - baseIndex[dim] = (long) contIndex[dim]; - distance[dim] = contIndex[dim] - double( baseIndex[dim] ); - } - - //Add contribution for each neighbor - totalOverlap = itk::NumericTraits::Zero; - for( counter = 0; counter < neighbors ; counter++ ) - { - overlap = 1.0; // fraction overlap - upper = counter; // each bit indicates upper/lower neighbour - - // get neighbor index and overlap fraction - for( dim = 0; dim < 3; dim++ ) - { - if ( upper & 1 ) - { - neighIndex[dim] = baseIndex[dim] + 1; - overlap *= distance[dim]; - } - else - { - neighIndex[dim] = baseIndex[dim]; - overlap *= 1.0 - distance[dim]; - } - upper >>= 1; - } - - //Set neighbor value only if overlap is not zero - if( (overlap>0.0)) // && - // (static_cast(neighIndex[0])(neighIndex[1])(neighIndex[2])=0) && - // (neighIndex[1]>=0) && - // (neighIndex[2]>=0) ) - { - - if (! m_ThreadSafe) - { - //Set the pixel and weight at neighIndex - outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * static_cast(inputIt.Get())); - m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); - - } - else - { - //Entering critilal section: shared memory - m_MutexImage->GetPixel(neighIndex).Lock(); - - //Set the pixel and weight at neighIndex - outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * static_cast(inputIt.Get())); - m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); - - //Unlock - m_MutexImage->GetPixel(neighIndex).Unlock(); - - } - //Add to total overlap - totalOverlap += overlap; - } - - //check for totaloverlap: not very likely - if( totalOverlap == 1.0 ) - { - // finished - break; - } - } - } - - ++fieldIt; - ++inputIt; - } - - + void SetEdgePaddingValue(OutputPixelType value) { + m_EdgePaddingValue = value; + this->Modified(); } + /** Typedef to describe the output image region type. */ + typedef typename OutputImageType::RegionType OutputImageRegionType; + +protected: + HelperClass2(); + ~HelperClass2() {}; + + //the actual processing + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); - //========================================================================================================================= - //helper class 2 to allow a threaded execution of normalisation by the weights - //========================================================================================================================= - template - class HelperClass2 : public itk::ImageToImageFilter - { - - public: - /** Standard class typedefs. */ - typedef HelperClass2 Self; - typedef itk::ImageToImageFilter Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods) */ - itkTypeMacro( HelperClass2, ImageToImageFilter ); - - /** Constants for the image dimensions */ - itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); - - //Typedefs - typedef typename InputImageType::PixelType InputPixelType; - typedef typename OutputImageType::PixelType OutputPixelType; - typedef itk::Image WeightsImageType; - - - //Set methods - void SetWeights(const typename WeightsImageType::Pointer input) - { - m_Weights = input; - this->Modified(); + + //member data + typename WeightsImageType::Pointer m_Weights; + OutputPixelType m_EdgePaddingValue; +} ; + + + +//========================================================================================================================= +//Member functions of the helper class 2 +//========================================================================================================================= + + +//========================================================================================================================= +//Empty constructor +template +HelperClass2::HelperClass2() +{ + m_EdgePaddingValue=static_cast(0.0); +} + + +//========================================================================================================================= +//update the output for the outputRegionForThread +template void +HelperClass2::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) +{ + + //Get pointer to the input + typename InputImageType::ConstPointer inputPtr = this->GetInput(); + + //Get pointer to the output + typename OutputImageType::Pointer outputPtr = this->GetOutput(); + + //Iterators over input, weigths and output + typedef itk::ImageRegionConstIterator InputImageIteratorType; + typedef itk::ImageRegionIterator OutputImageIteratorType; + typedef itk::ImageRegionIterator WeightsImageIteratorType; + + //define them over the outputRegionForThread + OutputImageIteratorType outputIt(outputPtr, outputRegionForThread); + InputImageIteratorType inputIt(inputPtr, outputRegionForThread); + WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread); + + + //================================================================================================== + //loop over the output and normalize the input, remove holes + OutputPixelType neighValue; + double zero = itk::NumericTraits::Zero; + while (!outputIt.IsAtEnd()) { + //the weight is not zero + if (weightsIt.Get() != zero) { + //divide by the weight + outputIt.Set(static_cast(inputIt.Get()/weightsIt.Get())); } - void SetEdgePaddingValue(OutputPixelType value) - { - m_EdgePaddingValue = value; - this->Modified(); + + //copy the value of the neighbour that was just processed + else { + if(!outputIt.IsAtBegin()) { + //go back + --outputIt; + neighValue=outputIt.Get(); + ++outputIt; + outputIt.Set(neighValue); + } else { + //DD("is at begin, setting edgepadding value"); + outputIt.Set(m_EdgePaddingValue); + } } - - /** Typedef to describe the output image region type. */ - typedef typename OutputImageType::RegionType OutputImageRegionType; - - protected: - HelperClass2(); - ~HelperClass2(){}; - - - //the actual processing - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); - - - //member data - typename WeightsImageType::Pointer m_Weights; - OutputPixelType m_EdgePaddingValue; - } ; - - - - //========================================================================================================================= - //Member functions of the helper class 2 - //========================================================================================================================= - - - //========================================================================================================================= - //Empty constructor - template - HelperClass2::HelperClass2() - { - m_EdgePaddingValue=static_cast(0.0); - } - - - //========================================================================================================================= - //update the output for the outputRegionForThread - template void - HelperClass2::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) - { - - //Get pointer to the input - typename InputImageType::ConstPointer inputPtr = this->GetInput(); - - //Get pointer to the output - typename OutputImageType::Pointer outputPtr = this->GetOutput(); - - //Iterators over input, weigths and output - typedef itk::ImageRegionConstIterator InputImageIteratorType; - typedef itk::ImageRegionIterator OutputImageIteratorType; - typedef itk::ImageRegionIterator WeightsImageIteratorType; - - //define them over the outputRegionForThread - OutputImageIteratorType outputIt(outputPtr, outputRegionForThread); - InputImageIteratorType inputIt(inputPtr, outputRegionForThread); - WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread); - - - //================================================================================================== - //loop over the output and normalize the input, remove holes - OutputPixelType neighValue; - double zero = itk::NumericTraits::Zero; - while (!outputIt.IsAtEnd()) - { - //the weight is not zero - if (weightsIt.Get() != zero) - { - //divide by the weight - outputIt.Set(static_cast(inputIt.Get()/weightsIt.Get())); - } - - //copy the value of the neighbour that was just processed - else - { - if(!outputIt.IsAtBegin()) - { - //go back - --outputIt; - neighValue=outputIt.Get(); - ++outputIt; - outputIt.Set(neighValue); - } - else{ - //DD("is at begin, setting edgepadding value"); - outputIt.Set(m_EdgePaddingValue); - } - } - ++weightsIt; - ++outputIt; - ++inputIt; - - }//end while - }//end member - + ++weightsIt; + ++outputIt; + ++inputIt; + + }//end while +}//end member + }//end nameless namespace @@ -407,109 +388,107 @@ namespace namespace clitk { - //========================================================================================================================= - // The rest is the ForwardWarpImageFilter - //========================================================================================================================= - - //========================================================================================================================= - //constructor - template - ForwardWarpImageFilter::ForwardWarpImageFilter() - { - // mIsUpdated=false; - m_NumberOfThreadsIsGiven=false; - m_EdgePaddingValue=static_cast(0.0); - m_ThreadSafe=false; - m_Verbose=false; - } +//========================================================================================================================= +// The rest is the ForwardWarpImageFilter +//========================================================================================================================= +//========================================================================================================================= +//constructor +template +ForwardWarpImageFilter::ForwardWarpImageFilter() +{ + // mIsUpdated=false; + m_NumberOfThreadsIsGiven=false; + m_EdgePaddingValue=static_cast(0.0); + m_ThreadSafe=false; + m_Verbose=false; +} + + +//========================================================================================================================= +//Update +template +void ForwardWarpImageFilter::GenerateData() +{ + + //Get the properties of the input + typename InputImageType::ConstPointer inputPtr=this->GetInput(); + typename WeightsImageType::RegionType region; + typename WeightsImageType::RegionType::SizeType size=inputPtr->GetLargestPossibleRegion().GetSize(); + region.SetSize(size); + typename OutputImageType::IndexType start; + for (unsigned int i =0; i< ImageDimension ; i ++)start[i]=0; + region.SetIndex(start); + + //Allocate the weights + typename WeightsImageType::Pointer weights=ForwardWarpImageFilter::WeightsImageType::New(); + weights->SetRegions(region); + weights->Allocate(); + weights->SetSpacing(inputPtr->GetSpacing()); + + + //=========================================================================== + //warp is divided in in two loops, for each we call a threaded helper class + //1. Add contribution of input to output and update weights + //2. Normalize the output by the weight and remove holes + //=========================================================================== + + //=========================================================================== + //1. Add contribution of input to output and update weights + + //Define an internal image type in double precision + typedef itk::Image InternalImageType; + + //Call threaded helper class 1 + typedef HelperClass1 HelperClass1Type; + typename HelperClass1Type::Pointer helper1=HelperClass1Type::New(); + + //Set input + if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads); + helper1->SetInput(inputPtr); + helper1->SetDeformationField(m_DeformationField); + helper1->SetWeights(weights); + + //Threadsafe? + if(m_ThreadSafe) { + //Allocate the mutex image + typename MutexImageType::Pointer mutex=ForwardWarpImageFilter::MutexImageType::New(); + mutex->SetRegions(region); + mutex->Allocate(); + mutex->SetSpacing(inputPtr->GetSpacing()); + helper1->SetMutexImage(mutex); + if (m_Verbose) std::cout <<"Forwarp warping using a thread-safe algorithm" <Update(); + + //Get the output + typename InternalImageType::Pointer temp= helper1->GetOutput(); + + //For clarity + weights=helper1->GetWeights(); + + + //=========================================================================== + //2. Normalize the output by the weights and remove holes + //Call threaded helper class + typedef HelperClass2 HelperClass2Type; + typename HelperClass2Type::Pointer helper2=HelperClass2Type::New(); + + //Set temporary output as input + if(m_NumberOfThreadsIsGiven)helper2->SetNumberOfThreads(m_NumberOfThreads); + helper2->SetInput(temp); + helper2->SetWeights(weights); + helper2->SetEdgePaddingValue(m_EdgePaddingValue); + + //Execute helper class + helper2->Update(); + + //Set the output + this->SetNthOutput(0, helper2->GetOutput()); +} - //========================================================================================================================= - //Update - template - void ForwardWarpImageFilter::GenerateData() - { - - //Get the properties of the input - typename InputImageType::ConstPointer inputPtr=this->GetInput(); - typename WeightsImageType::RegionType region; - typename WeightsImageType::RegionType::SizeType size=inputPtr->GetLargestPossibleRegion().GetSize(); - region.SetSize(size); - typename OutputImageType::IndexType start; - for (unsigned int i =0; i< ImageDimension ;i ++)start[i]=0; - region.SetIndex(start); - - //Allocate the weights - typename WeightsImageType::Pointer weights=ForwardWarpImageFilter::WeightsImageType::New(); - weights->SetRegions(region); - weights->Allocate(); - weights->SetSpacing(inputPtr->GetSpacing()); - - - //=========================================================================== - //warp is divided in in two loops, for each we call a threaded helper class - //1. Add contribution of input to output and update weights - //2. Normalize the output by the weight and remove holes - //=========================================================================== - - //=========================================================================== - //1. Add contribution of input to output and update weights - - //Define an internal image type in double precision - typedef itk::Image InternalImageType; - - //Call threaded helper class 1 - typedef HelperClass1 HelperClass1Type; - typename HelperClass1Type::Pointer helper1=HelperClass1Type::New(); - - //Set input - if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads); - helper1->SetInput(inputPtr); - helper1->SetDeformationField(m_DeformationField); - helper1->SetWeights(weights); - - //Threadsafe? - if(m_ThreadSafe) - { - //Allocate the mutex image - typename MutexImageType::Pointer mutex=ForwardWarpImageFilter::MutexImageType::New(); - mutex->SetRegions(region); - mutex->Allocate(); - mutex->SetSpacing(inputPtr->GetSpacing()); - helper1->SetMutexImage(mutex); - if (m_Verbose) std::cout <<"Forwarp warping using a thread-safe algorithm" <Update(); - - //Get the output - typename InternalImageType::Pointer temp= helper1->GetOutput(); - - //For clarity - weights=helper1->GetWeights(); - - - //=========================================================================== - //2. Normalize the output by the weights and remove holes - //Call threaded helper class - typedef HelperClass2 HelperClass2Type; - typename HelperClass2Type::Pointer helper2=HelperClass2Type::New(); - - //Set temporary output as input - if(m_NumberOfThreadsIsGiven)helper2->SetNumberOfThreads(m_NumberOfThreads); - helper2->SetInput(temp); - helper2->SetWeights(weights); - helper2->SetEdgePaddingValue(m_EdgePaddingValue); - - //Execute helper class - helper2->Update(); - - //Set the output - this->SetNthOutput(0, helper2->GetOutput()); - } - } #endif diff --git a/itk/clitkGenericInterpolator.txx b/itk/clitkGenericInterpolator.txx index 072d3c6..c401e8f 100644 --- a/itk/clitkGenericInterpolator.txx +++ b/itk/clitkGenericInterpolator.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -15,7 +15,7 @@ - BSD See included LICENSE.txt file - CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html ======================================================================-====*/ -#ifndef __clitkGenericInterpolator_txx +#ifndef __clitkGenericInterpolator_txx #define __clitkGenericInterpolator_txx #include "clitkGenericInterpolator.h" @@ -23,69 +23,66 @@ namespace clitk { - //========================================================================================================================= - //constructor - template - GenericInterpolator::GenericInterpolator() - { - m_Interpolator=NULL; - m_Verbose=false; +//========================================================================================================================= +//constructor +template +GenericInterpolator::GenericInterpolator() +{ + m_Interpolator=NULL; + m_Verbose=false; +} + + +//========================================================================================================================= +//Get the pointer +template +typename GenericInterpolator::InterpolatorPointer +GenericInterpolator::GetInterpolatorPointer() +{ + //============================================================================ + // We retrieve the type of interpolation from the command line + //============================================================================ + typename InterpolatorType::Pointer interpolator; + + switch ( m_ArgsInfo.interp_arg ) { + case 0: + + interpolator= itk::NearestNeighborInterpolateImageFunction< ImageType,TCoordRep >::New(); + if (m_Verbose) std::cout<<"Using nearestneighbor interpolation..."<::New(); + if (m_Verbose) std::cout<<"Using linear interpolation..."<::Pointer m =itk::BSplineInterpolateImageFunction< ImageType,TCoordRep >::New(); + m->SetSplineOrder(m_ArgsInfo.interpOrder_arg); + interpolator=m; + if (m_Verbose) std::cout<<"Using Bspline interpolation..."< - typename GenericInterpolator::InterpolatorPointer - GenericInterpolator::GetInterpolatorPointer() - { - //============================================================================ - // We retrieve the type of interpolation from the command line - //============================================================================ - typename InterpolatorType::Pointer interpolator; - - switch ( m_ArgsInfo.interp_arg ) - { - case 0: - - interpolator= itk::NearestNeighborInterpolateImageFunction< ImageType,TCoordRep >::New(); - if (m_Verbose) std::cout<<"Using nearestneighbor interpolation..."<::New(); - if (m_Verbose) std::cout<<"Using linear interpolation..."<::Pointer m =itk::BSplineInterpolateImageFunction< ImageType,TCoordRep >::New(); - m->SetSplineOrder(m_ArgsInfo.interpOrder_arg); - interpolator=m; - if (m_Verbose) std::cout<<"Using Bspline interpolation..."<::Pointer m =itk::BSplineInterpolateImageFunctionWithLUT< ImageType,TCoordRep >::New(); - m->SetSplineOrder(m_ArgsInfo.interpOrder_arg); - m->SetLUTSamplingFactor(m_ArgsInfo.interpSF_arg); - interpolator=m; - if (m_Verbose) std::cout<<"Using BLUT interpolation..."<::Pointer m =itk::BSplineInterpolateImageFunctionWithLUT< ImageType,TCoordRep >::New(); + m->SetSplineOrder(m_ArgsInfo.interpOrder_arg); + m->SetLUTSamplingFactor(m_ArgsInfo.interpSF_arg); + interpolator=m; + if (m_Verbose) std::cout<<"Using BLUT interpolation..."< - GenericVectorInterpolator::GenericVectorInterpolator() - { - m_Interpolator=NULL; - m_Verbose=false; +//========================================================================================================================= +//constructor +template +GenericVectorInterpolator::GenericVectorInterpolator() +{ + m_Interpolator=NULL; + m_Verbose=false; +} + + +//========================================================================================================================= +//Get the pointer +template +typename GenericVectorInterpolator::InterpolatorPointer +GenericVectorInterpolator::GetInterpolatorPointer() +{ + //============================================================================ + // We retrieve the type of interpolation from the command line + //============================================================================ + typename InterpolatorType::Pointer interpolator; + + switch ( m_ArgsInfo.interpVF_arg ) { + case 0: + + interpolator= itk::VectorNearestNeighborInterpolateImageFunction< ImageType,TCoordRep >::New(); + if (m_Verbose) std::cout<<"Using nearestneighbor interpolation..."<::New(); + if (m_Verbose) std::cout<<"Using linear interpolation..."<::Pointer m =clitk::VectorBSplineInterpolateImageFunction< ImageType,TCoordRep >::New(); + m->SetSplineOrder(m_ArgsInfo.interpVFOrder_arg); + interpolator=m; + if (m_Verbose) std::cout<<"Using Bspline interpolation..."< - typename GenericVectorInterpolator::InterpolatorPointer - GenericVectorInterpolator::GetInterpolatorPointer() - { - //============================================================================ - // We retrieve the type of interpolation from the command line - //============================================================================ - typename InterpolatorType::Pointer interpolator; - - switch ( m_ArgsInfo.interpVF_arg ) - { - case 0: - - interpolator= itk::VectorNearestNeighborInterpolateImageFunction< ImageType,TCoordRep >::New(); - if (m_Verbose) std::cout<<"Using nearestneighbor interpolation..."<::New(); - if (m_Verbose) std::cout<<"Using linear interpolation..."<::Pointer m =clitk::VectorBSplineInterpolateImageFunction< ImageType,TCoordRep >::New(); - m->SetSplineOrder(m_ArgsInfo.interpVFOrder_arg); - interpolator=m; - if (m_Verbose) std::cout<<"Using Bspline interpolation..."<::Pointer m =clitk::VectorBSplineInterpolateImageFunctionWithLUT< ImageType,TCoordRep >::New(); - m->SetSplineOrder(m_ArgsInfo.interpVFOrder_arg); - m->SetLUTSamplingFactor(m_ArgsInfo.interpVFSF_arg); - interpolator=m; - if (m_Verbose) std::cout<<"Using BLUT interpolation..."<::Pointer m =clitk::VectorBSplineInterpolateImageFunctionWithLUT< ImageType,TCoordRep >::New(); + m->SetSplineOrder(m_ArgsInfo.interpVFOrder_arg); + m->SetLUTSamplingFactor(m_ArgsInfo.interpVFSF_arg); + interpolator=m; + if (m_Verbose) std::cout<<"Using BLUT interpolation..."< class ITK_EXPORT HelperClass1 : public itk::ImageToImageFilter - { - - public: - /** Standard class typedefs. */ - typedef HelperClass1 Self; - typedef itk::ImageToImageFilter Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods) */ - itkTypeMacro( HelperClass1, ImageToImageFilter ); - - /** Constants for the image dimensions */ - itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); - - - //Typedefs - typedef typename OutputImageType::PixelType PixelType; - typedef itk::Image WeightsImageType; - typedef itk::Image MutexImageType; - - //=================================================================================== - //Set methods - void SetWeights(const typename WeightsImageType::Pointer input) - { - m_Weights = input; - this->Modified(); - } - void SetMutexImage(const typename MutexImageType::Pointer input) - { - m_MutexImage=input; - this->Modified(); - m_ThreadSafe=true; - } - - //Get methods - typename WeightsImageType::Pointer GetWeights(){return m_Weights;} - - /** Typedef to describe the output image region type. */ - typedef typename OutputImageType::RegionType OutputImageRegionType; - - protected: - HelperClass1(); - ~HelperClass1(){}; - - //the actual processing - void BeforeThreadedGenerateData(); - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); +//========================================================================================================================= +//helper class 1 to allow a threaded execution: add contributions of input to output and update weights +//========================================================================================================================= +template class ITK_EXPORT HelperClass1 : public itk::ImageToImageFilter +{ - //member data - typename WeightsImageType::Pointer m_Weights; - typename MutexImageType::Pointer m_MutexImage; - bool m_ThreadSafe; +public: + /** Standard class typedefs. */ + typedef HelperClass1 Self; + typedef itk::ImageToImageFilter Superclass; + typedef itk::SmartPointer Pointer; + typedef itk::SmartPointer ConstPointer; - }; + /** Method for creation through the object factory. */ + itkNewMacro(Self); + /** Run-time type information (and related methods) */ + itkTypeMacro( HelperClass1, ImageToImageFilter ); + /** Constants for the image dimensions */ + itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); - //========================================================================================================================= - //Member functions of the helper class 1 - //========================================================================================================================= + //Typedefs + typedef typename OutputImageType::PixelType PixelType; + typedef itk::Image WeightsImageType; + typedef itk::Image MutexImageType; - //========================================================================================================================= - //Empty constructor - template - HelperClass1::HelperClass1() - { - m_ThreadSafe=false; + //=================================================================================== + //Set methods + void SetWeights(const typename WeightsImageType::Pointer input) { + m_Weights = input; + this->Modified(); + } + void SetMutexImage(const typename MutexImageType::Pointer input) { + m_MutexImage=input; + this->Modified(); + m_ThreadSafe=true; } - //========================================================================================================================= - //Before threaded data - template - void HelperClass1::BeforeThreadedGenerateData() - { - //Since we will add, put to zero! - this->GetOutput()->FillBuffer(itk::NumericTraits::Zero); - this->GetWeights()->FillBuffer(itk::NumericTraits::Zero); + //Get methods + typename WeightsImageType::Pointer GetWeights() { + return m_Weights; } - //========================================================================================================================= - //update the output for the outputRegionForThread - template - void HelperClass1::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) - { - - //Get pointer to the input - typename InputImageType::ConstPointer inputPtr = this->GetInput(); - - //Get pointer to the output - typename OutputImageType::Pointer outputPtr = this->GetOutput(); - typename OutputImageType::SizeType size=outputPtr->GetLargestPossibleRegion().GetSize(); - - //Iterator over input - typedef itk::ImageRegionConstIteratorWithIndex InputImageIteratorType; - - //define them over the outputRegionForThread - InputImageIteratorType inputIt(inputPtr, outputRegionForThread); - - //Initialize - typename InputImageType::IndexType index; - itk::ContinuousIndex contIndex; - typename InputImageType::PointType ipoint; - typename OutputImageType::PointType opoint; - typedef typename OutputImageType::PixelType DisplacementType; - DisplacementType displacement; - inputIt.GoToBegin(); - - //define some temp variables - signed long baseIndex[ImageDimension]; - double distance[ImageDimension]; - unsigned int dim, counter, upper; - double totalOverlap,overlap; - typename OutputImageType::IndexType neighIndex; - - //Find the number of neighbors - unsigned int neighbors = 1 << ImageDimension; - - //================================================================================================== - //Loop over the region and add the intensities to the output and the weight to the weights - //================================================================================================== - while( !inputIt.IsAtEnd() ) - { - // get the input image index - index = inputIt.GetIndex(); - inputPtr->TransformIndexToPhysicalPoint( index,ipoint ); - - // get the required displacement - displacement = inputIt.Get(); - - // compute the required output image point - for(unsigned int j = 0; j < ImageDimension; j++ ) opoint[j] = ipoint[j] + (double)displacement[j]; - - // Update the output and the weights - if(outputPtr->TransformPhysicalPointToContinuousIndex(opoint, contIndex ) ) - { - for(dim = 0; dim < ImageDimension; dim++) - { - // The following block is equivalent to the following line without - // having to call floor. (Only for positive inputs, we already now that is in the image) - // baseIndex[dim] = (long) vcl_floor(contIndex[dim] ); - - baseIndex[dim] = (long) contIndex[dim]; - distance[dim] = contIndex[dim] - double( baseIndex[dim] ); - } - - //Add contribution for each neighbor - totalOverlap = itk::NumericTraits::Zero; - for( counter = 0; counter < neighbors ; counter++ ) - { - overlap = 1.0; // fraction overlap - upper = counter; // each bit indicates upper/lower neighbour - - // get neighbor index and overlap fraction - for( dim = 0; dim < 3; dim++ ) - { - if ( upper & 1 ) - { - neighIndex[dim] = baseIndex[dim] + 1; - overlap *= distance[dim]; - } - else - { - neighIndex[dim] = baseIndex[dim]; - overlap *= 1.0 - distance[dim]; - } - upper >>= 1; - } - - - - //Set neighbor value only if overlap is not zero - if( (overlap>0.0)) // && - // (static_cast(neighIndex[0])(neighIndex[1])(neighIndex[2])=0) && - // (neighIndex[1]>=0) && - // (neighIndex[2]>=0) ) - { - //what to store? the original displacement vector? - if (! m_ThreadSafe) - { - //Set the pixel and weight at neighIndex - outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap)); - m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); - } - - else - { - //Entering critilal section: shared memory - m_MutexImage->GetPixel(neighIndex).Lock(); - - //Set the pixel and weight at neighIndex - outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap)); - m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); - - //Unlock - m_MutexImage->GetPixel(neighIndex).Unlock(); - - } - //Add to total overlap - totalOverlap += overlap; - } - - if( totalOverlap == 1.0 ) - { - // finished - break; - } - } - } - - ++inputIt; + /** Typedef to describe the output image region type. */ + typedef typename OutputImageType::RegionType OutputImageRegionType; + +protected: + HelperClass1(); + ~HelperClass1() {}; + + //the actual processing + void BeforeThreadedGenerateData(); + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); + + //member data + typename WeightsImageType::Pointer m_Weights; + typename MutexImageType::Pointer m_MutexImage; + bool m_ThreadSafe; + +}; + + + +//========================================================================================================================= +//Member functions of the helper class 1 +//========================================================================================================================= + + +//========================================================================================================================= +//Empty constructor +template +HelperClass1::HelperClass1() +{ + m_ThreadSafe=false; +} + +//========================================================================================================================= +//Before threaded data +template +void HelperClass1::BeforeThreadedGenerateData() +{ + //Since we will add, put to zero! + this->GetOutput()->FillBuffer(itk::NumericTraits::Zero); + this->GetWeights()->FillBuffer(itk::NumericTraits::Zero); +} + +//========================================================================================================================= +//update the output for the outputRegionForThread +template +void HelperClass1::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) +{ + + //Get pointer to the input + typename InputImageType::ConstPointer inputPtr = this->GetInput(); + + //Get pointer to the output + typename OutputImageType::Pointer outputPtr = this->GetOutput(); + typename OutputImageType::SizeType size=outputPtr->GetLargestPossibleRegion().GetSize(); + + //Iterator over input + typedef itk::ImageRegionConstIteratorWithIndex InputImageIteratorType; + + //define them over the outputRegionForThread + InputImageIteratorType inputIt(inputPtr, outputRegionForThread); + + //Initialize + typename InputImageType::IndexType index; + itk::ContinuousIndex contIndex; + typename InputImageType::PointType ipoint; + typename OutputImageType::PointType opoint; + typedef typename OutputImageType::PixelType DisplacementType; + DisplacementType displacement; + inputIt.GoToBegin(); + + //define some temp variables + signed long baseIndex[ImageDimension]; + double distance[ImageDimension]; + unsigned int dim, counter, upper; + double totalOverlap,overlap; + typename OutputImageType::IndexType neighIndex; + + //Find the number of neighbors + unsigned int neighbors = 1 << ImageDimension; + + //================================================================================================== + //Loop over the region and add the intensities to the output and the weight to the weights + //================================================================================================== + while( !inputIt.IsAtEnd() ) { + // get the input image index + index = inputIt.GetIndex(); + inputPtr->TransformIndexToPhysicalPoint( index,ipoint ); + + // get the required displacement + displacement = inputIt.Get(); + + // compute the required output image point + for(unsigned int j = 0; j < ImageDimension; j++ ) opoint[j] = ipoint[j] + (double)displacement[j]; + + // Update the output and the weights + if(outputPtr->TransformPhysicalPointToContinuousIndex(opoint, contIndex ) ) { + for(dim = 0; dim < ImageDimension; dim++) { + // The following block is equivalent to the following line without + // having to call floor. (Only for positive inputs, we already now that is in the image) + // baseIndex[dim] = (long) vcl_floor(contIndex[dim] ); + + baseIndex[dim] = (long) contIndex[dim]; + distance[dim] = contIndex[dim] - double( baseIndex[dim] ); + } + + //Add contribution for each neighbor + totalOverlap = itk::NumericTraits::Zero; + for( counter = 0; counter < neighbors ; counter++ ) { + overlap = 1.0; // fraction overlap + upper = counter; // each bit indicates upper/lower neighbour + + // get neighbor index and overlap fraction + for( dim = 0; dim < 3; dim++ ) { + if ( upper & 1 ) { + neighIndex[dim] = baseIndex[dim] + 1; + overlap *= distance[dim]; + } else { + neighIndex[dim] = baseIndex[dim]; + overlap *= 1.0 - distance[dim]; + } + upper >>= 1; + } + + + + //Set neighbor value only if overlap is not zero + if( (overlap>0.0)) // && + // (static_cast(neighIndex[0])(neighIndex[1])(neighIndex[2])=0) && + // (neighIndex[1]>=0) && + // (neighIndex[2]>=0) ) + { + //what to store? the original displacement vector? + if (! m_ThreadSafe) { + //Set the pixel and weight at neighIndex + outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap)); + m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); + } + + else { + //Entering critilal section: shared memory + m_MutexImage->GetPixel(neighIndex).Lock(); + + //Set the pixel and weight at neighIndex + outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) - (displacement*overlap)); + m_Weights->SetPixel(neighIndex, m_Weights->GetPixel(neighIndex) + overlap); + + //Unlock + m_MutexImage->GetPixel(neighIndex).Unlock(); + + } + //Add to total overlap + totalOverlap += overlap; + } + + if( totalOverlap == 1.0 ) { + // finished + break; + } } + } + ++inputIt; } +} - //========================================================================================================================= - //helper class 2 to allow a threaded execution of normalisation by the weights - //========================================================================================================================= - template class HelperClass2 : public itk::ImageToImageFilter - { - - public: - /** Standard class typedefs. */ - typedef HelperClass2 Self; - typedef itk::ImageToImageFilter Superclass; - typedef itk::SmartPointer Pointer; - typedef itk::SmartPointer ConstPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** Run-time type information (and related methods) */ - itkTypeMacro( HelperClass2, ImageToImageFilter ); - - /** Constants for the image dimensions */ - itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); - - //Typedefs - typedef typename OutputImageType::PixelType PixelType; - typedef itk::Image WeightsImageType; - - //Set methods - void SetWeights(const typename WeightsImageType::Pointer input) - { - m_Weights = input; - this->Modified(); - } - void SetEdgePaddingValue(PixelType value) - { - m_EdgePaddingValue = value; - this->Modified(); - } - /** Typedef to describe the output image region type. */ - typedef typename OutputImageType::RegionType OutputImageRegionType; - - protected: - HelperClass2(); - ~HelperClass2(){}; - - - //the actual processing - void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); +//========================================================================================================================= +//helper class 2 to allow a threaded execution of normalisation by the weights +//========================================================================================================================= +template class HelperClass2 : public itk::ImageToImageFilter +{ +public: + /** Standard class typedefs. */ + typedef HelperClass2 Self; + typedef itk::ImageToImageFilter Superclass; + typedef itk::SmartPointer Pointer; + typedef itk::SmartPointer ConstPointer; - //member data - typename WeightsImageType::Pointer m_Weights; - PixelType m_EdgePaddingValue; + /** Method for creation through the object factory. */ + itkNewMacro(Self); - } ; + /** Run-time type information (and related methods) */ + itkTypeMacro( HelperClass2, ImageToImageFilter ); + /** Constants for the image dimensions */ + itkStaticConstMacro(ImageDimension, unsigned int,InputImageType::ImageDimension); + //Typedefs + typedef typename OutputImageType::PixelType PixelType; + typedef itk::Image WeightsImageType; - //========================================================================================================================= - //Member functions of the helper class 2 - //========================================================================================================================= - - - //========================================================================================================================= - //Empty constructor - template HelperClass2::HelperClass2() - { - m_EdgePaddingValue=itk::NumericTraits::Zero; + //Set methods + void SetWeights(const typename WeightsImageType::Pointer input) { + m_Weights = input; + this->Modified(); + } + void SetEdgePaddingValue(PixelType value) { + m_EdgePaddingValue = value; + this->Modified(); } - - - //========================================================================================================================= - //update the output for the outputRegionForThread - template void HelperClass2::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) - { - - //Get pointer to the input - typename InputImageType::ConstPointer inputPtr = this->GetInput(); - - //Get pointer to the output - typename OutputImageType::Pointer outputPtr = this->GetOutput(); - - //Iterators over input, weigths and output - typedef itk::ImageRegionConstIterator InputImageIteratorType; - typedef itk::ImageRegionIterator OutputImageIteratorType; - typedef itk::ImageRegionIterator WeightsImageIteratorType; - - //define them over the outputRegionForThread - OutputImageIteratorType outputIt(outputPtr, outputRegionForThread); - InputImageIteratorType inputIt(inputPtr, outputRegionForThread); - WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread); - - - //================================================================================================== - //loop over the output and normalize the input, remove holes - PixelType neighValue; - double zero = itk::NumericTraits::Zero; - while (!outputIt.IsAtEnd()) - { - //the weight is not zero - if (weightsIt.Get() != zero) - { - //divide by the weight - outputIt.Set(static_cast(inputIt.Get()/weightsIt.Get())); - } - - //copy the value of the neighbour that was just processed - else - { - if(!outputIt.IsAtBegin()) - { - //go back - --outputIt; - - //Neighbour cannot have zero weight because it should be filled already - neighValue=outputIt.Get(); - ++outputIt; - outputIt.Set(neighValue); - //DD("hole filled"); - } - else{ - //DD("is at begin, setting edgepadding value"); - outputIt.Set(m_EdgePaddingValue); - } - } - ++weightsIt; - ++outputIt; - ++inputIt; - - }//end while - }//end member + /** Typedef to describe the output image region type. */ + typedef typename OutputImageType::RegionType OutputImageRegionType; -}//end nameless namespace +protected: + HelperClass2(); + ~HelperClass2() {}; + //the actual processing + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ); -namespace clitk + + //member data + typename WeightsImageType::Pointer m_Weights; + PixelType m_EdgePaddingValue; + +} ; + + + +//========================================================================================================================= +//Member functions of the helper class 2 +//========================================================================================================================= + + +//========================================================================================================================= +//Empty constructor +template HelperClass2::HelperClass2() { + m_EdgePaddingValue=itk::NumericTraits::Zero; +} - //========================================================================================================================= - // The rest is the InvertVFFilter - //========================================================================================================================= - - //========================================================================================================================= - //constructor - template - InvertVFFilter::InvertVFFilter() - { - m_EdgePaddingValue=itk::NumericTraits::Zero; //no other reasonable value? - m_ThreadSafe=false; - m_Verbose=false; - } +//========================================================================================================================= +//update the output for the outputRegionForThread +template void HelperClass2::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, int threadId ) +{ - //========================================================================================================================= - //Update - template void InvertVFFilter::GenerateData() - { - - //Get the properties of the input - typename InputImageType::ConstPointer inputPtr=this->GetInput(); - typename WeightsImageType::RegionType region; - typename WeightsImageType::RegionType::SizeType size=inputPtr->GetLargestPossibleRegion().GetSize(); - region.SetSize(size); - typename OutputImageType::IndexType start; - for (unsigned int i=0; i< ImageDimension; i++) start[i]=0; - region.SetIndex(start); - PixelType zero = itk::NumericTraits::Zero; - - - //Allocate the weights - typename WeightsImageType::Pointer weights=WeightsImageType::New(); - weights->SetRegions(region); - weights->Allocate(); - weights->SetSpacing(inputPtr->GetSpacing()); - - //=========================================================================== - //Inversion is divided in in two loops, for each we will call a threaded helper class - //1. add contribution of input to output and update weights - //2. normalize the output by the weight and remove holes - //=========================================================================== - - - //=========================================================================== - //1. add contribution of input to output and update weights - - //Define an internal image type - - typedef itk::Image, ImageDimension > InternalImageType; - - //Call threaded helper class 1 - typedef HelperClass1 HelperClass1Type; - typename HelperClass1Type::Pointer helper1=HelperClass1Type::New(); - - //Set input - if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads); - helper1->SetInput(inputPtr); - helper1->SetWeights(weights); - - //Threadsafe? - if(m_ThreadSafe) - { - //Allocate the mutex image - typename MutexImageType::Pointer mutex=InvertVFFilter::MutexImageType::New(); - mutex->SetRegions(region); - mutex->Allocate(); - mutex->SetSpacing(inputPtr->GetSpacing()); - helper1->SetMutexImage(mutex); - if (m_Verbose) std::cout <<"Inverting using a thread-safe algorithm" <GetInput(); + + //Get pointer to the output + typename OutputImageType::Pointer outputPtr = this->GetOutput(); + + //Iterators over input, weigths and output + typedef itk::ImageRegionConstIterator InputImageIteratorType; + typedef itk::ImageRegionIterator OutputImageIteratorType; + typedef itk::ImageRegionIterator WeightsImageIteratorType; + + //define them over the outputRegionForThread + OutputImageIteratorType outputIt(outputPtr, outputRegionForThread); + InputImageIteratorType inputIt(inputPtr, outputRegionForThread); + WeightsImageIteratorType weightsIt(m_Weights, outputRegionForThread); + + + //================================================================================================== + //loop over the output and normalize the input, remove holes + PixelType neighValue; + double zero = itk::NumericTraits::Zero; + while (!outputIt.IsAtEnd()) { + //the weight is not zero + if (weightsIt.Get() != zero) { + //divide by the weight + outputIt.Set(static_cast(inputIt.Get()/weightsIt.Get())); + } + + //copy the value of the neighbour that was just processed + else { + if(!outputIt.IsAtBegin()) { + //go back + --outputIt; + + //Neighbour cannot have zero weight because it should be filled already + neighValue=outputIt.Get(); + ++outputIt; + outputIt.Set(neighValue); + //DD("hole filled"); + } else { + //DD("is at begin, setting edgepadding value"); + outputIt.Set(m_EdgePaddingValue); } - else if(m_Verbose)std::cout <<"Inverting using a thread-unsafe algorithm" <Update(); + }//end while +}//end member - //Get the output - typename InternalImageType::Pointer temp= helper1->GetOutput(); - weights=helper1->GetWeights(); +}//end nameless namespace + + + +namespace clitk +{ + +//========================================================================================================================= +// The rest is the InvertVFFilter +//========================================================================================================================= + +//========================================================================================================================= +//constructor +template +InvertVFFilter::InvertVFFilter() +{ + m_EdgePaddingValue=itk::NumericTraits::Zero; //no other reasonable value? + m_ThreadSafe=false; + m_Verbose=false; +} + + +//========================================================================================================================= +//Update +template void InvertVFFilter::GenerateData() +{ + + //Get the properties of the input + typename InputImageType::ConstPointer inputPtr=this->GetInput(); + typename WeightsImageType::RegionType region; + typename WeightsImageType::RegionType::SizeType size=inputPtr->GetLargestPossibleRegion().GetSize(); + region.SetSize(size); + typename OutputImageType::IndexType start; + for (unsigned int i=0; i< ImageDimension; i++) start[i]=0; + region.SetIndex(start); + PixelType zero = itk::NumericTraits::Zero; + + + //Allocate the weights + typename WeightsImageType::Pointer weights=WeightsImageType::New(); + weights->SetRegions(region); + weights->Allocate(); + weights->SetSpacing(inputPtr->GetSpacing()); + + //=========================================================================== + //Inversion is divided in in two loops, for each we will call a threaded helper class + //1. add contribution of input to output and update weights + //2. normalize the output by the weight and remove holes + //=========================================================================== + + + //=========================================================================== + //1. add contribution of input to output and update weights + + //Define an internal image type + + typedef itk::Image, ImageDimension > InternalImageType; + + //Call threaded helper class 1 + typedef HelperClass1 HelperClass1Type; + typename HelperClass1Type::Pointer helper1=HelperClass1Type::New(); + + //Set input + if(m_NumberOfThreadsIsGiven)helper1->SetNumberOfThreads(m_NumberOfThreads); + helper1->SetInput(inputPtr); + helper1->SetWeights(weights); + + //Threadsafe? + if(m_ThreadSafe) { + //Allocate the mutex image + typename MutexImageType::Pointer mutex=InvertVFFilter::MutexImageType::New(); + mutex->SetRegions(region); + mutex->Allocate(); + mutex->SetSpacing(inputPtr->GetSpacing()); + helper1->SetMutexImage(mutex); + if (m_Verbose) std::cout <<"Inverting using a thread-safe algorithm" <Update(); + + //Get the output + typename InternalImageType::Pointer temp= helper1->GetOutput(); + weights=helper1->GetWeights(); + + + //=========================================================================== + //2. Normalize the output by the weights and remove holes + //Call threaded helper class + typedef HelperClass2 HelperClass2Type; + typename HelperClass2Type::Pointer helper2=HelperClass2Type::New(); + + //Set temporary output as input + helper2->SetInput(temp); + helper2->SetWeights(weights); + helper2->SetEdgePaddingValue(m_EdgePaddingValue); + + //Execute helper class + if (m_Verbose) std::cout << "Normalizing the output VF..."<Update(); + + //Set the output + this->SetNthOutput(0, helper2->GetOutput()); +} - //=========================================================================== - //2. Normalize the output by the weights and remove holes - //Call threaded helper class - typedef HelperClass2 HelperClass2Type; - typename HelperClass2Type::Pointer helper2=HelperClass2Type::New(); - - //Set temporary output as input - helper2->SetInput(temp); - helper2->SetWeights(weights); - helper2->SetEdgePaddingValue(m_EdgePaddingValue); - //Execute helper class - if (m_Verbose) std::cout << "Normalizing the output VF..."<Update(); - //Set the output - this->SetNthOutput(0, helper2->GetOutput()); - } - - - } #endif diff --git a/itk/clitkResampleImageWithOptionsFilter.txx b/itk/clitkResampleImageWithOptionsFilter.txx index aee15f5..dd5a821 100644 --- a/itk/clitkResampleImageWithOptionsFilter.txx +++ b/itk/clitkResampleImageWithOptionsFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -33,265 +33,267 @@ #include "itkBSplineInterpolateImageFunctionWithLUT.h" #include "itkCommand.h" -namespace clitk { +namespace clitk +{ - //-------------------------------------------------------------------- - template - ResampleImageWithOptionsFilter:: - ResampleImageWithOptionsFilter():itk::ImageToImageFilter() { - static const unsigned int dim = InputImageType::ImageDimension; - this->SetNumberOfRequiredInputs(1); - m_OutputIsoSpacing = -1; - m_InterpolationType = NearestNeighbor; - m_GaussianFilteringEnabled = true; - m_BSplineOrder = 3; - m_BLUTSamplingFactor = 20; - m_LastDimensionIsTime = false; - m_Transform = TransformType::New(); - if (dim == 4) m_LastDimensionIsTime = true; // by default 4D is 3D+t - for(unsigned int i=0; i +ResampleImageWithOptionsFilter:: +ResampleImageWithOptionsFilter():itk::ImageToImageFilter() +{ + static const unsigned int dim = InputImageType::ImageDimension; + this->SetNumberOfRequiredInputs(1); + m_OutputIsoSpacing = -1; + m_InterpolationType = NearestNeighbor; + m_GaussianFilteringEnabled = true; + m_BSplineOrder = 3; + m_BLUTSamplingFactor = 20; + m_LastDimensionIsTime = false; + m_Transform = TransformType::New(); + if (dim == 4) m_LastDimensionIsTime = true; // by default 4D is 3D+t + for(unsigned int i=0; i - void - ResampleImageWithOptionsFilter:: - SetInput(const InputImageType * image) { - // Process object is not const-correct so the const casting is required. - this->SetNthInput(0, const_cast(image)); - } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - template - void - ResampleImageWithOptionsFilter:: - GenerateInputRequestedRegion() { - // call the superclass's implementation of this method - Superclass::GenerateInputRequestedRegion(); - - // get pointers to the input and output - InputImagePointer inputPtr = - const_cast< TInputImage *>( this->GetInput() ); - - // Request the entire input image - InputImageRegionType inputRegion; - inputRegion = inputPtr->GetLargestPossibleRegion(); - inputPtr->SetRequestedRegion(inputRegion); - } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - template - void - ResampleImageWithOptionsFilter:: - GenerateOutputInformation() { - static const unsigned int dim = InputImageType::ImageDimension; - - // Warning - if (!std::numeric_limits::is_signed) { - if ((m_InterpolationType == BSpline) || - (m_InterpolationType == B_LUT)) { - std::cerr << "Warning : input pixel type is not signed, use bspline interpolation at your own risk ..." << std::endl; - } +//-------------------------------------------------------------------- +template +void +ResampleImageWithOptionsFilter:: +SetInput(const InputImageType * image) +{ + // Process object is not const-correct so the const casting is required. + this->SetNthInput(0, const_cast(image)); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +void +ResampleImageWithOptionsFilter:: +GenerateInputRequestedRegion() +{ + // call the superclass's implementation of this method + Superclass::GenerateInputRequestedRegion(); + + // get pointers to the input and output + InputImagePointer inputPtr = + const_cast< TInputImage *>( this->GetInput() ); + + // Request the entire input image + InputImageRegionType inputRegion; + inputRegion = inputPtr->GetLargestPossibleRegion(); + inputPtr->SetRequestedRegion(inputRegion); +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +void +ResampleImageWithOptionsFilter:: +GenerateOutputInformation() +{ + static const unsigned int dim = InputImageType::ImageDimension; + + // Warning + if (!std::numeric_limits::is_signed) { + if ((m_InterpolationType == BSpline) || + (m_InterpolationType == B_LUT)) { + std::cerr << "Warning : input pixel type is not signed, use bspline interpolation at your own risk ..." << std::endl; } + } + + // Get input pointer + InputImagePointer input = dynamic_cast(itk::ProcessObject::GetInput(0)); - // Get input pointer - InputImagePointer input = dynamic_cast(itk::ProcessObject::GetInput(0)); - - // Perform default implementation - Superclass::GenerateOutputInformation(); + // Perform default implementation + Superclass::GenerateOutputInformation(); - // Compute sizes - InputImageSpacingType inputSpacing = input->GetSpacing(); - InputImageSizeType inputSize = input->GetLargestPossibleRegion().GetSize(); + // Compute sizes + InputImageSpacingType inputSpacing = input->GetSpacing(); + InputImageSizeType inputSize = input->GetLargestPossibleRegion().GetSize(); - if (m_OutputIsoSpacing != -1) { // apply isoSpacing + if (m_OutputIsoSpacing != -1) { // apply isoSpacing + for(unsigned int i=0; iGetOutput(0); - OutputImageRegionType region; - region.SetSize(m_OutputSize); - region.SetIndex(input->GetLargestPossibleRegion().GetIndex()); - DD(input->GetLargestPossibleRegion().GetIndex()); - outputImage->SetLargestPossibleRegion(region); - outputImage->SetSpacing(m_OutputSpacing); - - // Init Gaussian sigma - if (m_GaussianSigma[0] != -1) { // Gaussian filter set by user - m_GaussianFilteringEnabled = true; - } - else { - if (m_GaussianFilteringEnabled) { // Automated sigma when downsample - for(unsigned int i=0; i inputSpacing[i]) { // downsample - m_GaussianSigma[i] = 0.5*m_OutputSpacing[i];// / inputSpacing[i]); - } - else m_GaussianSigma[i] = 0; // will be ignore after - } + // Special case for temporal image 2D+t or 3D+t + if (m_LastDimensionIsTime) { + int l = dim-1; + m_OutputSize[l] = inputSize[l]; + m_OutputSpacing[l] = inputSpacing[l]; + } + + // Set Size/Spacing + OutputImagePointer outputImage = this->GetOutput(0); + OutputImageRegionType region; + region.SetSize(m_OutputSize); + region.SetIndex(input->GetLargestPossibleRegion().GetIndex()); + DD(input->GetLargestPossibleRegion().GetIndex()); + outputImage->SetLargestPossibleRegion(region); + outputImage->SetSpacing(m_OutputSpacing); + + // Init Gaussian sigma + if (m_GaussianSigma[0] != -1) { // Gaussian filter set by user + m_GaussianFilteringEnabled = true; + } else { + if (m_GaussianFilteringEnabled) { // Automated sigma when downsample + for(unsigned int i=0; i inputSpacing[i]) { // downsample + m_GaussianSigma[i] = 0.5*m_OutputSpacing[i];// / inputSpacing[i]); + } else m_GaussianSigma[i] = 0; // will be ignore after } } - if (m_GaussianFilteringEnabled && m_LastDimensionIsTime) { - m_GaussianSigma[dim-1] = 0; - } } - //-------------------------------------------------------------------- - - - //-------------------------------------------------------------------- - template - void - ResampleImageWithOptionsFilter:: - GenerateData() { - - // Get input pointer - InputImagePointer input = dynamic_cast(itk::ProcessObject::GetInput(0)); - static const unsigned int dim = InputImageType::ImageDimension; - - // Create main Resample Image Filter - typedef itk::ResampleImageFilter FilterType; - typename FilterType::Pointer filter = FilterType::New(); - filter->GraftOutput(this->GetOutput()); + if (m_GaussianFilteringEnabled && m_LastDimensionIsTime) { + m_GaussianSigma[dim-1] = 0; + } +} +//-------------------------------------------------------------------- + + +//-------------------------------------------------------------------- +template +void +ResampleImageWithOptionsFilter:: +GenerateData() +{ + + // Get input pointer + InputImagePointer input = dynamic_cast(itk::ProcessObject::GetInput(0)); + static const unsigned int dim = InputImageType::ImageDimension; + + // Create main Resample Image Filter + typedef itk::ResampleImageFilter FilterType; + typename FilterType::Pointer filter = FilterType::New(); + filter->GraftOutput(this->GetOutput()); // this->GetOutput()->Print(std::cout); // this->GetOutput()->SetBufferedRegion(this->GetOutput()->GetLargestPossibleRegion()); // this->GetOutput()->Print(std::cout); - // Print options if needed - if (m_VerboseOptions) { - std::cout << "Output Spacing = " << m_OutputSpacing << std::endl - << "Output Size = " << m_OutputSize << std::endl - << "Gaussian = " << m_GaussianFilteringEnabled << std::endl; - if (m_GaussianFilteringEnabled) - std::cout << "Sigma = " << m_GaussianSigma << std::endl; - std::cout << "Interpol = "; - switch (m_InterpolationType) { - case NearestNeighbor: std::cout << "NearestNeighbor" << std::endl; break; - case Linear: std::cout << "Linear" << std::endl; break; - case BSpline: std::cout << "BSpline " << m_BSplineOrder << std::endl; break; - case B_LUT: std::cout << "B-LUT " << m_BSplineOrder << " " << m_BLUTSamplingFactor << std::endl; break; - } - std::cout << "Threads = " << this->GetNumberOfThreads() << std::endl; - std::cout << "LastDimIsTime = " << m_LastDimensionIsTime << std::endl; - } - - // Instance of the transform object to be passed to the resample - // filter. By default, identity transform is applied - filter->SetTransform(m_Transform); - filter->SetSize(m_OutputSize); - filter->SetOutputSpacing(m_OutputSpacing); - filter->SetOutputOrigin(input->GetOrigin()); - filter->SetDefaultPixelValue(m_DefaultPixelValue); - filter->SetNumberOfThreads(this->GetNumberOfThreads()); - - // Select interpolator + // Print options if needed + if (m_VerboseOptions) { + std::cout << "Output Spacing = " << m_OutputSpacing << std::endl + << "Output Size = " << m_OutputSize << std::endl + << "Gaussian = " << m_GaussianFilteringEnabled << std::endl; + if (m_GaussianFilteringEnabled) + std::cout << "Sigma = " << m_GaussianSigma << std::endl; + std::cout << "Interpol = "; switch (m_InterpolationType) { - case NearestNeighbor: - { - typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; - typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); - filter->SetInterpolator(interpolator); - break; - } - case Linear: - { - typedef itk::LinearInterpolateImageFunction InterpolatorType; - typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); - filter->SetInterpolator(interpolator); - break; - } - case BSpline: - { - typedef itk::BSplineInterpolateImageFunction InterpolatorType; - typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); - interpolator->SetSplineOrder(m_BSplineOrder); - filter->SetInterpolator(interpolator); + case NearestNeighbor: + std::cout << "NearestNeighbor" << std::endl; + break; + case Linear: + std::cout << "Linear" << std::endl; + break; + case BSpline: + std::cout << "BSpline " << m_BSplineOrder << std::endl; + break; + case B_LUT: + std::cout << "B-LUT " << m_BSplineOrder << " " << m_BLUTSamplingFactor << std::endl; break; - } - case B_LUT: - { - typedef itk::BSplineInterpolateImageFunctionWithLUT InterpolatorType; - typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); - interpolator->SetSplineOrder(m_BSplineOrder); - interpolator->SetLUTSamplingFactor(m_BLUTSamplingFactor); - filter->SetInterpolator(interpolator); - break; - } } - - // Initial Gaussian blurring if needed - typedef itk::RecursiveGaussianImageFilter GaussianFilterType; - std::vector gaussianFilters; - if (m_GaussianFilteringEnabled) { - for(unsigned int i=0; iSetDirection(i); - gaussianFilters[i]->SetOrder(GaussianFilterType::ZeroOrder); - gaussianFilters[i]->SetNormalizeAcrossScale(false); - gaussianFilters[i]->SetSigma(m_GaussianSigma[i]); // in millimeter ! - if (gaussianFilters.size() == 1) { // first - gaussianFilters[0]->SetInput(input); - } - else { - gaussianFilters[i]->SetInput(gaussianFilters[i-1]->GetOutput()); - } + std::cout << "Threads = " << this->GetNumberOfThreads() << std::endl; + std::cout << "LastDimIsTime = " << m_LastDimensionIsTime << std::endl; + } + + // Instance of the transform object to be passed to the resample + // filter. By default, identity transform is applied + filter->SetTransform(m_Transform); + filter->SetSize(m_OutputSize); + filter->SetOutputSpacing(m_OutputSpacing); + filter->SetOutputOrigin(input->GetOrigin()); + filter->SetDefaultPixelValue(m_DefaultPixelValue); + filter->SetNumberOfThreads(this->GetNumberOfThreads()); + + // Select interpolator + switch (m_InterpolationType) { + case NearestNeighbor: { + typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; + typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); + filter->SetInterpolator(interpolator); + break; + } + case Linear: { + typedef itk::LinearInterpolateImageFunction InterpolatorType; + typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); + filter->SetInterpolator(interpolator); + break; + } + case BSpline: { + typedef itk::BSplineInterpolateImageFunction InterpolatorType; + typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); + interpolator->SetSplineOrder(m_BSplineOrder); + filter->SetInterpolator(interpolator); + break; + } + case B_LUT: { + typedef itk::BSplineInterpolateImageFunctionWithLUT InterpolatorType; + typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); + interpolator->SetSplineOrder(m_BSplineOrder); + interpolator->SetLUTSamplingFactor(m_BLUTSamplingFactor); + filter->SetInterpolator(interpolator); + break; + } + } + + // Initial Gaussian blurring if needed + typedef itk::RecursiveGaussianImageFilter GaussianFilterType; + std::vector gaussianFilters; + if (m_GaussianFilteringEnabled) { + for(unsigned int i=0; iSetDirection(i); + gaussianFilters[i]->SetOrder(GaussianFilterType::ZeroOrder); + gaussianFilters[i]->SetNormalizeAcrossScale(false); + gaussianFilters[i]->SetSigma(m_GaussianSigma[i]); // in millimeter ! + if (gaussianFilters.size() == 1) { // first + gaussianFilters[0]->SetInput(input); + } else { + gaussianFilters[i]->SetInput(gaussianFilters[i-1]->GetOutput()); } } - if (gaussianFilters.size() > 0) { - filter->SetInput(gaussianFilters[gaussianFilters.size()-1]->GetOutput()); - } - else filter->SetInput(input); } - else filter->SetInput(input); - - // Go ! - filter->Update(); - - // Set output - // DD("before Graft"); - this->GraftOutput(filter->GetOutput()); - // DD("after Graft"); - } - //-------------------------------------------------------------------- - + if (gaussianFilters.size() > 0) { + filter->SetInput(gaussianFilters[gaussianFilters.size()-1]->GetOutput()); + } else filter->SetInput(input); + } else filter->SetInput(input); + + // Go ! + filter->Update(); + + // Set output + // DD("before Graft"); + this->GraftOutput(filter->GetOutput()); + // DD("after Graft"); +} +//-------------------------------------------------------------------- + }//end clitk - + diff --git a/itk/clitkVectorBSplineDecompositionImageFilter.txx b/itk/clitkVectorBSplineDecompositionImageFilter.txx index 2495594..440c977 100644 --- a/itk/clitkVectorBSplineDecompositionImageFilter.txx +++ b/itk/clitkVectorBSplineDecompositionImageFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -48,7 +48,7 @@ template void VectorBSplineDecompositionImageFilter ::PrintSelf( - std::ostream& os, + std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); @@ -61,50 +61,44 @@ template bool VectorBSplineDecompositionImageFilter ::DataToCoefficients1D() -{ +{ + + // See Unser, 1993, Part II, Equation 2.5, + // or Unser, 1999, Box 2. for an explaination. - // See Unser, 1993, Part II, Equation 2.5, - // or Unser, 1999, Box 2. for an explaination. + double c0 = 1.0; - double c0 = 1.0; - - if (m_DataLength[m_IteratorDirection] == 1) //Required by mirror boundaries - { + if (m_DataLength[m_IteratorDirection] == 1) { //Required by mirror boundaries return false; - } + } // Compute overall gain - for (int k = 0; k < m_NumberOfPoles; k++) - { - // Note for cubic splines lambda = 6 + for (int k = 0; k < m_NumberOfPoles; k++) { + // Note for cubic splines lambda = 6 c0 = c0 * (1.0 - m_SplinePoles[k]) * (1.0 - 1.0 / m_SplinePoles[k]); - } + } - // apply the gain - for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) - { + // apply the gain + for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] *= c0; - } + } - // loop over all poles - for (int k = 0; k < m_NumberOfPoles; k++) - { - // causal initialization + // loop over all poles + for (int k = 0; k < m_NumberOfPoles; k++) { + // causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); - // causal recursion - for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) - { + // causal recursion + for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; - } + } - // anticausal initialization + // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); - // anticausal recursion - for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) - { + // anticausal recursion + for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) { m_Scratch[n] = m_SplinePoles[k] * (m_Scratch[n + 1] - m_Scratch[n]); - } } + } return true; } @@ -115,10 +109,9 @@ void VectorBSplineDecompositionImageFilter ::SetSplineOrder(unsigned int SplineOrder) { - if (SplineOrder == m_SplineOrder) - { + if (SplineOrder == m_SplineOrder) { return; - } + } m_SplineOrder = SplineOrder; this->SetPoles(); this->Modified(); @@ -132,44 +125,43 @@ VectorBSplineDecompositionImageFilter ::SetPoles() { /* See Unser, 1997. Part II, Table I for Pole values */ - // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, + // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, // 2000, pg. 416. - switch (m_SplineOrder) - { - case 3: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; - break; - case 0: - m_NumberOfPoles = 0; - break; - case 1: - m_NumberOfPoles = 0; - break; - case 2: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; - break; - case 4: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; - m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; - break; - case 5: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - break; - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION); - err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; - } + switch (m_SplineOrder) { + case 3: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; + break; + case 0: + m_NumberOfPoles = 0; + break; + case 1: + m_NumberOfPoles = 0; + break; + case 2: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; + break; + case 4: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; + m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; + break; + case 5: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + break; + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION); + err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } } @@ -188,34 +180,29 @@ VectorBSplineDecompositionImageFilter /* this initialization corresponds to mirror boundaries */ horizon = m_DataLength[m_IteratorDirection]; zn = z; - if (m_Tolerance > 0.0) - { + if (m_Tolerance > 0.0) { horizon = (long)vcl_ceil(log(m_Tolerance) / vcl_log(fabs(z))); - } - if (horizon < m_DataLength[m_IteratorDirection]) - { + } + if (horizon < m_DataLength[m_IteratorDirection]) { /* accelerated loop */ sum = m_Scratch[0]; // verify this - for (unsigned int n = 1; n < horizon; n++) - { + for (unsigned int n = 1; n < horizon; n++) { sum += zn * m_Scratch[n]; zn *= z; - } - m_Scratch[0] = sum; } - else { - /* full loop */ - iz = 1.0 / z; - z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); - sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; - z2n *= z2n * iz; - for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) - { - sum += (zn + z2n) * m_Scratch[n]; - zn *= z; - z2n *= iz; + m_Scratch[0] = sum; + } else { + /* full loop */ + iz = 1.0 / z; + z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); + sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; + z2n *= z2n * iz; + for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) { + sum += (zn + z2n) * m_Scratch[n]; + zn *= z; + z2n *= iz; } - m_Scratch[0] = sum / (1.0 - zn * zn); + m_Scratch[0] = sum / (1.0 - zn * zn); } } @@ -225,11 +212,11 @@ void VectorBSplineDecompositionImageFilter ::SetInitialAntiCausalCoefficient(double z) { - // this initialization corresponds to mirror boundaries + // this initialization corresponds to mirror boundaries /* See Unser, 1999, Box 2 for explaination */ // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html m_Scratch[m_DataLength[m_IteratorDirection] - 1] = - (z / (z * z - 1.0)) * + (z / (z * z - 1.0)) * (z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1]); } @@ -250,8 +237,7 @@ VectorBSplineDecompositionImageFilter // Initialize coeffient array this->CopyImageToImage(); // Coefficients are initialized to the input data - for (unsigned int n=0; n < ImageDimension; n++) - { + for (unsigned int n=0; n < ImageDimension; n++) { m_IteratorDirection = n; // Loop through each dimension @@ -259,23 +245,22 @@ VectorBSplineDecompositionImageFilter OutputLinearIterator CIterator( output, output->GetBufferedRegion() ); CIterator.SetDirection( m_IteratorDirection ); // For each data vector - while ( !CIterator.IsAtEnd() ) - { + while ( !CIterator.IsAtEnd() ) { // Copy coefficients to scratch this->CopyCoefficientsToScratch( CIterator ); // Perform 1D BSpline calculations this->DataToCoefficients1D(); - + // Copy scratch back to coefficients. // Brings us back to the end of the line we were working on. CIterator.GoToBeginOfLine(); this->CopyScratchToCoefficients( CIterator ); // m_Scratch = m_Image; CIterator.NextLine(); progress.CompletedPixel(); - } } + } } @@ -298,17 +283,15 @@ VectorBSplineDecompositionImageFilter inIt = inIt.Begin(); outIt = outIt.Begin(); OutputPixelType v; - while ( !outIt.IsAtEnd() ) - { - for (unsigned int i=0; i< VectorDimension;i++) - { - v[i]= static_cast( inIt.Get()[i] ); - } - outIt.Set( v ); - ++inIt; - ++outIt; + while ( !outIt.IsAtEnd() ) { + for (unsigned int i=0; i< VectorDimension; i++) { + v[i]= static_cast( inIt.Get()[i] ); } - + outIt.Set( v ); + ++inIt; + ++outIt; + } + } @@ -323,13 +306,12 @@ VectorBSplineDecompositionImageFilter typedef typename TOutputImage::PixelType OutputPixelType; unsigned long j = 0; OutputPixelType v; - while ( !Iter.IsAtEndOfLine() ) - { - for(unsigned int i=0; i( m_Scratch[j][i]); + while ( !Iter.IsAtEndOfLine() ) { + for(unsigned int i=0; i( m_Scratch[j][i]); Iter.Set( v ); ++Iter; ++j; - } + } } @@ -344,13 +326,12 @@ VectorBSplineDecompositionImageFilter { unsigned long j = 0; itk::Vector v; - while ( !Iter.IsAtEndOfLine() ) - { - for(unsigned int i=0; i( Iter.Get()[i] ); + while ( !Iter.IsAtEndOfLine() ) { + for(unsigned int i=0; i( Iter.Get()[i] ); m_Scratch[j] = v ; ++Iter; ++j; - } + } } @@ -365,10 +346,9 @@ VectorBSplineDecompositionImageFilter // this filter requires the all of the input image to be in // the buffer InputImagePointer inputPtr = const_cast< TInputImage * > ( this->GetInput() ); - if( inputPtr ) - { + if( inputPtr ) { inputPtr->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -385,10 +365,9 @@ VectorBSplineDecompositionImageFilter // the buffer TOutputImage *imgData; imgData = dynamic_cast( output ); - if( imgData ) - { + if( imgData ) { imgData->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -406,13 +385,11 @@ VectorBSplineDecompositionImageFilter m_DataLength = inputPtr->GetBufferedRegion().GetSize(); unsigned long maxLength = 0; - for ( unsigned int n = 0; n < ImageDimension; n++ ) - { - if ( m_DataLength[n] > maxLength ) - { + for ( unsigned int n = 0; n < ImageDimension; n++ ) { + if ( m_DataLength[n] > maxLength ) { maxLength = m_DataLength[n]; - } } + } m_Scratch.resize( maxLength ); // Allocate memory for output image diff --git a/itk/clitkVectorBSplineDecompositionImageFilterWithOBD.txx b/itk/clitkVectorBSplineDecompositionImageFilterWithOBD.txx index 4af3e49..fbac370 100644 --- a/itk/clitkVectorBSplineDecompositionImageFilterWithOBD.txx +++ b/itk/clitkVectorBSplineDecompositionImageFilterWithOBD.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -48,7 +48,7 @@ template void VectorBSplineDecompositionImageFilterWithOBD ::PrintSelf( - std::ostream& os, + std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); @@ -61,50 +61,44 @@ template bool VectorBSplineDecompositionImageFilterWithOBD ::DataToCoefficients1D() -{ +{ + + // See Unser, 1993, Part II, Equation 2.5, + // or Unser, 1999, Box 2. for an explaination. - // See Unser, 1993, Part II, Equation 2.5, - // or Unser, 1999, Box 2. for an explaination. + double c0 = 1.0; - double c0 = 1.0; - - if (m_DataLength[m_IteratorDirection] == 1) //Required by mirror boundaries - { + if (m_DataLength[m_IteratorDirection] == 1) { //Required by mirror boundaries return false; - } + } // Compute overall gain - for (int k = 0; k < m_NumberOfPoles; k++) - { - // Note for cubic splines lambda = 6 + for (int k = 0; k < m_NumberOfPoles; k++) { + // Note for cubic splines lambda = 6 c0 = c0 * (1.0 - m_SplinePoles[k]) * (1.0 - 1.0 / m_SplinePoles[k]); - } + } - // apply the gain - for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) - { + // apply the gain + for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] *= c0; - } + } - // loop over all poles - for (int k = 0; k < m_NumberOfPoles; k++) - { - // causal initialization + // loop over all poles + for (int k = 0; k < m_NumberOfPoles; k++) { + // causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); - // causal recursion - for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) - { + // causal recursion + for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; - } + } - // anticausal initialization + // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); - // anticausal recursion - for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) - { + // anticausal recursion + for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) { m_Scratch[n] = m_SplinePoles[k] * (m_Scratch[n + 1] - m_Scratch[n]); - } } + } return true; } @@ -115,10 +109,9 @@ void VectorBSplineDecompositionImageFilterWithOBD ::SetSplineOrder(unsigned int SplineOrder) { - if (SplineOrder == m_SplineOrder) - { + if (SplineOrder == m_SplineOrder) { return; - } + } m_SplineOrder = SplineOrder; this->SetPoles(); this->Modified(); @@ -140,44 +133,43 @@ VectorBSplineDecompositionImageFilterWithOBD ::SetPoles() { /* See Unser, 1997. Part II, Table I for Pole values */ - // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, + // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, // 2000, pg. 416. - switch (m_SplineOrder) - { - case 3: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; - break; - case 0: - m_NumberOfPoles = 0; - break; - case 1: - m_NumberOfPoles = 0; - break; - case 2: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; - break; - case 4: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; - m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; - break; - case 5: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - break; - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION); - err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; - } + switch (m_SplineOrder) { + case 3: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; + break; + case 0: + m_NumberOfPoles = 0; + break; + case 1: + m_NumberOfPoles = 0; + break; + case 2: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; + break; + case 4: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; + m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; + break; + case 5: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + break; + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION); + err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } } @@ -196,34 +188,29 @@ VectorBSplineDecompositionImageFilterWithOBD /* this initialization corresponds to mirror boundaries */ horizon = m_DataLength[m_IteratorDirection]; zn = z; - if (m_Tolerance > 0.0) - { + if (m_Tolerance > 0.0) { horizon = (long)vcl_ceil(log(m_Tolerance) / vcl_log(fabs(z))); - } - if (horizon < m_DataLength[m_IteratorDirection]) - { + } + if (horizon < m_DataLength[m_IteratorDirection]) { /* accelerated loop */ sum = m_Scratch[0]; // verify this - for (unsigned int n = 1; n < horizon; n++) - { + for (unsigned int n = 1; n < horizon; n++) { sum += zn * m_Scratch[n]; zn *= z; - } - m_Scratch[0] = sum; } - else { - /* full loop */ - iz = 1.0 / z; - z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); - sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; - z2n *= z2n * iz; - for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) - { - sum += (zn + z2n) * m_Scratch[n]; - zn *= z; - z2n *= iz; + m_Scratch[0] = sum; + } else { + /* full loop */ + iz = 1.0 / z; + z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); + sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; + z2n *= z2n * iz; + for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) { + sum += (zn + z2n) * m_Scratch[n]; + zn *= z; + z2n *= iz; } - m_Scratch[0] = sum / (1.0 - zn * zn); + m_Scratch[0] = sum / (1.0 - zn * zn); } } @@ -233,11 +220,11 @@ void VectorBSplineDecompositionImageFilterWithOBD ::SetInitialAntiCausalCoefficient(double z) { - // this initialization corresponds to mirror boundaries + // this initialization corresponds to mirror boundaries /* See Unser, 1999, Box 2 for explaination */ // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html m_Scratch[m_DataLength[m_IteratorDirection] - 1] = - (z / (z * z - 1.0)) * + (z / (z * z - 1.0)) * (z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1]); } @@ -258,8 +245,7 @@ VectorBSplineDecompositionImageFilterWithOBD // Initialize coeffient array this->CopyImageToImage(); // Coefficients are initialized to the input data - for (unsigned int n=0; n < ImageDimension; n++) - { + for (unsigned int n=0; n < ImageDimension; n++) { m_IteratorDirection = n; // Loop through each dimension @@ -270,23 +256,22 @@ VectorBSplineDecompositionImageFilterWithOBD OutputLinearIterator CIterator( output, output->GetBufferedRegion() ); CIterator.SetDirection( m_IteratorDirection ); // For each data vector - while ( !CIterator.IsAtEnd() ) - { + while ( !CIterator.IsAtEnd() ) { // Copy coefficients to scratch this->CopyCoefficientsToScratch( CIterator ); // Perform 1D BSpline calculations this->DataToCoefficients1D(); - + // Copy scratch back to coefficients. // Brings us back to the end of the line we were working on. CIterator.GoToBeginOfLine(); this->CopyScratchToCoefficients( CIterator ); // m_Scratch = m_Image; CIterator.NextLine(); progress.CompletedPixel(); - } } + } } @@ -309,17 +294,15 @@ VectorBSplineDecompositionImageFilterWithOBD inIt = inIt.Begin(); outIt = outIt.Begin(); OutputPixelType v; - while ( !outIt.IsAtEnd() ) - { - for (unsigned int i=0; i< VectorDimension;i++) - { - v[i]= static_cast( inIt.Get()[i] ); - } - outIt.Set( v ); - ++inIt; - ++outIt; + while ( !outIt.IsAtEnd() ) { + for (unsigned int i=0; i< VectorDimension; i++) { + v[i]= static_cast( inIt.Get()[i] ); } - + outIt.Set( v ); + ++inIt; + ++outIt; + } + } @@ -334,13 +317,12 @@ VectorBSplineDecompositionImageFilterWithOBD typedef typename TOutputImage::PixelType OutputPixelType; unsigned long j = 0; OutputPixelType v; - while ( !Iter.IsAtEndOfLine() ) - { - for(unsigned int i=0; i( m_Scratch[j][i]); + while ( !Iter.IsAtEndOfLine() ) { + for(unsigned int i=0; i( m_Scratch[j][i]); Iter.Set( v ); ++Iter; ++j; - } + } } @@ -355,13 +337,12 @@ VectorBSplineDecompositionImageFilterWithOBD { unsigned long j = 0; itk::Vector v; - while ( !Iter.IsAtEndOfLine() ) - { - for(unsigned int i=0; i( Iter.Get()[i] ); + while ( !Iter.IsAtEndOfLine() ) { + for(unsigned int i=0; i( Iter.Get()[i] ); m_Scratch[j] = v ; ++Iter; ++j; - } + } } @@ -376,10 +357,9 @@ VectorBSplineDecompositionImageFilterWithOBD // this filter requires the all of the input image to be in // the buffer InputImagePointer inputPtr = const_cast< TInputImage * > ( this->GetInput() ); - if( inputPtr ) - { + if( inputPtr ) { inputPtr->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -396,10 +376,9 @@ VectorBSplineDecompositionImageFilterWithOBD // the buffer TOutputImage *imgData; imgData = dynamic_cast( output ); - if( imgData ) - { + if( imgData ) { imgData->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -417,13 +396,11 @@ VectorBSplineDecompositionImageFilterWithOBD m_DataLength = inputPtr->GetBufferedRegion().GetSize(); unsigned long maxLength = 0; - for ( unsigned int n = 0; n < ImageDimension; n++ ) - { - if ( m_DataLength[n] > maxLength ) - { + for ( unsigned int n = 0; n < ImageDimension; n++ ) { + if ( m_DataLength[n] > maxLength ) { maxLength = m_DataLength[n]; - } } + } m_Scratch.resize( maxLength ); // Allocate memory for output image diff --git a/itk/clitkVectorBSplineInterpolateImageFunction.txx b/itk/clitkVectorBSplineInterpolateImageFunction.txx index e653bd7..4b2a7de 100644 --- a/itk/clitkVectorBSplineInterpolateImageFunction.txx +++ b/itk/clitkVectorBSplineInterpolateImageFunction.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -61,75 +61,70 @@ template void VectorBSplineInterpolateImageFunction ::PrintSelf( - std::ostream& os, + std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf( os, indent ); os << indent << "Spline Order: " << m_SplineOrder << std::endl; - os << indent << "UseImageDirection = " + os << indent << "UseImageDirection = " << (this->m_UseImageDirection ? "On" : "Off") << std::endl; } template -void +void VectorBSplineInterpolateImageFunction ::SetInputImage(const TImageType * inputData) { - if ( inputData ) - { - - DD("calling decomposition filter"); - m_CoefficientFilter->SetInput(inputData); - - // the Coefficient Filter requires that the spline order and the input data be set. - // TODO: We need to ensure that this is only run once and only after both input and - // spline order have been set. Should we force an update after the - // splineOrder has been set also? - - m_CoefficientFilter->Update(); - m_Coefficients = m_CoefficientFilter->GetOutput(); - - - // Call the Superclass implementation after, in case the filter - // pulls in more of the input image - Superclass::SetInputImage(inputData); - - m_DataLength = inputData->GetBufferedRegion().GetSize(); - - } - else - { - m_Coefficients = NULL; - } + if ( inputData ) { + + DD("calling decomposition filter"); + m_CoefficientFilter->SetInput(inputData); + + // the Coefficient Filter requires that the spline order and the input data be set. + // TODO: We need to ensure that this is only run once and only after both input and + // spline order have been set. Should we force an update after the + // splineOrder has been set also? + + m_CoefficientFilter->Update(); + m_Coefficients = m_CoefficientFilter->GetOutput(); + + + // Call the Superclass implementation after, in case the filter + // pulls in more of the input image + Superclass::SetInputImage(inputData); + + m_DataLength = inputData->GetBufferedRegion().GetSize(); + + } else { + m_Coefficients = NULL; + } } template -void +void VectorBSplineInterpolateImageFunction ::SetSplineOrder(unsigned int SplineOrder) { - if (SplineOrder == m_SplineOrder) - { + if (SplineOrder == m_SplineOrder) { return; - } + } m_SplineOrder = SplineOrder; m_CoefficientFilter->SetSplineOrder( SplineOrder ); //this->SetPoles();/ m_MaxNumberInterpolationPoints = 1; - for (unsigned int n=0; n < ImageDimension; n++) - { + for (unsigned int n=0; n < ImageDimension; n++) { m_MaxNumberInterpolationPoints *= ( m_SplineOrder + 1); - } + } this->GeneratePointsToIndex( ); } template -typename +typename VectorBSplineInterpolateImageFunction ::OutputType VectorBSplineInterpolateImageFunction @@ -137,8 +132,8 @@ VectorBSplineInterpolateImageFunction { vnl_matrix EvaluateIndex(ImageDimension, ( m_SplineOrder + 1 )); - // compute the interpolation indexes - this->DetermineRegionOfSupport(EvaluateIndex, x, m_SplineOrder); + // compute the interpolation indexes + this->DetermineRegionOfSupport(EvaluateIndex, x, m_SplineOrder); // Determine weights vnl_matrix weights(ImageDimension, ( m_SplineOrder + 1 )); @@ -146,59 +141,57 @@ VectorBSplineInterpolateImageFunction // Modify EvaluateIndex at the boundaries using mirror boundary conditions this->ApplyMirrorBoundaryConditions(EvaluateIndex, m_SplineOrder); - + // perform interpolation - //JV - itk::Vector interpolated; - for (unsigned int i=0; i< VectorDimension; i++) interpolated[i]=itk::NumericTraits::Zero; + //JV + itk::Vector interpolated; + for (unsigned int i=0; i< VectorDimension; i++) interpolated[i]=itk::NumericTraits::Zero; IndexType coefficientIndex; // Step through eachpoint in the N-dimensional interpolation cube. - for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) - { + for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) { // translate each step into the N-dimensional index. // IndexType pointIndex = PointToIndex( p ); double w = 1.0; - for (unsigned int n = 0; n < ImageDimension; n++ ) - { + for (unsigned int n = 0; n < ImageDimension; n++ ) { - w *= weights[n][ m_PointsToIndex[p][n] ]; - coefficientIndex[n] = EvaluateIndex[n][m_PointsToIndex[p][n]]; // Build up ND index for coefficients. - } + w *= weights[n][ m_PointsToIndex[p][n] ]; + coefficientIndex[n] = EvaluateIndex[n][m_PointsToIndex[p][n]]; // Build up ND index for coefficients. + } // Convert our step p to the appropriate point in ND space in the // m_Coefficients cube. //JV shouldn't be necessary for (unsigned int i=0; iGetPixel(coefficientIndex)[i]; - } - -/* double interpolated = 0.0; - IndexType coefficientIndex; - // Step through eachpoint in the N-dimensional interpolation cube. - for (unsigned int sp = 0; sp <= m_SplineOrder; sp++) - { - for (unsigned int sp1=0; sp1 <= m_SplineOrder; sp1++) - { + } - double w = 1.0; - for (unsigned int n1 = 0; n1 < ImageDimension; n1++ ) + /* double interpolated = 0.0; + IndexType coefficientIndex; + // Step through eachpoint in the N-dimensional interpolation cube. + for (unsigned int sp = 0; sp <= m_SplineOrder; sp++) + { + for (unsigned int sp1=0; sp1 <= m_SplineOrder; sp1++) { - w *= weights[n1][ sp1 ]; - coefficientIndex[n1] = EvaluateIndex[n1][sp]; // Build up ND index for coefficients. - } - interpolated += w * m_Coefficients->GetPixel(coefficientIndex); - } - } -*/ + double w = 1.0; + for (unsigned int n1 = 0; n1 < ImageDimension; n1++ ) + { + w *= weights[n1][ sp1 ]; + coefficientIndex[n1] = EvaluateIndex[n1][sp]; // Build up ND index for coefficients. + } + + interpolated += w * m_Coefficients->GetPixel(coefficientIndex); + } + } + */ return(interpolated); - + } template -typename +typename VectorBSplineInterpolateImageFunction :: CovariantVectorType VectorBSplineInterpolateImageFunction @@ -206,7 +199,7 @@ VectorBSplineInterpolateImageFunction { vnl_matrix EvaluateIndex(ImageDimension, ( m_SplineOrder + 1 )); - // compute the interpolation indexes + // compute the interpolation indexes // TODO: Do we need to revisit region of support for the derivatives? this->DetermineRegionOfSupport(EvaluateIndex, x, m_SplineOrder); @@ -219,7 +212,7 @@ VectorBSplineInterpolateImageFunction // Modify EvaluateIndex at the boundaries using mirror boundary conditions this->ApplyMirrorBoundaryConditions(EvaluateIndex, m_SplineOrder); - + const InputImageType * inputImage = this->GetInputImage(); const typename InputImageType::SpacingType & spacing = inputImage->GetSpacing(); @@ -227,39 +220,32 @@ VectorBSplineInterpolateImageFunction CovariantVectorType derivativeValue; double tempValue; IndexType coefficientIndex; - for (unsigned int n = 0; n < ImageDimension; n++) - { + for (unsigned int n = 0; n < ImageDimension; n++) { derivativeValue[n] = 0.0; - for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) - { - tempValue = 1.0 ; - for (unsigned int n1 = 0; n1 < ImageDimension; n1++) - { + for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) { + tempValue = 1.0 ; + for (unsigned int n1 = 0; n1 < ImageDimension; n1++) { //coefficientIndex[n1] = EvaluateIndex[n1][sp]; coefficientIndex[n1] = EvaluateIndex[n1][m_PointsToIndex[p][n1]]; - if (n1 == n) - { + if (n1 == n) { //w *= weights[n][ m_PointsToIndex[p][n] ]; tempValue *= weightsDerivative[n1][ m_PointsToIndex[p][n1] ]; - } - else - { - tempValue *= weights[n1][ m_PointsToIndex[p][n1] ]; - } + } else { + tempValue *= weights[n1][ m_PointsToIndex[p][n1] ]; } - derivativeValue[n] += m_Coefficients->GetPixel(coefficientIndex) * tempValue ; } - derivativeValue[n] /= spacing[n]; // take spacing into account + derivativeValue[n] += m_Coefficients->GetPixel(coefficientIndex) * tempValue ; } + derivativeValue[n] /= spacing[n]; // take spacing into account + } #ifdef ITK_USE_ORIENTED_IMAGE_DIRECTION - if( this->m_UseImageDirection ) - { + if( this->m_UseImageDirection ) { CovariantVectorType orientedDerivative; inputImage->TransformLocalVectorToPhysicalVector( derivativeValue, orientedDerivative ); return orientedDerivative; - } + } #endif return(derivativeValue); @@ -267,107 +253,100 @@ VectorBSplineInterpolateImageFunction template -void +void VectorBSplineInterpolateImageFunction -::SetInterpolationWeights( const ContinuousIndexType & x, const vnl_matrix & EvaluateIndex, +::SetInterpolationWeights( const ContinuousIndexType & x, const vnl_matrix & EvaluateIndex, vnl_matrix & weights, unsigned int splineOrder ) const { // For speed improvements we could make each case a separate function and use // function pointers to reference the correct weight order. // Left as is for now for readability. double w, w2, w4, t, t0, t1; - - switch (splineOrder) - { - case 3: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] - (double) EvaluateIndex[n][1]; - weights[n][3] = (1.0 / 6.0) * w * w * w; - weights[n][0] = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - weights[n][3]; - weights[n][2] = w + weights[n][0] - 2.0 * weights[n][3]; - weights[n][1] = 1.0 - weights[n][0] - weights[n][2] - weights[n][3]; - } - break; - case 0: - for (unsigned int n = 0; n < ImageDimension; n++) - { - weights[n][0] = 1; // implements nearest neighbor - } - break; - case 1: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] - (double) EvaluateIndex[n][0]; - weights[n][1] = w; - weights[n][0] = 1.0 - w; - } - break; - case 2: - for (unsigned int n = 0; n < ImageDimension; n++) - { - /* x */ - w = x[n] - (double)EvaluateIndex[n][1]; - weights[n][1] = 0.75 - w * w; - weights[n][2] = 0.5 * (w - weights[n][1] + 1.0); - weights[n][0] = 1.0 - weights[n][1] - weights[n][2]; - } - break; - case 4: - for (unsigned int n = 0; n < ImageDimension; n++) - { - /* x */ - w = x[n] - (double)EvaluateIndex[n][2]; - w2 = w * w; - t = (1.0 / 6.0) * w2; - weights[n][0] = 0.5 - w; - weights[n][0] *= weights[n][0]; - weights[n][0] *= (1.0 / 24.0) * weights[n][0]; - t0 = w * (t - 11.0 / 24.0); - t1 = 19.0 / 96.0 + w2 * (0.25 - t); - weights[n][1] = t1 + t0; - weights[n][3] = t1 - t0; - weights[n][4] = weights[n][0] + t0 + 0.5 * w; - weights[n][2] = 1.0 - weights[n][0] - weights[n][1] - weights[n][3] - weights[n][4]; - } - break; - case 5: - for (unsigned int n = 0; n < ImageDimension; n++) - { - /* x */ - w = x[n] - (double)EvaluateIndex[n][2]; - w2 = w * w; - weights[n][5] = (1.0 / 120.0) * w * w2 * w2; - w2 -= w; - w4 = w2 * w2; - w -= 0.5; - t = w2 * (w2 - 3.0); - weights[n][0] = (1.0 / 24.0) * (1.0 / 5.0 + w2 + w4) - weights[n][5]; - t0 = (1.0 / 24.0) * (w2 * (w2 - 5.0) + 46.0 / 5.0); - t1 = (-1.0 / 12.0) * w * (t + 4.0); - weights[n][2] = t0 + t1; - weights[n][3] = t0 - t1; - t0 = (1.0 / 16.0) * (9.0 / 5.0 - t); - t1 = (1.0 / 24.0) * w * (w4 - w2 - 5.0); - weights[n][1] = t0 + t1; - weights[n][4] = t0 - t1; - } - break; - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION ); - err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; + + switch (splineOrder) { + case 3: + for (unsigned int n = 0; n < ImageDimension; n++) { + w = x[n] - (double) EvaluateIndex[n][1]; + weights[n][3] = (1.0 / 6.0) * w * w * w; + weights[n][0] = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - weights[n][3]; + weights[n][2] = w + weights[n][0] - 2.0 * weights[n][3]; + weights[n][1] = 1.0 - weights[n][0] - weights[n][2] - weights[n][3]; + } + break; + case 0: + for (unsigned int n = 0; n < ImageDimension; n++) { + weights[n][0] = 1; // implements nearest neighbor + } + break; + case 1: + for (unsigned int n = 0; n < ImageDimension; n++) { + w = x[n] - (double) EvaluateIndex[n][0]; + weights[n][1] = w; + weights[n][0] = 1.0 - w; + } + break; + case 2: + for (unsigned int n = 0; n < ImageDimension; n++) { + /* x */ + w = x[n] - (double)EvaluateIndex[n][1]; + weights[n][1] = 0.75 - w * w; + weights[n][2] = 0.5 * (w - weights[n][1] + 1.0); + weights[n][0] = 1.0 - weights[n][1] - weights[n][2]; + } + break; + case 4: + for (unsigned int n = 0; n < ImageDimension; n++) { + /* x */ + w = x[n] - (double)EvaluateIndex[n][2]; + w2 = w * w; + t = (1.0 / 6.0) * w2; + weights[n][0] = 0.5 - w; + weights[n][0] *= weights[n][0]; + weights[n][0] *= (1.0 / 24.0) * weights[n][0]; + t0 = w * (t - 11.0 / 24.0); + t1 = 19.0 / 96.0 + w2 * (0.25 - t); + weights[n][1] = t1 + t0; + weights[n][3] = t1 - t0; + weights[n][4] = weights[n][0] + t0 + 0.5 * w; + weights[n][2] = 1.0 - weights[n][0] - weights[n][1] - weights[n][3] - weights[n][4]; } - + break; + case 5: + for (unsigned int n = 0; n < ImageDimension; n++) { + /* x */ + w = x[n] - (double)EvaluateIndex[n][2]; + w2 = w * w; + weights[n][5] = (1.0 / 120.0) * w * w2 * w2; + w2 -= w; + w4 = w2 * w2; + w -= 0.5; + t = w2 * (w2 - 3.0); + weights[n][0] = (1.0 / 24.0) * (1.0 / 5.0 + w2 + w4) - weights[n][5]; + t0 = (1.0 / 24.0) * (w2 * (w2 - 5.0) + 46.0 / 5.0); + t1 = (-1.0 / 12.0) * w * (t + 4.0); + weights[n][2] = t0 + t1; + weights[n][3] = t0 - t1; + t0 = (1.0 / 16.0) * (9.0 / 5.0 - t); + t1 = (1.0 / 24.0) * w * (w4 - w2 - 5.0); + weights[n][1] = t0 + t1; + weights[n][4] = t0 - t1; + } + break; + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION ); + err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } + } template -void +void VectorBSplineInterpolateImageFunction -::SetDerivativeWeights( const ContinuousIndexType & x, const vnl_matrix & EvaluateIndex, +::SetDerivativeWeights( const ContinuousIndexType & x, const vnl_matrix & EvaluateIndex, vnl_matrix & weights, unsigned int splineOrder ) const { // For speed improvements we could make each case a separate function and use @@ -377,103 +356,96 @@ VectorBSplineInterpolateImageFunction // Left as is for now for readability. double w, w1, w2, w3, w4, w5, t, t0, t1, t2; int derivativeSplineOrder = (int) splineOrder -1; - - switch (derivativeSplineOrder) - { - - // Calculates B(splineOrder) ( (x + 1/2) - xi) - B(splineOrder -1) ( (x - 1/2) - xi) - case -1: - // Why would we want to do this? - for (unsigned int n = 0; n < ImageDimension; n++) - { - weights[n][0] = 0.0; - } - break; - case 0: - for (unsigned int n = 0; n < ImageDimension; n++) - { - weights[n][0] = -1.0; - weights[n][1] = 1.0; - } - break; - case 1: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + 0.5 - (double)EvaluateIndex[n][1]; - // w2 = w; - w1 = 1.0 - w; - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w; - weights[n][2] = w; - } - break; - case 2: - - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + .5 - (double)EvaluateIndex[n][2]; - w2 = 0.75 - w * w; - w3 = 0.5 * (w - w2 + 1.0); - w1 = 1.0 - w2 - w3; - - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w2; - weights[n][2] = w2 - w3; - weights[n][3] = w3; - } - break; - case 3: - - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + 0.5 - (double)EvaluateIndex[n][2]; - w4 = (1.0 / 6.0) * w * w * w; - w1 = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - w4; - w3 = w + w1 - 2.0 * w4; - w2 = 1.0 - w1 - w3 - w4; - - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w2; - weights[n][2] = w2 - w3; - weights[n][3] = w3 - w4; - weights[n][4] = w4; - } - break; - case 4: - for (unsigned int n = 0; n < ImageDimension; n++) - { - w = x[n] + .5 - (double)EvaluateIndex[n][3]; - t2 = w * w; - t = (1.0 / 6.0) * t2; - w1 = 0.5 - w; - w1 *= w1; - w1 *= (1.0 / 24.0) * w1; - t0 = w * (t - 11.0 / 24.0); - t1 = 19.0 / 96.0 + t2 * (0.25 - t); - w2 = t1 + t0; - w4 = t1 - t0; - w5 = w1 + t0 + 0.5 * w; - w3 = 1.0 - w1 - w2 - w4 - w5; - - weights[n][0] = 0.0 - w1; - weights[n][1] = w1 - w2; - weights[n][2] = w2 - w3; - weights[n][3] = w3 - w4; - weights[n][4] = w4 - w5; - weights[n][5] = w5; - } - break; - - default: - // SplineOrder not implemented yet. - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION ); - err.SetDescription( "SplineOrder (for derivatives) must be between 1 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; + switch (derivativeSplineOrder) { + + // Calculates B(splineOrder) ( (x + 1/2) - xi) - B(splineOrder -1) ( (x - 1/2) - xi) + case -1: + // Why would we want to do this? + for (unsigned int n = 0; n < ImageDimension; n++) { + weights[n][0] = 0.0; } - + break; + case 0: + for (unsigned int n = 0; n < ImageDimension; n++) { + weights[n][0] = -1.0; + weights[n][1] = 1.0; + } + break; + case 1: + for (unsigned int n = 0; n < ImageDimension; n++) { + w = x[n] + 0.5 - (double)EvaluateIndex[n][1]; + // w2 = w; + w1 = 1.0 - w; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w; + weights[n][2] = w; + } + break; + case 2: + + for (unsigned int n = 0; n < ImageDimension; n++) { + w = x[n] + .5 - (double)EvaluateIndex[n][2]; + w2 = 0.75 - w * w; + w3 = 0.5 * (w - w2 + 1.0); + w1 = 1.0 - w2 - w3; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w2; + weights[n][2] = w2 - w3; + weights[n][3] = w3; + } + break; + case 3: + + for (unsigned int n = 0; n < ImageDimension; n++) { + w = x[n] + 0.5 - (double)EvaluateIndex[n][2]; + w4 = (1.0 / 6.0) * w * w * w; + w1 = (1.0 / 6.0) + 0.5 * w * (w - 1.0) - w4; + w3 = w + w1 - 2.0 * w4; + w2 = 1.0 - w1 - w3 - w4; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w2; + weights[n][2] = w2 - w3; + weights[n][3] = w3 - w4; + weights[n][4] = w4; + } + break; + case 4: + for (unsigned int n = 0; n < ImageDimension; n++) { + w = x[n] + .5 - (double)EvaluateIndex[n][3]; + t2 = w * w; + t = (1.0 / 6.0) * t2; + w1 = 0.5 - w; + w1 *= w1; + w1 *= (1.0 / 24.0) * w1; + t0 = w * (t - 11.0 / 24.0); + t1 = 19.0 / 96.0 + t2 * (0.25 - t); + w2 = t1 + t0; + w4 = t1 - t0; + w5 = w1 + t0 + 0.5 * w; + w3 = 1.0 - w1 - w2 - w4 - w5; + + weights[n][0] = 0.0 - w1; + weights[n][1] = w1 - w2; + weights[n][2] = w2 - w3; + weights[n][3] = w3 - w4; + weights[n][4] = w4 - w5; + weights[n][5] = w5; + } + break; + + default: + // SplineOrder not implemented yet. + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION ); + err.SetDescription( "SplineOrder (for derivatives) must be between 1 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } + } @@ -486,87 +458,71 @@ VectorBSplineInterpolateImageFunction // m_PointsToIndex is used to convert a sequential location to an N-dimension // index vector. This is precomputed to save time during the interpolation routine. m_PointsToIndex.resize(m_MaxNumberInterpolationPoints); - for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) - { + for (unsigned int p = 0; p < m_MaxNumberInterpolationPoints; p++) { int pp = p; unsigned long indexFactor[ImageDimension]; indexFactor[0] = 1; - for (int j=1; j< static_cast(ImageDimension); j++) - { + for (int j=1; j< static_cast(ImageDimension); j++) { indexFactor[j] = indexFactor[j-1] * ( m_SplineOrder + 1 ); - } - for (int j = (static_cast(ImageDimension) - 1); j >= 0; j--) - { + } + for (int j = (static_cast(ImageDimension) - 1); j >= 0; j--) { m_PointsToIndex[p][j] = pp / indexFactor[j]; pp = pp % indexFactor[j]; - } } + } } template void VectorBSplineInterpolateImageFunction -::DetermineRegionOfSupport( vnl_matrix & evaluateIndex, - const ContinuousIndexType & x, +::DetermineRegionOfSupport( vnl_matrix & evaluateIndex, + const ContinuousIndexType & x, unsigned int splineOrder ) const -{ +{ long indx; -// compute the interpolation indexes - for (unsigned int n = 0; n< ImageDimension; n++) - { - if (splineOrder & 1) // Use this index calculation for odd splineOrder - { +// compute the interpolation indexes + for (unsigned int n = 0; n< ImageDimension; n++) { + if (splineOrder & 1) { // Use this index calculation for odd splineOrder indx = (long)vcl_floor((float)x[n]) - splineOrder / 2; - for (unsigned int k = 0; k <= splineOrder; k++) - { + for (unsigned int k = 0; k <= splineOrder; k++) { evaluateIndex[n][k] = indx++; - } } - else // Use this index calculation for even splineOrder - { + } else { // Use this index calculation for even splineOrder indx = (long)vcl_floor((float)(x[n] + 0.5)) - splineOrder / 2; - for (unsigned int k = 0; k <= splineOrder; k++) - { + for (unsigned int k = 0; k <= splineOrder; k++) { evaluateIndex[n][k] = indx++; - } } } + } } template void VectorBSplineInterpolateImageFunction -::ApplyMirrorBoundaryConditions(vnl_matrix & evaluateIndex, +::ApplyMirrorBoundaryConditions(vnl_matrix & evaluateIndex, unsigned int splineOrder) const { - for (unsigned int n = 0; n < ImageDimension; n++) - { + for (unsigned int n = 0; n < ImageDimension; n++) { long dataLength2 = 2 * m_DataLength[n] - 2; - // apply the mirror boundary conditions + // apply the mirror boundary conditions // TODO: We could implement other boundary options beside mirror - if (m_DataLength[n] == 1) - { - for (unsigned int k = 0; k <= splineOrder; k++) - { + if (m_DataLength[n] == 1) { + for (unsigned int k = 0; k <= splineOrder; k++) { evaluateIndex[n][k] = 0; - } } - else - { - for (unsigned int k = 0; k <= splineOrder; k++) - { + } else { + for (unsigned int k = 0; k <= splineOrder; k++) { // btw - Think about this couldn't this be replaced with a more elagent modulus method? evaluateIndex[n][k] = (evaluateIndex[n][k] < 0L) ? (-evaluateIndex[n][k] - dataLength2 * ((-evaluateIndex[n][k]) / dataLength2)) - : (evaluateIndex[n][k] - dataLength2 * (evaluateIndex[n][k] / dataLength2)); - if ((long) m_DataLength[n] <= evaluateIndex[n][k]) - { + : (evaluateIndex[n][k] - dataLength2 * (evaluateIndex[n][k] / dataLength2)); + if ((long) m_DataLength[n] <= evaluateIndex[n][k]) { evaluateIndex[n][k] = dataLength2 - evaluateIndex[n][k]; - } } } } + } } } // namespace itk diff --git a/itk/clitkVectorBSplineInterpolateImageFunctionWithLUT.txx b/itk/clitkVectorBSplineInterpolateImageFunctionWithLUT.txx index 8aa39ab..4c6f3eb 100644 --- a/itk/clitkVectorBSplineInterpolateImageFunctionWithLUT.txx +++ b/itk/clitkVectorBSplineInterpolateImageFunctionWithLUT.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,433 +18,434 @@ #ifndef _CLITKVECTORBSPLINEINTERPOLATEIMAGEFUNCTIONWITHLUT_TXX #define _CLITKVECTORBSPLINEINTERPOLATEIMAGEFUNCTIONWITHLUT_TXX /* ========================================================================= - + @file itkBSplineInterpolateImageFunctionWithLUT.txx @author jefvdmb@gmail.com -Copyright (c) -* CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). +Copyright (c) +* CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details. * Léon Bérard cancer center, 28 rue Laënnec, 69373 Lyon cedex 08, France * http://www.creatis.insa-lyon.fr/rio - + 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. - + ========================================================================= */ namespace clitk { - //==================================================================== - template - VectorBSplineInterpolateImageFunctionWithLUT:: - VectorBSplineInterpolateImageFunctionWithLUT():Superclass() { - // Set default values - //for(int i=0; i +VectorBSplineInterpolateImageFunctionWithLUT:: +VectorBSplineInterpolateImageFunctionWithLUT():Superclass() +{ + // Set default values + //for(int i=0; i +void VectorBSplineInterpolateImageFunctionWithLUT:: +SetLUTSamplingFactor(const int& s) +{ + for(int i=0; i - void VectorBSplineInterpolateImageFunctionWithLUT:: - SetLUTSamplingFactor(const int& s) { - for(int i=0; i +void VectorBSplineInterpolateImageFunctionWithLUT:: +SetLUTSamplingFactors(const SizeType& s) +{ + for(int i=0; i +// void VectorBSplineInterpolateImageFunctionWithLUT:: +// SetOutputSpacing(const SpacingType & s) { +// for(int i=0; i +void VectorBSplineInterpolateImageFunctionWithLUT:: +SetSplineOrder(const unsigned int& SplineOrder) +{ + Superclass::SetSplineOrder(SplineOrder); + // Compute support and half size + static const int d = TImageType::ImageDimension; + for(int l=0; l - void VectorBSplineInterpolateImageFunctionWithLUT:: - SetLUTSamplingFactors(const SizeType& s) { - for(int i=0; i +void VectorBSplineInterpolateImageFunctionWithLUT:: +SetSplineOrders(const SizeType& SplineOrders) +{ + mSplineOrders=SplineOrders; + + // Compute support and half size + static const int d = TImageType::ImageDimension; + for(int l=0; l +void VectorBSplineInterpolateImageFunctionWithLUT:: +SetInputImage(const TImageType * inputData) +{ - //==================================================================== - - // //==================================================================== - // template - // void VectorBSplineInterpolateImageFunctionWithLUT:: - // SetOutputSpacing(const SpacingType & s) { - // for(int i=0; i - void VectorBSplineInterpolateImageFunctionWithLUT:: - SetSplineOrder(const unsigned int& SplineOrder) { - Superclass::SetSplineOrder(SplineOrder); - // Compute support and half size - static const int d = TImageType::ImageDimension; - for(int l=0; lm_Coefficients = inputData; + // if ( this->m_Coefficients.IsNotNull()) + // { + // this->m_DataLength = this->m_Coefficients->GetBufferedRegion().GetSize(); + // } + + // //Call super-superclass in case more input arrives + // itk::ImageFunction::RealType, TCoefficientType>::SetInputImage(inputData); + // } + + if (!inputData) return; + UpdateWeightsProperties(); + +} + +//==================================================================== +template +void VectorBSplineInterpolateImageFunctionWithLUT:: +UpdateWeightsProperties() +{ + + // Compute Memory offset inside coefficients images (for looping over coefficients) + static const unsigned int d = TImageType::ImageDimension; + mInputMemoryOffset[0] = 1; + for(unsigned int l=1; lm_Coefficients->GetLargestPossibleRegion().GetSize(l-1); } - //==================================================================== - //JV - //==================================================================== - template - void VectorBSplineInterpolateImageFunctionWithLUT:: - SetSplineOrders(const SizeType& SplineOrders) { - mSplineOrders=SplineOrders; - - // Compute support and half size - static const int d = TImageType::ImageDimension; - for(int l=0; l(mSupportIndex[k], mInputMemoryOffset); + // next coefficient index + if (k != mSupportSize-1) { + for(unsigned int l=0; l(mSupportIndex[k+1][l]) == mSupport[l]) { + mSupportIndex[k+1][l] = 0; + l++; + } else stop = true; + } } - else mHalfSupport[l] = mSupport[l]/2; // support is odd (like cubic spline) } - mSupportSize = 1; - for(int l=0; l - void VectorBSplineInterpolateImageFunctionWithLUT:: - SetInputImage(const TImageType * inputData) { - //============================== - // if (!mInputIsCoef) - // { - Superclass::SetInputImage(inputData); + // // Check + // for(unsigned int l=0; lm_Coefficients = inputData; - // if ( this->m_Coefficients.IsNotNull()) - // { - // this->m_DataLength = this->m_Coefficients->GetBufferedRegion().GetSize(); - // } - - // //Call super-superclass in case more input arrives - // itk::ImageFunction::RealType, TCoefficientType>::SetInputImage(inputData); - // } - - if (!inputData) return; - UpdateWeightsProperties(); + // } + // Compute BSpline weights if not up to date + //if (!mWeightsAreUpToDate) + UpdatePrecomputedWeights(); } - - //==================================================================== - template - void VectorBSplineInterpolateImageFunctionWithLUT:: - UpdateWeightsProperties() { - - // Compute Memory offset inside coefficients images (for looping over coefficients) - static const unsigned int d = TImageType::ImageDimension; - mInputMemoryOffset[0] = 1; - for(unsigned int l=1; lm_Coefficients->GetLargestPossibleRegion().GetSize(l-1); - } + // Initialisation + // *mIntrinsecErrorMax = *mIntrinsecError = 0.0; + // *mNumberOfError = 0; +} +//==================================================================== + +//==================================================================== +template +void VectorBSplineInterpolateImageFunctionWithLUT:: +UpdatePrecomputedWeights() +{ + // mLUTTimer.Reset(); + // mLUTTimer.Start(); + mWeightsCalculator.SetSplineOrders(mSplineOrders); + mWeightsCalculator.SetSamplingFactors(mSamplingFactors); + mWeightsCalculator.ComputeTensorProducts(); + mWeightsAreUpToDate = true; + //DS + // coef = new TCoefficientType[mSupportSize]; + // mCorrectedSupportIndex.resize(mSupportSize); + // mCorrectedSupportOffset.resize(mSupportSize); + // mLUTTimer.Stop(); + // mLUTTimer.Print("LUT \t"); +} +//==================================================================== + +//==================================================================== +template +typename VectorBSplineInterpolateImageFunctionWithLUT::IndexType +VectorBSplineInterpolateImageFunctionWithLUT:: +GetSampleIndexOfPixelPosition(const ContinuousIndexType & x, IndexType & EvaluateIndex) const +{ - //JV Put here? - if (!mWeightsAreUpToDate) - { - // Compute mSupportOffset according to input size - mSupportOffset.resize(mSupportSize); - mSupportIndex.resize(mSupportSize); - for(unsigned int l=0; l(mSupportIndex[k], mInputMemoryOffset); - // next coefficient index - if (k != mSupportSize-1) { - for(unsigned int l=0; l(mSupportIndex[k+1][l]) == mSupport[l]) { - mSupportIndex[k+1][l] = 0; - l++; - } - else stop = true; - } - } - } - - // // Check - // for(unsigned int l=0; l - void VectorBSplineInterpolateImageFunctionWithLUT:: - UpdatePrecomputedWeights() { - // mLUTTimer.Reset(); - // mLUTTimer.Start(); - mWeightsCalculator.SetSplineOrders(mSplineOrders); - mWeightsCalculator.SetSamplingFactors(mSamplingFactors); - mWeightsCalculator.ComputeTensorProducts(); - mWeightsAreUpToDate = true; - //DS - // coef = new TCoefficientType[mSupportSize]; - // mCorrectedSupportIndex.resize(mSupportSize); - // mCorrectedSupportOffset.resize(mSupportSize); - // mLUTTimer.Stop(); - // mLUTTimer.Print("LUT \t"); - } - //==================================================================== - - //==================================================================== - template - typename VectorBSplineInterpolateImageFunctionWithLUT::IndexType - VectorBSplineInterpolateImageFunctionWithLUT:: - GetSampleIndexOfPixelPosition(const ContinuousIndexType & x, IndexType & EvaluateIndex) const { + } + // Statistics (to be removed) /* - WARNING : sometimes, a floating number x could not really be - represented in memory. In this case, the difference between x and - floor(x) can be almost 1 (instead of 0). So we take into account - such special case, otherwise it could lead to annoying results. + *mIntrinsecError += fabs(index[l]-t2); + (*mNumberOfError)++; + if (fabs(index[l]-t2)> *mIntrinsecErrorMax) *mIntrinsecErrorMax = fabs(index[l]-t2); */ - // static const TCoefficientType tiny = 1.0e-7; - IndexType index; - - for(int l=0; l *mIntrinsecErrorMax) *mIntrinsecErrorMax = fabs(index[l]-t2); - */ - - // When to close to 1, take the next coefficient for odd order, but - // only change index for odd - if (index[l] == (int)mSamplingFactors[l]) { - index[l] = 0; - if (mSplineOrders[l] & 1) EvaluateIndex[l] = EvaluateIndex[l]+1; - } - } - // The end - return index; + // When to close to 1, take the next coefficient for odd order, but + // only change index for odd + if (index[l] == (int)mSamplingFactors[l]) { + index[l] = 0; + if (mSplineOrders[l] & 1) EvaluateIndex[l] = EvaluateIndex[l]+1; + } } + // The end + return index; +} - //==================================================================== - //==================================================================== - template - typename VectorBSplineInterpolateImageFunctionWithLUT::OutputType - VectorBSplineInterpolateImageFunctionWithLUT:: - EvaluateAtContinuousIndex(const ContinuousIndexType & x) const { +//==================================================================== - // For shorter coding - static const unsigned int d = TImageType::ImageDimension; +//==================================================================== +template +typename VectorBSplineInterpolateImageFunctionWithLUT::OutputType +VectorBSplineInterpolateImageFunctionWithLUT:: +EvaluateAtContinuousIndex(const ContinuousIndexType & x) const +{ - // Compute the index of the first interpolation coefficient in the coefficient image - IndexType evaluateIndex; - long indx; - for (unsigned int l=0; lm_SplineOrder / 2; - evaluateIndex[l] = indx; - } - else { // Use this index calculation for even splineOrder - if (mSplineOrders[l] == 0) evaluateIndex[l] = (long)rint(x[l]); - else { - indx = (long)vcl_floor((x[l]+ 0.5)) - mSplineOrders[l] / 2; //this->m_SplineOrder / 2; - evaluateIndex[l] = indx; - } - } - } - - // Compute index of precomputed weights and get pointer to first weights - const IndexType weightIndex = GetSampleIndexOfPixelPosition(x, evaluateIndex); - const TCoefficientType * pweights = mWeightsCalculator.GetFirstTensorProduct(weightIndex); - - // Check boundaries - bool boundaryCase = false; - for (unsigned int l=0; l= this->m_Coefficients->GetLargestPossibleRegion().GetSize(l)) { - boundaryCase = true; + // For shorter coding + static const unsigned int d = TImageType::ImageDimension; + + // Compute the index of the first interpolation coefficient in the coefficient image + IndexType evaluateIndex; + long indx; + for (unsigned int l=0; lm_SplineOrder / 2; + evaluateIndex[l] = indx; + } else { // Use this index calculation for even splineOrder + if (mSplineOrders[l] == 0) evaluateIndex[l] = (long)rint(x[l]); + else { + indx = (long)vcl_floor((x[l]+ 0.5)) - mSplineOrders[l] / 2; //this->m_SplineOrder / 2; + evaluateIndex[l] = indx; } } + } - // Pointer to support offset - const int * psupport; - - // Special case for boundary (to be changed ....) - std::vector correctedSupportOffset; - if (boundaryCase) { - // return -1000; - //std::vector coef(mSupportSize); - // DD(EvaluateIndex); - //std::vector CorrectedSupportOffset;//(mSupportSize); - std::vector correctedSupportIndex;//(mSupportSize); - correctedSupportIndex.resize(mSupportSize); - correctedSupportOffset.resize(mSupportSize); - for(unsigned int i=0; im_Coefficients->GetLargestPossibleRegion().GetSize(l); - // DD(a); - // DD(b); - long d2 = 2 * b - 2; - if (a < 0) { - correctedSupportIndex[i][l] = -a - d2*(-a/d2) - evaluateIndex[l];//mSupportIndex[i][l]-a; - } - else { - if (a>=b) { - correctedSupportIndex[i][l] = d2 - a - evaluateIndex[l]; - } - else { - correctedSupportIndex[i][l] = mSupportIndex[i][l]; //a - d2*(a/d2) - EvaluateIndex[l]; - } - /* - if (a>=b) { - correctedSupportIndex[i][l] = d2 - a - EvaluateIndex[l];//mSupportIndex[i][l] - (a-(b-1)); - } - else { - correctedSupportIndex[i][l] = mSupportIndex[i][l]; - } - */ - } - } - // DD(correctedSupportIndex[i]); - correctedSupportOffset[i] = itk::Index2Offset(correctedSupportIndex[i], mInputMemoryOffset); - } - // for (unsigned int l=0; lm_Coefficients->GetPixel(evaluateIndex)); - - // Main loop over BSpline support - CoefficientImagePixelType interpolated = 0.0; - for (unsigned int p=0; p= this->m_Coefficients->GetLargestPossibleRegion().GetSize(l)) { + boundaryCase = true; } + } - // Return interpolated value - return(interpolated); + // Pointer to support offset + const int * psupport; + + // Special case for boundary (to be changed ....) + std::vector correctedSupportOffset; + if (boundaryCase) { + // return -1000; + //std::vector coef(mSupportSize); + // DD(EvaluateIndex); + //std::vector CorrectedSupportOffset;//(mSupportSize); + std::vector correctedSupportIndex;//(mSupportSize); + correctedSupportIndex.resize(mSupportSize); + correctedSupportOffset.resize(mSupportSize); + for(unsigned int i=0; im_Coefficients->GetLargestPossibleRegion().GetSize(l); + // DD(a); + // DD(b); + long d2 = 2 * b - 2; + if (a < 0) { + correctedSupportIndex[i][l] = -a - d2*(-a/d2) - evaluateIndex[l];//mSupportIndex[i][l]-a; + } else { + if (a>=b) { + correctedSupportIndex[i][l] = d2 - a - evaluateIndex[l]; + } else { + correctedSupportIndex[i][l] = mSupportIndex[i][l]; //a - d2*(a/d2) - EvaluateIndex[l]; + } + /* + if (a>=b) { + correctedSupportIndex[i][l] = d2 - a - EvaluateIndex[l];//mSupportIndex[i][l] - (a-(b-1)); + } + else { + correctedSupportIndex[i][l] = mSupportIndex[i][l]; + } + */ + } + } + // DD(correctedSupportIndex[i]); + correctedSupportOffset[i] = itk::Index2Offset(correctedSupportIndex[i], mInputMemoryOffset); + } + // for (unsigned int l=0; lm_Coefficients->GetPixel(evaluateIndex)); + + // Main loop over BSpline support + CoefficientImagePixelType interpolated = 0.0; + for (unsigned int p=0; p - void - VectorBSplineInterpolateImageFunctionWithLUT:: - EvaluateWeightsAtContinuousIndex(const ContinuousIndexType& x, const TCoefficientType ** pweights, IndexType & evaluateIndex)const { + // Return interpolated value + return(interpolated); +} +//==================================================================== - // JV Compute BSpline weights if not up to date! Problem const: pass image as last - // if (!mWeightsAreUpToDate) UpdatePrecomputedWeights(); - // For shorter coding - static const unsigned int d = TImageType::ImageDimension; +//==================================================================== +template +void +VectorBSplineInterpolateImageFunctionWithLUT:: +EvaluateWeightsAtContinuousIndex(const ContinuousIndexType& x, const TCoefficientType ** pweights, IndexType & evaluateIndex)const +{ - // Compute the index of the first interpolation coefficient in the coefficient image - //IndexType evaluateIndex; - long indx; - for (unsigned int l=0; lm_SplineOrder / 2; - evaluateIndex[l] = indx; - } - else { // Use this index calculation for even splineOrder - if (mSplineOrders[l] == 0) evaluateIndex[l] = (long)rint(x[l]); - else { - indx = (long)vcl_floor((x[l]+ 0.5)) - mSplineOrders[l] / 2; //this->m_SplineOrder / 2; - evaluateIndex[l] = indx; - } + // JV Compute BSpline weights if not up to date! Problem const: pass image as last + // if (!mWeightsAreUpToDate) UpdatePrecomputedWeights(); + + // For shorter coding + static const unsigned int d = TImageType::ImageDimension; + + // Compute the index of the first interpolation coefficient in the coefficient image + //IndexType evaluateIndex; + long indx; + for (unsigned int l=0; lm_SplineOrder / 2; + evaluateIndex[l] = indx; + } else { // Use this index calculation for even splineOrder + if (mSplineOrders[l] == 0) evaluateIndex[l] = (long)rint(x[l]); + else { + indx = (long)vcl_floor((x[l]+ 0.5)) - mSplineOrders[l] / 2; //this->m_SplineOrder / 2; + evaluateIndex[l] = indx; } } - - // Compute index of precomputed weights and get pointer to first weights - const IndexType weightIndex = GetSampleIndexOfPixelPosition(x, evaluateIndex); - *pweights = mWeightsCalculator.GetFirstTensorProduct(weightIndex); - } - //==================================================================== + + // Compute index of precomputed weights and get pointer to first weights + const IndexType weightIndex = GetSampleIndexOfPixelPosition(x, evaluateIndex); + *pweights = mWeightsCalculator.GetFirstTensorProduct(weightIndex); + +} +//==================================================================== diff --git a/itk/itkBSplineDecompositionImageFilterWithOBD.txx b/itk/itkBSplineDecompositionImageFilterWithOBD.txx index ff9be13..3812bb5 100644 --- a/itk/itkBSplineDecompositionImageFilterWithOBD.txx +++ b/itk/itkBSplineDecompositionImageFilterWithOBD.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -48,7 +48,7 @@ template void BSplineDecompositionImageFilterWithOBD ::PrintSelf( - std::ostream& os, + std::ostream& os, Indent indent) const { Superclass::PrintSelf( os, indent ); @@ -61,50 +61,44 @@ template bool BSplineDecompositionImageFilterWithOBD ::DataToCoefficients1D() -{ +{ + + // See Unser, 1993, Part II, Equation 2.5, + // or Unser, 1999, Box 2. for an explaination. - // See Unser, 1993, Part II, Equation 2.5, - // or Unser, 1999, Box 2. for an explaination. + double c0 = 1.0; - double c0 = 1.0; - - if (m_DataLength[m_IteratorDirection] == 1) //Required by mirror boundaries - { + if (m_DataLength[m_IteratorDirection] == 1) { //Required by mirror boundaries return false; - } + } // Compute overall gain - for (int k = 0; k < m_NumberOfPoles; k++) - { - // Note for cubic splines lambda = 6 + for (int k = 0; k < m_NumberOfPoles; k++) { + // Note for cubic splines lambda = 6 c0 = c0 * (1.0 - m_SplinePoles[k]) * (1.0 - 1.0 / m_SplinePoles[k]); - } + } - // apply the gain - for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) - { + // apply the gain + for (unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] *= c0; - } + } - // loop over all poles - for (int k = 0; k < m_NumberOfPoles; k++) - { - // causal initialization + // loop over all poles + for (int k = 0; k < m_NumberOfPoles; k++) { + // causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); - // causal recursion - for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) - { + // causal recursion + for (unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++) { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; - } + } - // anticausal initialization + // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); - // anticausal recursion - for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) - { + // anticausal recursion + for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n--) { m_Scratch[n] = m_SplinePoles[k] * (m_Scratch[n + 1] - m_Scratch[n]); - } } + } return true; } @@ -115,10 +109,9 @@ void BSplineDecompositionImageFilterWithOBD ::SetSplineOrder(unsigned int SplineOrder) { - if (SplineOrder == m_SplineOrder) - { + if (SplineOrder == m_SplineOrder) { return; - } + } m_SplineOrder = SplineOrder; this->SetPoles(); this->Modified(); @@ -140,45 +133,44 @@ BSplineDecompositionImageFilterWithOBD ::SetPoles() { /* See Unser, 1997. Part II, Table I for Pole values */ - // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, + // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac N. Bankman, // 2000, pg. 416. - switch (m_SplineOrder) - { - - case 3: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; - break; - case 0: - m_NumberOfPoles = 0; - break; - case 1: - m_NumberOfPoles = 0; - break; - case 2: - m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; - break; - case 4: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; - m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; - break; - case 5: - m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) - - 13.0 / 2.0; - break; - default: - // SplineOrder not implemented yet. - ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION); - err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); - throw err; - break; - } + switch (m_SplineOrder) { + + case 3: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; + break; + case 0: + m_NumberOfPoles = 0; + break; + case 1: + m_NumberOfPoles = 0; + break; + case 2: + m_NumberOfPoles = 1; + m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; + break; + case 4: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(664.0 - vcl_sqrt(438976.0)) + vcl_sqrt(304.0) - 19.0; + m_SplinePoles[1] = vcl_sqrt(664.0 + vcl_sqrt(438976.0)) - vcl_sqrt(304.0) - 19.0; + break; + case 5: + m_NumberOfPoles = 2; + m_SplinePoles[0] = vcl_sqrt(135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0)) + vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + m_SplinePoles[1] = vcl_sqrt(135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0)) - vcl_sqrt(105.0 / 4.0) + - 13.0 / 2.0; + break; + default: + // SplineOrder not implemented yet. + ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION); + err.SetDescription( "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet." ); + throw err; + break; + } } @@ -196,34 +188,29 @@ BSplineDecompositionImageFilterWithOBD /* this initialization corresponds to mirror boundaries */ horizon = m_DataLength[m_IteratorDirection]; zn = z; - if (m_Tolerance > 0.0) - { + if (m_Tolerance > 0.0) { horizon = (long)vcl_ceil(log(m_Tolerance) / vcl_log(fabs(z))); - } - if (horizon < m_DataLength[m_IteratorDirection]) - { + } + if (horizon < m_DataLength[m_IteratorDirection]) { /* accelerated loop */ sum = m_Scratch[0]; // verify this - for (unsigned int n = 1; n < horizon; n++) - { + for (unsigned int n = 1; n < horizon; n++) { sum += zn * m_Scratch[n]; zn *= z; - } - m_Scratch[0] = sum; } - else { - /* full loop */ - iz = 1.0 / z; - z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); - sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; - z2n *= z2n * iz; - for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) - { - sum += (zn + z2n) * m_Scratch[n]; - zn *= z; - z2n *= iz; + m_Scratch[0] = sum; + } else { + /* full loop */ + iz = 1.0 / z; + z2n = vcl_pow(z, (double)(m_DataLength[m_IteratorDirection] - 1L)); + sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; + z2n *= z2n * iz; + for (unsigned int n = 1; n <= (m_DataLength[m_IteratorDirection] - 2); n++) { + sum += (zn + z2n) * m_Scratch[n]; + zn *= z; + z2n *= iz; } - m_Scratch[0] = sum / (1.0 - zn * zn); + m_Scratch[0] = sum / (1.0 - zn * zn); } } @@ -233,11 +220,11 @@ void BSplineDecompositionImageFilterWithOBD ::SetInitialAntiCausalCoefficient(double z) { - // this initialization corresponds to mirror boundaries + // this initialization corresponds to mirror boundaries /* See Unser, 1999, Box 2 for explaination */ // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html m_Scratch[m_DataLength[m_IteratorDirection] - 1] = - (z / (z * z - 1.0)) * + (z / (z * z - 1.0)) * (z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1]); } @@ -258,8 +245,7 @@ BSplineDecompositionImageFilterWithOBD // Initialize coeffient array this->CopyImageToImage(); // Coefficients are initialized to the input data - for (unsigned int n=0; n < ImageDimension; n++) - { + for (unsigned int n=0; n < ImageDimension; n++) { m_IteratorDirection = n; // Loop through each dimension @@ -270,22 +256,21 @@ BSplineDecompositionImageFilterWithOBD OutputLinearIterator CIterator( output, output->GetBufferedRegion() ); CIterator.SetDirection( m_IteratorDirection ); // For each data vector - while ( !CIterator.IsAtEnd() ) - { + while ( !CIterator.IsAtEnd() ) { // Copy coefficients to scratch this->CopyCoefficientsToScratch( CIterator ); // Perform 1D BSpline calculations this->DataToCoefficients1D(); - + // Copy scratch back to coefficients. // Brings us back to the end of the line we were working on. CIterator.GoToBeginOfLine(); this->CopyScratchToCoefficients( CIterator ); // m_Scratch = m_Image; CIterator.NextLine(); progress.CompletedPixel(); - } } + } } @@ -308,13 +293,12 @@ BSplineDecompositionImageFilterWithOBD inIt = inIt.Begin(); outIt = outIt.Begin(); - while ( !outIt.IsAtEnd() ) - { + while ( !outIt.IsAtEnd() ) { outIt.Set( static_cast( inIt.Get() ) ); ++inIt; ++outIt; - } - + } + } @@ -328,12 +312,11 @@ BSplineDecompositionImageFilterWithOBD { typedef typename TOutputImage::PixelType OutputPixelType; unsigned long j = 0; - while ( !Iter.IsAtEndOfLine() ) - { + while ( !Iter.IsAtEndOfLine() ) { Iter.Set( static_cast( m_Scratch[j] ) ); ++Iter; ++j; - } + } } @@ -347,12 +330,11 @@ BSplineDecompositionImageFilterWithOBD ::CopyCoefficientsToScratch(OutputLinearIterator & Iter) { unsigned long j = 0; - while ( !Iter.IsAtEndOfLine() ) - { + while ( !Iter.IsAtEndOfLine() ) { m_Scratch[j] = static_cast( Iter.Get() ) ; ++Iter; ++j; - } + } } @@ -367,10 +349,9 @@ BSplineDecompositionImageFilterWithOBD // this filter requires the all of the input image to be in // the buffer InputImagePointer inputPtr = const_cast< TInputImage * > ( this->GetInput() ); - if( inputPtr ) - { + if( inputPtr ) { inputPtr->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -388,10 +369,9 @@ BSplineDecompositionImageFilterWithOBD // the buffer TOutputImage *imgData; imgData = dynamic_cast( output ); - if( imgData ) - { + if( imgData ) { imgData->SetRequestedRegionToLargestPossibleRegion(); - } + } } @@ -409,13 +389,11 @@ BSplineDecompositionImageFilterWithOBD m_DataLength = inputPtr->GetBufferedRegion().GetSize(); unsigned long maxLength = 0; - for ( unsigned int n = 0; n < ImageDimension; n++ ) - { - if ( m_DataLength[n] > maxLength ) - { + for ( unsigned int n = 0; n < ImageDimension; n++ ) { + if ( m_DataLength[n] > maxLength ) { maxLength = m_DataLength[n]; - } } + } m_Scratch.resize( maxLength ); // Allocate memory for output image diff --git a/itk/itkBSplineInterpolateImageFunctionWithLUT.txx b/itk/itkBSplineInterpolateImageFunctionWithLUT.txx index 3c9dff7..b059bc3 100644 --- a/itk/itkBSplineInterpolateImageFunctionWithLUT.txx +++ b/itk/itkBSplineInterpolateImageFunctionWithLUT.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,394 +18,395 @@ #ifndef _ITKINTERPOLATEIMAGEFUNCTIONWITHLUT_TXX #define _ITKINTERPOLATEIMAGEFUNCTIONWITHLUT_TXX /* ========================================================================= - + @file itkBSplineInterpolateImageFunctionWithLUT.txx @author David Sarrut -Copyright (c) -* CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). +Copyright (c) +* CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details. * Léon Bérard cancer center, 28 rue Laënnec, 69373 Lyon cedex 08, France * http://www.creatis.insa-lyon.fr/rio - + 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. - + ========================================================================= */ namespace itk { - //==================================================================== - template - BSplineInterpolateImageFunctionWithLUT:: - BSplineInterpolateImageFunctionWithLUT():Superclass() { - // Set default values - //for(int i=0; i +BSplineInterpolateImageFunctionWithLUT:: +BSplineInterpolateImageFunctionWithLUT():Superclass() +{ + // Set default values + //for(int i=0; i - void BSplineInterpolateImageFunctionWithLUT:: - SetLUTSamplingFactor(const int& s) { - for(int i=0; i +void BSplineInterpolateImageFunctionWithLUT:: +SetLUTSamplingFactor(const int& s) +{ + for(int i=0; i +void BSplineInterpolateImageFunctionWithLUT:: +SetLUTSamplingFactors(const SizeType& s) +{ + for(int i=0; i - void BSplineInterpolateImageFunctionWithLUT:: - SetLUTSamplingFactors(const SizeType& s) { - for(int i=0; i +// void BSplineInterpolateImageFunctionWithLUT:: +// SetOutputSpacing(const SpacingType & s) { +// for(int i=0; i +void BSplineInterpolateImageFunctionWithLUT:: +SetSplineOrder(const unsigned int& SplineOrder) +{ + Superclass::SetSplineOrder(SplineOrder); + // Compute support and half size + static const int d = TImageType::ImageDimension; + for(int l=0; l - // void BSplineInterpolateImageFunctionWithLUT:: - // SetOutputSpacing(const SpacingType & s) { - // for(int i=0; i - void BSplineInterpolateImageFunctionWithLUT:: - SetSplineOrder(const unsigned int& SplineOrder) { - Superclass::SetSplineOrder(SplineOrder); - // Compute support and half size - static const int d = TImageType::ImageDimension; - for(int l=0; l +void BSplineInterpolateImageFunctionWithLUT:: +SetSplineOrders(const SizeType& SplineOrders) +{ + mSplineOrders=SplineOrders; + + // Compute support and half size + static const int d = TImageType::ImageDimension; + for(int l=0; l - void BSplineInterpolateImageFunctionWithLUT:: - SetSplineOrders(const SizeType& SplineOrders) { - mSplineOrders=SplineOrders; - - // Compute support and half size - static const int d = TImageType::ImageDimension; - for(int l=0; l - void BSplineInterpolateImageFunctionWithLUT:: - SetInputImage(const TImageType * inputData) { +//==================================================================== +template +void BSplineInterpolateImageFunctionWithLUT:: +SetInputImage(const TImageType * inputData) +{ - //============================== - // if (!mInputIsCoef) - // { - Superclass::SetInputImage(inputData); - // } - - //============================== - // //JV Don't call superclass (decomposition filter is executeed each time!) - // else - // { - // this->m_Coefficients = inputData; - // if ( this->m_Coefficients.IsNotNull()) - // { - // this->m_DataLength = this->m_Coefficients->GetBufferedRegion().GetSize(); - // } - - // //Call super-superclass in case more input arrives - // itk::ImageFunction::RealType, TCoefficientType>::SetInputImage(inputData); - // } - if (!inputData) return; - UpdateWeightsProperties(); + //============================== + // if (!mInputIsCoef) + // { + Superclass::SetInputImage(inputData); + // } + + //============================== + // //JV Don't call superclass (decomposition filter is executeed each time!) + // else + // { + // this->m_Coefficients = inputData; + // if ( this->m_Coefficients.IsNotNull()) + // { + // this->m_DataLength = this->m_Coefficients->GetBufferedRegion().GetSize(); + // } + + // //Call super-superclass in case more input arrives + // itk::ImageFunction::RealType, TCoefficientType>::SetInputImage(inputData); + // } + if (!inputData) return; + UpdateWeightsProperties(); + +} +//==================================================================== +template +void BSplineInterpolateImageFunctionWithLUT:: +UpdateWeightsProperties() +{ + + // Compute Memory offset inside coefficients images (for looping over coefficients) + static const unsigned int d = TImageType::ImageDimension; + mInputMemoryOffset[0] = 1; + for(unsigned int l=1; lm_Coefficients->GetLargestPossibleRegion().GetSize(l-1); } - - //==================================================================== - template - void BSplineInterpolateImageFunctionWithLUT:: - UpdateWeightsProperties() { - - // Compute Memory offset inside coefficients images (for looping over coefficients) - static const unsigned int d = TImageType::ImageDimension; - mInputMemoryOffset[0] = 1; - for(unsigned int l=1; lm_Coefficients->GetLargestPossibleRegion().GetSize(l-1); - } - - //JV Put here? - if (!mWeightsAreUpToDate) - { - // Compute mSupportOffset according to input size - mSupportOffset.resize(mSupportSize); - mSupportIndex.resize(mSupportSize); - for(unsigned int l=0; l(mSupportIndex[k], mInputMemoryOffset); - // next coefficient index - if (k != mSupportSize-1) { - for(unsigned int l=0; l(mSupportIndex[k+1][l]) == mSupport[l]) { - mSupportIndex[k+1][l] = 0; - l++; - } - else stop = true; - } - } - } - - // // Check - // for(unsigned int l=0; l(mSupportIndex[k], mInputMemoryOffset); + // next coefficient index + if (k != mSupportSize-1) { + for(unsigned int l=0; l(mSupportIndex[k+1][l]) == mSupport[l]) { + mSupportIndex[k+1][l] = 0; + l++; + } else stop = true; + } } - // Initialisation - // *mIntrinsecErrorMax = *mIntrinsecError = 0.0; - // *mNumberOfError = 0; - } - //==================================================================== - - //==================================================================== - template - void BSplineInterpolateImageFunctionWithLUT:: - UpdatePrecomputedWeights() { - // mLUTTimer.Reset(); - // mLUTTimer.Start(); - mWeightsCalculator.SetSplineOrders(mSplineOrders); - mWeightsCalculator.SetSamplingFactors(mSamplingFactors); - mWeightsCalculator.ComputeTensorProducts(); - mWeightsAreUpToDate = true; - //DS - // coef = new TCoefficientType[mSupportSize]; - // mCorrectedSupportIndex.resize(mSupportSize); - // mCorrectedSupportOffset.resize(mSupportSize); - // mLUTTimer.Stop(); - // mLUTTimer.Print("LUT \t"); + } + + // // Check + // for(unsigned int l=0; l - typename BSplineInterpolateImageFunctionWithLUT::IndexType - BSplineInterpolateImageFunctionWithLUT:: - GetSampleIndexOfPixelPosition(const ContinuousIndexType & x, IndexType & EvaluateIndex) const { +//==================================================================== +template +void BSplineInterpolateImageFunctionWithLUT:: +UpdatePrecomputedWeights() +{ + // mLUTTimer.Reset(); + // mLUTTimer.Start(); + mWeightsCalculator.SetSplineOrders(mSplineOrders); + mWeightsCalculator.SetSamplingFactors(mSamplingFactors); + mWeightsCalculator.ComputeTensorProducts(); + mWeightsAreUpToDate = true; + //DS + // coef = new TCoefficientType[mSupportSize]; + // mCorrectedSupportIndex.resize(mSupportSize); + // mCorrectedSupportOffset.resize(mSupportSize); + // mLUTTimer.Stop(); + // mLUTTimer.Print("LUT \t"); +} +//==================================================================== +//==================================================================== +template +typename BSplineInterpolateImageFunctionWithLUT::IndexType +BSplineInterpolateImageFunctionWithLUT:: +GetSampleIndexOfPixelPosition(const ContinuousIndexType & x, IndexType & EvaluateIndex) const +{ + + /* + WARNING : sometimes, a floating number x could not really be + represented in memory. In this case, the difference between x and + floor(x) can be almost 1 (instead of 0). So we take into account + such special case, otherwise it could lead to annoying results. + */ + // static const TCoefficientType tiny = 1.0e-7; + IndexType index; + + for(int l=0; l *mIntrinsecErrorMax) *mIntrinsecErrorMax = fabs(index[l]-t2); */ - // static const TCoefficientType tiny = 1.0e-7; - IndexType index; - - for(int l=0; l *mIntrinsecErrorMax) *mIntrinsecErrorMax = fabs(index[l]-t2); - */ - - // When to close to 1, take the next coefficient for odd order, but - // only change index for odd - if (index[l] == (int)mSamplingFactors[l]) { - index[l] = 0; - if (mSplineOrders[l] & 1) EvaluateIndex[l] = EvaluateIndex[l]+1; - } - } - // The end - return index; + // When to close to 1, take the next coefficient for odd order, but + // only change index for odd + if (index[l] == (int)mSamplingFactors[l]) { + index[l] = 0; + if (mSplineOrders[l] & 1) EvaluateIndex[l] = EvaluateIndex[l]+1; + } } + // The end + return index; +} - //==================================================================== - //==================================================================== - template - typename BSplineInterpolateImageFunctionWithLUT::OutputType - BSplineInterpolateImageFunctionWithLUT:: - EvaluateAtContinuousIndex(const ContinuousIndexType & x) const { +//==================================================================== - // For shorter coding - static const unsigned int d = TImageType::ImageDimension; +//==================================================================== +template +typename BSplineInterpolateImageFunctionWithLUT::OutputType +BSplineInterpolateImageFunctionWithLUT:: +EvaluateAtContinuousIndex(const ContinuousIndexType & x) const +{ - // Compute the index of the first interpolation coefficient in the coefficient image - IndexType evaluateIndex; - long indx; - for (unsigned int l=0; lm_SplineOrder / 2; - evaluateIndex[l] = indx; - } - else { // Use this index calculation for even splineOrder - if (mSplineOrders[l] == 0) evaluateIndex[l] = (long)rint(x[l]); - else { - indx = (long)vcl_floor((x[l]+ 0.5)) - mSplineOrders[l] / 2; //this->m_SplineOrder / 2; - evaluateIndex[l] = indx; - } + // For shorter coding + static const unsigned int d = TImageType::ImageDimension; + + // Compute the index of the first interpolation coefficient in the coefficient image + IndexType evaluateIndex; + long indx; + for (unsigned int l=0; lm_SplineOrder / 2; + evaluateIndex[l] = indx; + } else { // Use this index calculation for even splineOrder + if (mSplineOrders[l] == 0) evaluateIndex[l] = (long)rint(x[l]); + else { + indx = (long)vcl_floor((x[l]+ 0.5)) - mSplineOrders[l] / 2; //this->m_SplineOrder / 2; + evaluateIndex[l] = indx; } } - - // Compute index of precomputed weights and get pointer to first weights - const IndexType weightIndex = GetSampleIndexOfPixelPosition(x, evaluateIndex); - const TCoefficientType * pweights = mWeightsCalculator.GetFirstTensorProduct(weightIndex); - - // Check boundaries - bool boundaryCase = false; - for (unsigned int l=0; l= this->m_Coefficients->GetLargestPossibleRegion().GetSize(l)) { - boundaryCase = true; - } + } + + // Compute index of precomputed weights and get pointer to first weights + const IndexType weightIndex = GetSampleIndexOfPixelPosition(x, evaluateIndex); + const TCoefficientType * pweights = mWeightsCalculator.GetFirstTensorProduct(weightIndex); + + // Check boundaries + bool boundaryCase = false; + for (unsigned int l=0; l= this->m_Coefficients->GetLargestPossibleRegion().GetSize(l)) { + boundaryCase = true; } + } - // Pointer to support offset - const int * psupport; - - // Special case for boundary (to be changed ....) - std::vector correctedSupportOffset; - if (boundaryCase) { - // return -1000; - //std::vector coef(mSupportSize); - // DD(EvaluateIndex); - //std::vector CorrectedSupportOffset;//(mSupportSize); - std::vector correctedSupportIndex;//(mSupportSize); - correctedSupportIndex.resize(mSupportSize); - correctedSupportOffset.resize(mSupportSize); - for(unsigned int i=0; im_Coefficients->GetLargestPossibleRegion().GetSize(l); - // DD(a); - // DD(b); - long d2 = 2 * b - 2; - if (a < 0) { - correctedSupportIndex[i][l] = -a - d2*(-a/d2) - evaluateIndex[l];//mSupportIndex[i][l]-a; - } - else { - if (a>=b) { - correctedSupportIndex[i][l] = d2 - a - evaluateIndex[l]; - } - else { - correctedSupportIndex[i][l] = mSupportIndex[i][l]; //a - d2*(a/d2) - EvaluateIndex[l]; - } - /* - if (a>=b) { - correctedSupportIndex[i][l] = d2 - a - EvaluateIndex[l];//mSupportIndex[i][l] - (a-(b-1)); - } - else { - correctedSupportIndex[i][l] = mSupportIndex[i][l]; - } - */ - } - } - // DD(correctedSupportIndex[i]); - correctedSupportOffset[i] = itk::Index2Offset(correctedSupportIndex[i], mInputMemoryOffset); + // Pointer to support offset + const int * psupport; + + // Special case for boundary (to be changed ....) + std::vector correctedSupportOffset; + if (boundaryCase) { + // return -1000; + //std::vector coef(mSupportSize); + // DD(EvaluateIndex); + //std::vector CorrectedSupportOffset;//(mSupportSize); + std::vector correctedSupportIndex;//(mSupportSize); + correctedSupportIndex.resize(mSupportSize); + correctedSupportOffset.resize(mSupportSize); + for(unsigned int i=0; im_Coefficients->GetLargestPossibleRegion().GetSize(l); + // DD(a); + // DD(b); + long d2 = 2 * b - 2; + if (a < 0) { + correctedSupportIndex[i][l] = -a - d2*(-a/d2) - evaluateIndex[l];//mSupportIndex[i][l]-a; + } else { + if (a>=b) { + correctedSupportIndex[i][l] = d2 - a - evaluateIndex[l]; + } else { + correctedSupportIndex[i][l] = mSupportIndex[i][l]; //a - d2*(a/d2) - EvaluateIndex[l]; + } + /* + if (a>=b) { + correctedSupportIndex[i][l] = d2 - a - EvaluateIndex[l];//mSupportIndex[i][l] - (a-(b-1)); + } + else { + correctedSupportIndex[i][l] = mSupportIndex[i][l]; + } + */ + } } - // for (unsigned int l=0; l(correctedSupportIndex[i], mInputMemoryOffset); } + // for (unsigned int l=0; lm_Coefficients->GetPixel(evaluateIndex)); + // Get pointer to first coefficient. Even if in some boundary cases, + // EvaluateIndex is out of the coefficient image, + const TCoefficientType * pcoef = &(this->m_Coefficients->GetPixel(evaluateIndex)); - // Main loop over BSpline support - TCoefficientType interpolated = 0.0; - for (unsigned int p=0; p - Copyright (c) - * CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). + Copyright (c) + * CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details. * Léon Bérard cancer center, 28 rue Laënnec, 69373 Lyon cedex 08, France * http://www.creatis.insa-lyon.fr/rio - + 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 ITKBSPLINEWEIGHTSCALCULATOR_TXX @@ -38,7 +38,8 @@ //==================================================================== template -typename Index::IndexValueType Index2Offset(const Index & index, const Index & offsetTable) { +typename Index::IndexValueType Index2Offset(const Index & index, const Index & offsetTable) +{ long v = index[0]; for(int l=1; l::IndexValueType Index2Offset(const Index //==================================================================== template BSplineWeightsCalculator:: -BSplineWeightsCalculator() { +BSplineWeightsCalculator() +{ mWeightsAreUpToDate = false; } //==================================================================== @@ -58,7 +60,8 @@ BSplineWeightsCalculator() { //==================================================================== template void BSplineWeightsCalculator:: -SetSplineOrder(int splineOrder) { +SetSplineOrder(int splineOrder) +{ SizeType temp; for(int l=0; l void BSplineWeightsCalculator:: -SetSplineOrders(const SizeType & splineOrder) { +SetSplineOrders(const SizeType & splineOrder) +{ // Compute support size mSupportSize = 1; for(int l=0; l void BSplineWeightsCalculator:: -SetSamplingFactor(int sampling) { +SetSamplingFactor(int sampling) +{ for(int l=0; l void BSplineWeightsCalculator:: -SetSamplingFactors(const SizeType & sampling) { +SetSamplingFactors(const SizeType & sampling) +{ for(int l=0; l -typename BSplineWeightsCalculator::InitialWeightsType & +typename BSplineWeightsCalculator::InitialWeightsType & BSplineWeightsCalculator:: -GetInitialWeights(int order) { +GetInitialWeights(int order) +{ if (!mBasisFunctionCoefficientsMatrixAreUpToDate[order]) ComputeBasisFunctionCoefficientsMatrix(order); return mBasisFunctionCoefficientsMatrix[order]; } //==================================================================== //==================================================================== -template inline T factorial(T rhs) { - T lhs = (T)1; +template inline T factorial(T rhs) +{ + T lhs = (T)1; for(T x=(T)1; x<=rhs; ++x) { lhs *= x; - } + } return lhs; } //==================================================================== @@ -140,7 +147,8 @@ template inline T factorial(T rhs) { //==================================================================== template double BSplineWeightsCalculator:: -BinomialCoefficient(int i, int j) { +BinomialCoefficient(int i, int j) +{ double f = (factorial(i))/(factorial(j) * factorial(i-j)); return f; } @@ -149,7 +157,8 @@ BinomialCoefficient(int i, int j) { //==================================================================== template void BSplineWeightsCalculator:: -ComputeBasisFunctionCoefficientsMatrix(int order) { +ComputeBasisFunctionCoefficientsMatrix(int order) +{ // Compute the sxs matrix of coefficients used to build the different // polynomials. With s the support is order+1. int s = order+1; @@ -160,9 +169,9 @@ ComputeBasisFunctionCoefficientsMatrix(int order) { for(int j=0; j TCoefficientType BSplineWeightsCalculator:: -BSplineEvaluate(int order, int k, double e) { - // Evaluate a BSpline +BSplineEvaluate(int order, int k, double e) +{ + // Evaluate a BSpline int s=order+1; TCoefficientType v = 0.0; for(int p=0; p void BSplineWeightsCalculator:: -ComputeSampledWeights1D(std::vector > & w, int order, int sampling) { +ComputeSampledWeights1D(std::vector > & w, int order, int sampling) +{ int s = order+1; w.resize(s); for(int k=0; k > & w, int ord } e += offset; if (fabs(1.0-e)<=1e-6) e = 1.0; // (for even order) - if (e>=1.0) e = e-1.0; + if (e>=1.0) e = e-1.0; } } //==================================================================== @@ -218,10 +229,11 @@ ComputeSampledWeights1D(std::vector > & w, int ord //==================================================================== template void BSplineWeightsCalculator:: -ComputeSampledWeights() { +ComputeSampledWeights() +{ mWeights.resize(VDimension); // Loop over dimension to compute weights - for(int l=0; l void BSplineWeightsCalculator:: -ComputeTensorProducts() { +ComputeTensorProducts() +{ // Initial BSpline samples weights ComputeSampledWeights(); - + // tensor product memory offsets mTensorProductMemoryOffset[0] = 1; - for(int l=1; l const TCoefficientType * BSplineWeightsCalculator:: -GetFirstTensorProduct(const IndexType & index) const { +GetFirstTensorProduct(const IndexType & index) const +{ int i = Index2Offset(index, mTensorProductMemoryOffset); return &(mTensorProducts[i][0]); } diff --git a/itk/itkImageToVTKImageFilter.txx b/itk/itkImageToVTKImageFilter.txx index dada86d..5bce506 100644 --- a/itk/itkImageToVTKImageFilter.txx +++ b/itk/itkImageToVTKImageFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -15,130 +15,129 @@ - BSD See included LICENSE.txt file - CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html ======================================================================-====*/ -#ifndef _itkImageToVTKImageFilter_txx -#define _itkImageToVTKImageFilter_txx -#include "itkImageToVTKImageFilter.h" - -namespace itk -{ - - - -/** - * Constructor - */ -template -ImageToVTKImageFilter -::ImageToVTKImageFilter() -{ - - m_Importer = vtkImageImport::New(); - - m_Exporter = ExporterFilterType::New(); - - m_Importer->SetUpdateInformationCallback(m_Exporter->GetUpdateInformationCallback()); - m_Importer->SetPipelineModifiedCallback(m_Exporter->GetPipelineModifiedCallback()); - m_Importer->SetWholeExtentCallback(m_Exporter->GetWholeExtentCallback()); - m_Importer->SetSpacingCallback(m_Exporter->GetSpacingCallback()); - m_Importer->SetOriginCallback(m_Exporter->GetOriginCallback()); - m_Importer->SetScalarTypeCallback(m_Exporter->GetScalarTypeCallback()); - m_Importer->SetNumberOfComponentsCallback(m_Exporter->GetNumberOfComponentsCallback()); - m_Importer->SetPropagateUpdateExtentCallback(m_Exporter->GetPropagateUpdateExtentCallback()); - m_Importer->SetUpdateDataCallback(m_Exporter->GetUpdateDataCallback()); - m_Importer->SetDataExtentCallback(m_Exporter->GetDataExtentCallback()); - m_Importer->SetBufferPointerCallback(m_Exporter->GetBufferPointerCallback()); - m_Importer->SetCallbackUserData(m_Exporter->GetCallbackUserData()); - -} - - - - -/** - * Destructor - */ -template -ImageToVTKImageFilter -::~ImageToVTKImageFilter() -{ - if ( m_Importer ) - { - m_Importer->Delete(); - m_Importer = 0; - } -} - - - -/** - * Set an itk::Image as input - */ -template -void -ImageToVTKImageFilter -::SetInput( const InputImageType * inputImage ) -{ - m_Exporter->SetInput( inputImage ); -} - - - -/** - * Get a vtkImage as output - */ -template -vtkImageData * -ImageToVTKImageFilter -::GetOutput() const -{ - return m_Importer->GetOutput(); -} - - - - -/** - * Get the importer filter - */ -template -vtkImageImport * -ImageToVTKImageFilter -::GetImporter() const -{ - return m_Importer; -} - - - -/** - * Get the exporter filter - */ -template -typename ImageToVTKImageFilter::ExporterFilterType * -ImageToVTKImageFilter -::GetExporter() const -{ - return m_Exporter.GetPointer(); -} - - - -/** - * Delegate the Update to the importer - */ -template -void -ImageToVTKImageFilter -::Update() -{ - m_Importer->Update(); -} - - - - - -} // end namespace itk - -#endif - +#ifndef _itkImageToVTKImageFilter_txx +#define _itkImageToVTKImageFilter_txx +#include "itkImageToVTKImageFilter.h" + +namespace itk +{ + + + +/** + * Constructor + */ +template +ImageToVTKImageFilter +::ImageToVTKImageFilter() +{ + + m_Importer = vtkImageImport::New(); + + m_Exporter = ExporterFilterType::New(); + + m_Importer->SetUpdateInformationCallback(m_Exporter->GetUpdateInformationCallback()); + m_Importer->SetPipelineModifiedCallback(m_Exporter->GetPipelineModifiedCallback()); + m_Importer->SetWholeExtentCallback(m_Exporter->GetWholeExtentCallback()); + m_Importer->SetSpacingCallback(m_Exporter->GetSpacingCallback()); + m_Importer->SetOriginCallback(m_Exporter->GetOriginCallback()); + m_Importer->SetScalarTypeCallback(m_Exporter->GetScalarTypeCallback()); + m_Importer->SetNumberOfComponentsCallback(m_Exporter->GetNumberOfComponentsCallback()); + m_Importer->SetPropagateUpdateExtentCallback(m_Exporter->GetPropagateUpdateExtentCallback()); + m_Importer->SetUpdateDataCallback(m_Exporter->GetUpdateDataCallback()); + m_Importer->SetDataExtentCallback(m_Exporter->GetDataExtentCallback()); + m_Importer->SetBufferPointerCallback(m_Exporter->GetBufferPointerCallback()); + m_Importer->SetCallbackUserData(m_Exporter->GetCallbackUserData()); + +} + + + + +/** + * Destructor + */ +template +ImageToVTKImageFilter +::~ImageToVTKImageFilter() +{ + if ( m_Importer ) { + m_Importer->Delete(); + m_Importer = 0; + } +} + + + +/** + * Set an itk::Image as input + */ +template +void +ImageToVTKImageFilter +::SetInput( const InputImageType * inputImage ) +{ + m_Exporter->SetInput( inputImage ); +} + + + +/** + * Get a vtkImage as output + */ +template +vtkImageData * +ImageToVTKImageFilter +::GetOutput() const +{ + return m_Importer->GetOutput(); +} + + + + +/** + * Get the importer filter + */ +template +vtkImageImport * +ImageToVTKImageFilter +::GetImporter() const +{ + return m_Importer; +} + + + +/** + * Get the exporter filter + */ +template +typename ImageToVTKImageFilter::ExporterFilterType * +ImageToVTKImageFilter +::GetExporter() const +{ + return m_Exporter.GetPointer(); +} + + + +/** + * Delegate the Update to the importer + */ +template +void +ImageToVTKImageFilter +::Update() +{ + m_Importer->Update(); +} + + + + + +} // end namespace itk + +#endif + diff --git a/itk/itkRayCastInterpolateImageFunctionWithOrigin.txx b/itk/itkRayCastInterpolateImageFunctionWithOrigin.txx index 2d95598..b2cbb76 100644 --- a/itk/itkRayCastInterpolateImageFunctionWithOrigin.txx +++ b/itk/itkRayCastInterpolateImageFunctionWithOrigin.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -24,7 +24,8 @@ // Put the helper class in an anonymous namespace so that it is not // exposed to the user -namespace { +namespace +{ /** \class Helper class to maintain state when casting a ray. * This helper class keeps the RayCastInterpolateImageFunctionWithOrigin thread safe. @@ -60,10 +61,9 @@ public: /** * Set the image class */ - void SetImage(const InputImageType *input) - { + void SetImage(const InputImageType *input) { m_Image = input; - } + } /** * Initialise the ray using the position and direction of a line. @@ -89,10 +89,9 @@ public: * * \return True if a valid ray was specified. */ - bool Integrate(double &integral) - { + bool Integrate(double &integral) { return IntegrateAboveThreshold(integral, 0); - }; + }; /** \brief @@ -131,8 +130,8 @@ public: if (m_ValidRay) return vcl_sqrt(m_VoxelIncrement[0]*spacing[0]*m_VoxelIncrement[0]*spacing[0] - + m_VoxelIncrement[1]*spacing[1]*m_VoxelIncrement[1]*spacing[1] - + m_VoxelIncrement[2]*spacing[2]*m_VoxelIncrement[2]*spacing[2] ); + + m_VoxelIncrement[1]*spacing[1]*m_VoxelIncrement[1]*spacing[1] + + m_VoxelIncrement[2]*spacing[2]*m_VoxelIncrement[2]*spacing[2] ); else return 0.; }; @@ -361,34 +360,34 @@ RayCastHelper m_BoundingCorner[0][0] = m_BoundingCorner[1][0] = - m_BoundingCorner[2][0] = - m_BoundingCorner[3][0] = 0; + m_BoundingCorner[2][0] = + m_BoundingCorner[3][0] = 0; m_BoundingCorner[4][0] = m_BoundingCorner[5][0] = - m_BoundingCorner[6][0] = - m_BoundingCorner[7][0] = m_VoxelDimensionInX*m_NumberOfVoxelsInX; + m_BoundingCorner[6][0] = + m_BoundingCorner[7][0] = m_VoxelDimensionInX*m_NumberOfVoxelsInX; m_BoundingCorner[1][1] = m_BoundingCorner[3][1] = - m_BoundingCorner[5][1] = - m_BoundingCorner[7][1] = m_VoxelDimensionInY*m_NumberOfVoxelsInY; + m_BoundingCorner[5][1] = + m_BoundingCorner[7][1] = m_VoxelDimensionInY*m_NumberOfVoxelsInY; m_BoundingCorner[0][1] = m_BoundingCorner[2][1] = - m_BoundingCorner[4][1] = - m_BoundingCorner[6][1] = 0; + m_BoundingCorner[4][1] = + m_BoundingCorner[6][1] = 0; m_BoundingCorner[0][2] = m_BoundingCorner[1][2] = - m_BoundingCorner[4][2] = - m_BoundingCorner[5][2] = - m_VoxelDimensionInZ*m_NumberOfVoxelsInZ; + m_BoundingCorner[4][2] = + m_BoundingCorner[5][2] = + m_VoxelDimensionInZ*m_NumberOfVoxelsInZ; m_BoundingCorner[2][2] = m_BoundingCorner[3][2] = - m_BoundingCorner[6][2] = - m_BoundingCorner[7][2] = 0; + m_BoundingCorner[6][2] = + m_BoundingCorner[7][2] = 0; } @@ -408,29 +407,41 @@ RayCastHelper int c1=0, c2=0, c3=0; - for (j=0; j<6; j++) - { // loop around for planes - switch (j) - { // which corners to take - case 0: - c1=1; c2=2; c3=3; - break; - case 1: - c1=4; c2=5; c3=6; - break; - case 2: - c1=5; c2=3; c3=7; - break; - case 3: - c1=2; c2=4; c3=6; - break; - case 4: - c1=1; c2=5; c3=0; - break; - case 5: - c1=3; c2=7; c3=2; - break; - } + for (j=0; j<6; j++) { + // loop around for planes + switch (j) { + // which corners to take + case 0: + c1=1; + c2=2; + c3=3; + break; + case 1: + c1=4; + c2=5; + c3=6; + break; + case 2: + c1=5; + c2=3; + c3=7; + break; + case 3: + c1=2; + c2=4; + c3=6; + break; + case 4: + c1=1; + c2=5; + c3=0; + break; + case 5: + c1=3; + c2=7; + c3=2; + break; + } double line1x, line1y, line1z; @@ -464,15 +475,14 @@ RayCastHelper m_BoundingPlane[j][2] = C/vcl_sqrt(A*A + B*B + C*C); m_BoundingPlane[j][3] = D/vcl_sqrt(A*A + B*B + C*C); - if ( (A*A + B*B + C*C) == 0 ) - { + if ( (A*A + B*B + C*C) == 0 ) { itk::ExceptionObject err(__FILE__, __LINE__); err.SetLocation( ITK_LOCATION ); err.SetDescription( "Division by zero (planes) " "- CalcPlanesAndCorners()."); throw err; - } } + } } @@ -502,15 +512,13 @@ RayCastHelper double interceptx[6], intercepty[6], interceptz[6]; double d[6]; - for( j=0; j interceptz[j] = m_CurrentRayPositionInMM[2] + d[j]*m_RayDirectionInMM[2]; noInterFlag[j] = 1; //OK - } - else - { + } else { noInterFlag[j] = 0; //NOT OK - } } + } nSidesCrossed = 0; - for( j=0; j cross[i][0] = (int)((ay*bz - az*by)/100); cross[i][1] = (int)((az*bx - ax*bz)/100); cross[i][2] = (int)((ax*by - ay*bx)/100); - } + } // See if a sign change occured between all these cross products // if not, then the ray went through this plane crossFlag=0; - for( i=0; i<3; i++ ) - { + for( i=0; i<3; i++ ) { if( ( cross[0][i]<=0 && cross[1][i]<=0 && cross[2][i]<=0 @@ -621,22 +626,20 @@ RayCastHelper || ( cross[0][i]>=0 && cross[1][i]>=0 && cross[2][i]>=0 - && cross[3][i]>=0) ) - { + && cross[3][i]>=0) ) { crossFlag++; - } } + } - if( crossFlag==3 && noInterFlag[j]==1 ) - { + if( crossFlag==3 && noInterFlag[j]==1 ) { cubeInter[nSidesCrossed][0] = interceptx[j]; cubeInter[nSidesCrossed][1] = intercepty[j]; cubeInter[nSidesCrossed][2] = interceptz[j]; nSidesCrossed++; - } + } - } // End of loop over all four planes + } // End of loop over all four planes m_RayStartCoordInMM[0] = cubeInter[0][0]; m_RayStartCoordInMM[1] = cubeInter[0][1]; @@ -646,10 +649,9 @@ RayCastHelper m_RayEndCoordInMM[1] = cubeInter[1][1]; m_RayEndCoordInMM[2] = cubeInter[1][2]; - if( nSidesCrossed >= 5 ) - { + if( nSidesCrossed >= 5 ) { std::cerr << "WARNING: No. of sides crossed equals: " << nSidesCrossed << std::endl; - } + } // If 'nSidesCrossed' is larger than 2, this means that the ray goes through // a corner of the volume and due to rounding errors, the ray is @@ -658,21 +660,16 @@ RayCastHelper // are furthest from each other. - if( nSidesCrossed >= 3 ) - { + if( nSidesCrossed >= 3 ) { maxInterDist = 0; - for( j=0; j maxInterDist ) - { + (cubeInter[j][i] - cubeInter[k][i]); + } + if( interDist > maxInterDist ) { maxInterDist = interDist; m_RayStartCoordInMM[0] = cubeInter[j][0]; @@ -682,20 +679,17 @@ RayCastHelper m_RayEndCoordInMM[0] = cubeInter[k][0]; m_RayEndCoordInMM[1] = cubeInter[k][1]; m_RayEndCoordInMM[2] = cubeInter[k][2]; - } } } - nSidesCrossed = 2; } + nSidesCrossed = 2; + } - if (nSidesCrossed == 2 ) - { + if (nSidesCrossed == 2 ) { return true; - } - else - { + } else { return false; - } + } } @@ -736,11 +730,10 @@ RayCastHelper m_ValidRay = this->CalcRayIntercepts(); - if (! m_ValidRay) - { + if (! m_ValidRay) { Reset(); return false; - } + } // Convert the start and end coordinates of the ray to voxels @@ -812,36 +805,32 @@ RayCastHelper // Iterate in X direction - if( (xNum >= yNum) && (xNum >= zNum) ) - { - if( m_RayVoxelStartPosition[0] < m_RayVoxelEndPosition[0] ) - { + if( (xNum >= yNum) && (xNum >= zNum) ) { + if( m_RayVoxelStartPosition[0] < m_RayVoxelEndPosition[0] ) { m_VoxelIncrement[0] = 1; m_VoxelIncrement[1] - = (m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0]); + = (m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0]); m_VoxelIncrement[2] - = (m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0]); - } - else - { + = (m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0]); + } else { m_VoxelIncrement[0] = -1; m_VoxelIncrement[1] - = -(m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0]); + = -(m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0]); m_VoxelIncrement[2] - = -(m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0]); - } + = -(m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0]); + } // This section is to alter the start position in order to // place the center of the voxels in there correct positions, @@ -852,117 +841,109 @@ RayCastHelper // center rather than finding the surrounding voxels. m_RayVoxelStartPosition[1] += ( (int)m_RayVoxelStartPosition[0] - - m_RayVoxelStartPosition[0])*m_VoxelIncrement[1]*m_VoxelIncrement[0] - + 0.5*m_VoxelIncrement[1] - 0.5; + - m_RayVoxelStartPosition[0])*m_VoxelIncrement[1]*m_VoxelIncrement[0] + + 0.5*m_VoxelIncrement[1] - 0.5; m_RayVoxelStartPosition[2] += ( (int)m_RayVoxelStartPosition[0] - - m_RayVoxelStartPosition[0])*m_VoxelIncrement[2]*m_VoxelIncrement[0] - + 0.5*m_VoxelIncrement[2] - 0.5; + - m_RayVoxelStartPosition[0])*m_VoxelIncrement[2]*m_VoxelIncrement[0] + + 0.5*m_VoxelIncrement[2] - 0.5; m_RayVoxelStartPosition[0] = (int)m_RayVoxelStartPosition[0] + 0.5*m_VoxelIncrement[0]; m_TotalRayVoxelPlanes = (int)xNum; m_TraversalDirection = TRANSVERSE_IN_X; - } + } // Iterate in Y direction - else if( (yNum >= xNum) && (yNum >= zNum) ) - { + else if( (yNum >= xNum) && (yNum >= zNum) ) { - if( m_RayVoxelStartPosition[1] < m_RayVoxelEndPosition[1] ) - { + if( m_RayVoxelStartPosition[1] < m_RayVoxelEndPosition[1] ) { m_VoxelIncrement[1] = 1; m_VoxelIncrement[0] - = (m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1]); + = (m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1]); m_VoxelIncrement[2] - = (m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1]); - } - else - { + = (m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1]); + } else { m_VoxelIncrement[1] = -1; m_VoxelIncrement[0] - = -(m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1]); + = -(m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1]); m_VoxelIncrement[2] - = -(m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1]); - } + = -(m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2])/(m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1]); + } m_RayVoxelStartPosition[0] += ( (int)m_RayVoxelStartPosition[1] - m_RayVoxelStartPosition[1])*m_VoxelIncrement[0]*m_VoxelIncrement[1] - + 0.5*m_VoxelIncrement[0] - 0.5; + + 0.5*m_VoxelIncrement[0] - 0.5; m_RayVoxelStartPosition[2] += ( (int)m_RayVoxelStartPosition[1] - m_RayVoxelStartPosition[1])*m_VoxelIncrement[2]*m_VoxelIncrement[1] - + 0.5*m_VoxelIncrement[2] - 0.5; + + 0.5*m_VoxelIncrement[2] - 0.5; m_RayVoxelStartPosition[1] = (int)m_RayVoxelStartPosition[1] + 0.5*m_VoxelIncrement[1]; m_TotalRayVoxelPlanes = (int)yNum; m_TraversalDirection = TRANSVERSE_IN_Y; - } + } // Iterate in Z direction - else - { + else { - if( m_RayVoxelStartPosition[2] < m_RayVoxelEndPosition[2] ) - { + if( m_RayVoxelStartPosition[2] < m_RayVoxelEndPosition[2] ) { m_VoxelIncrement[2] = 1; m_VoxelIncrement[0] - = (m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2]); + = (m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2]); m_VoxelIncrement[1] - = (m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2]); - } - else - { + = (m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2]); + } else { m_VoxelIncrement[2] = -1; m_VoxelIncrement[0] - = -(m_RayVoxelStartPosition[0] - - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2]); + = -(m_RayVoxelStartPosition[0] + - m_RayVoxelEndPosition[0])/(m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2]); m_VoxelIncrement[1] - = -(m_RayVoxelStartPosition[1] - - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[2] - - m_RayVoxelEndPosition[2]); - } + = -(m_RayVoxelStartPosition[1] + - m_RayVoxelEndPosition[1])/(m_RayVoxelStartPosition[2] + - m_RayVoxelEndPosition[2]); + } m_RayVoxelStartPosition[0] += ( (int)m_RayVoxelStartPosition[2] - m_RayVoxelStartPosition[2])*m_VoxelIncrement[0]*m_VoxelIncrement[2] - + 0.5*m_VoxelIncrement[0] - 0.5; + + 0.5*m_VoxelIncrement[0] - 0.5; m_RayVoxelStartPosition[1] += ( (int)m_RayVoxelStartPosition[2] - m_RayVoxelStartPosition[2])*m_VoxelIncrement[1]*m_VoxelIncrement[2] - + 0.5*m_VoxelIncrement[1] - 0.5; + + 0.5*m_VoxelIncrement[1] - 0.5; m_RayVoxelStartPosition[2] = (int)m_RayVoxelStartPosition[2] + 0.5*m_VoxelIncrement[2]; m_TotalRayVoxelPlanes = (int)zNum; m_TraversalDirection = TRANSVERSE_IN_Z; - } + } } @@ -980,37 +961,29 @@ RayCastHelper int Istart[3]; int Idirn[3]; - if (m_TraversalDirection == TRANSVERSE_IN_X) - { + if (m_TraversalDirection == TRANSVERSE_IN_X) { Idirn[0] = 0; Idirn[1] = 1; Idirn[2] = 1; - } - else if (m_TraversalDirection == TRANSVERSE_IN_Y) - { + } else if (m_TraversalDirection == TRANSVERSE_IN_Y) { Idirn[0] = 1; Idirn[1] = 0; Idirn[2] = 1; - } - else if (m_TraversalDirection == TRANSVERSE_IN_Z) - { + } else if (m_TraversalDirection == TRANSVERSE_IN_Z) { Idirn[0] = 1; Idirn[1] = 1; Idirn[2] = 0; - } - else - { + } else { itk::ExceptionObject err(__FILE__, __LINE__); err.SetLocation( ITK_LOCATION ); err.SetDescription( "The ray traversal direction is unset " "- AdjustRayLength()."); throw err; return false; - } + } - do - { + do { startOK = false; endOK = false; @@ -1021,42 +994,36 @@ RayCastHelper if( (Istart[0] >= 0) && (Istart[0] + Idirn[0] < m_NumberOfVoxelsInX) && (Istart[1] >= 0) && (Istart[1] + Idirn[1] < m_NumberOfVoxelsInY) && - (Istart[2] >= 0) && (Istart[2] + Idirn[2] < m_NumberOfVoxelsInZ) ) - { + (Istart[2] >= 0) && (Istart[2] + Idirn[2] < m_NumberOfVoxelsInZ) ) { startOK = true; - } - else - { + } else { m_RayVoxelStartPosition[0] += m_VoxelIncrement[0]; m_RayVoxelStartPosition[1] += m_VoxelIncrement[1]; m_RayVoxelStartPosition[2] += m_VoxelIncrement[2]; m_TotalRayVoxelPlanes--; - } + } Istart[0] = (int) vcl_floor(m_RayVoxelStartPosition[0] - + m_TotalRayVoxelPlanes*m_VoxelIncrement[0]); + + m_TotalRayVoxelPlanes*m_VoxelIncrement[0]); Istart[1] = (int) vcl_floor(m_RayVoxelStartPosition[1] - + m_TotalRayVoxelPlanes*m_VoxelIncrement[1]); + + m_TotalRayVoxelPlanes*m_VoxelIncrement[1]); Istart[2] = (int) vcl_floor(m_RayVoxelStartPosition[2] - + m_TotalRayVoxelPlanes*m_VoxelIncrement[2]); + + m_TotalRayVoxelPlanes*m_VoxelIncrement[2]); if( (Istart[0] >= 0) && (Istart[0] + Idirn[0] < m_NumberOfVoxelsInX) && (Istart[1] >= 0) && (Istart[1] + Idirn[1] < m_NumberOfVoxelsInY) && - (Istart[2] >= 0) && (Istart[2] + Idirn[2] < m_NumberOfVoxelsInZ) ) - { + (Istart[2] >= 0) && (Istart[2] + Idirn[2] < m_NumberOfVoxelsInZ) ) { endOK = true; - } - else - { + } else { m_TotalRayVoxelPlanes--; - } + } - } while ( (! (startOK && endOK)) && (m_TotalRayVoxelPlanes > 1) ); + } while ( (! (startOK && endOK)) && (m_TotalRayVoxelPlanes > 1) ); return (startOK && endOK); @@ -1078,44 +1045,36 @@ RayCastHelper // If this is a valid ray... - if (m_ValidRay) - { - for (i=0; i<3; i++) - { + if (m_ValidRay) { + for (i=0; i<3; i++) { m_Position3Dvox[i] = m_RayVoxelStartPosition[i]; - } - this->InitialiseVoxelPointers(); } + this->InitialiseVoxelPointers(); + } // otherwise set parameters to zero - else - { - for (i=0; i<3; i++) - { + else { + for (i=0; i<3; i++) { m_RayVoxelStartPosition[i] = 0.; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_RayVoxelEndPosition[i] = 0.; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_VoxelIncrement[i] = 0.; - } + } m_TraversalDirection = UNDEFINED_DIRECTION; m_TotalRayVoxelPlanes = 0; - for (i=0; i<4; i++) - { + for (i=0; i<4; i++) { m_RayIntersectionVoxels[i] = 0; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_RayIntersectionVoxelIndex[i] = 0; - } } + } } @@ -1140,121 +1099,131 @@ RayCastHelper m_RayIntersectionVoxelIndex[1] = Iy; m_RayIntersectionVoxelIndex[2] = Iz; - switch( m_TraversalDirection ) - { - case TRANSVERSE_IN_X: - { - - if( (Ix >= 0) && (Ix < m_NumberOfVoxelsInX) && - (Iy >= 0) && (Iy + 1 < m_NumberOfVoxelsInY) && - (Iz >= 0) && (Iz + 1 < m_NumberOfVoxelsInZ)) - { - - index[0]=Ix; index[1]=Iy; index[2]=Iz; - m_RayIntersectionVoxels[0] - = this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index); - - index[0]=Ix; index[1]=Iy+1; index[2]=Iz; - m_RayIntersectionVoxels[1] - = ( this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix; index[1]=Iy; index[2]=Iz+1; - m_RayIntersectionVoxels[2] - = ( this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix; index[1]=Iy+1; index[2]=Iz+1; - m_RayIntersectionVoxels[3] - = ( this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index) ); - } - else - { - m_RayIntersectionVoxels[0] = - m_RayIntersectionVoxels[1] = + switch( m_TraversalDirection ) { + case TRANSVERSE_IN_X: { + + if( (Ix >= 0) && (Ix < m_NumberOfVoxelsInX) && + (Iy >= 0) && (Iy + 1 < m_NumberOfVoxelsInY) && + (Iz >= 0) && (Iz + 1 < m_NumberOfVoxelsInZ)) { + + index[0]=Ix; + index[1]=Iy; + index[2]=Iz; + m_RayIntersectionVoxels[0] + = this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index); + + index[0]=Ix; + index[1]=Iy+1; + index[2]=Iz; + m_RayIntersectionVoxels[1] + = ( this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix; + index[1]=Iy; + index[2]=Iz+1; + m_RayIntersectionVoxels[2] + = ( this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix; + index[1]=Iy+1; + index[2]=Iz+1; + m_RayIntersectionVoxels[3] + = ( this->m_Image->GetBufferPointer() + this->m_Image->ComputeOffset(index) ); + } else { + m_RayIntersectionVoxels[0] = + m_RayIntersectionVoxels[1] = m_RayIntersectionVoxels[2] = - m_RayIntersectionVoxels[3] = NULL; - } - break; - } - - case TRANSVERSE_IN_Y: - { - - if( (Ix >= 0) && (Ix + 1 < m_NumberOfVoxelsInX) && - (Iy >= 0) && (Iy < m_NumberOfVoxelsInY) && - (Iz >= 0) && (Iz + 1 < m_NumberOfVoxelsInZ)) - { - - index[0]=Ix; index[1]=Iy; index[2]=Iz; - m_RayIntersectionVoxels[0] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix+1; index[1]=Iy; index[2]=Iz; - m_RayIntersectionVoxels[1] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix; index[1]=Iy; index[2]=Iz+1; - m_RayIntersectionVoxels[2] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix+1; index[1]=Iy; index[2]=Iz+1; - m_RayIntersectionVoxels[3] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - } - else - { - m_RayIntersectionVoxels[0] - = m_RayIntersectionVoxels[1] + m_RayIntersectionVoxels[3] = NULL; + } + break; + } + + case TRANSVERSE_IN_Y: { + + if( (Ix >= 0) && (Ix + 1 < m_NumberOfVoxelsInX) && + (Iy >= 0) && (Iy < m_NumberOfVoxelsInY) && + (Iz >= 0) && (Iz + 1 < m_NumberOfVoxelsInZ)) { + + index[0]=Ix; + index[1]=Iy; + index[2]=Iz; + m_RayIntersectionVoxels[0] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix+1; + index[1]=Iy; + index[2]=Iz; + m_RayIntersectionVoxels[1] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix; + index[1]=Iy; + index[2]=Iz+1; + m_RayIntersectionVoxels[2] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix+1; + index[1]=Iy; + index[2]=Iz+1; + m_RayIntersectionVoxels[3] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + } else { + m_RayIntersectionVoxels[0] + = m_RayIntersectionVoxels[1] = m_RayIntersectionVoxels[2] - = m_RayIntersectionVoxels[3] = NULL; - } - break; - } - - case TRANSVERSE_IN_Z: - { - - if( (Ix >= 0) && (Ix + 1 < m_NumberOfVoxelsInX) && - (Iy >= 0) && (Iy + 1 < m_NumberOfVoxelsInY) && - (Iz >= 0) && (Iz < m_NumberOfVoxelsInZ)) - { - - index[0]=Ix; index[1]=Iy; index[2]=Iz; - m_RayIntersectionVoxels[0] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix+1; index[1]=Iy; index[2]=Iz; - m_RayIntersectionVoxels[1] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix; index[1]=Iy+1; index[2]=Iz; - m_RayIntersectionVoxels[2] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - index[0]=Ix+1; index[1]=Iy+1; index[2]=Iz; - m_RayIntersectionVoxels[3] = ( this->m_Image->GetBufferPointer() - + this->m_Image->ComputeOffset(index) ); - - } - else - { - m_RayIntersectionVoxels[0] - = m_RayIntersectionVoxels[1] + = m_RayIntersectionVoxels[3] = NULL; + } + break; + } + + case TRANSVERSE_IN_Z: { + + if( (Ix >= 0) && (Ix + 1 < m_NumberOfVoxelsInX) && + (Iy >= 0) && (Iy + 1 < m_NumberOfVoxelsInY) && + (Iz >= 0) && (Iz < m_NumberOfVoxelsInZ)) { + + index[0]=Ix; + index[1]=Iy; + index[2]=Iz; + m_RayIntersectionVoxels[0] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix+1; + index[1]=Iy; + index[2]=Iz; + m_RayIntersectionVoxels[1] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix; + index[1]=Iy+1; + index[2]=Iz; + m_RayIntersectionVoxels[2] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + index[0]=Ix+1; + index[1]=Iy+1; + index[2]=Iz; + m_RayIntersectionVoxels[3] = ( this->m_Image->GetBufferPointer() + + this->m_Image->ComputeOffset(index) ); + + } else { + m_RayIntersectionVoxels[0] + = m_RayIntersectionVoxels[1] = m_RayIntersectionVoxels[2] - = m_RayIntersectionVoxels[3] = NULL; - } - break; - } - - default: - { - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION ); - err.SetDescription( "The ray traversal direction is unset " - "- InitialiseVoxelPointers()."); - throw err; - return; - } + = m_RayIntersectionVoxels[3] = NULL; } + break; + } + + default: { + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION ); + err.SetDescription( "The ray traversal direction is unset " + "- InitialiseVoxelPointers()."); + throw err; + return; + } + } } /* ----------------------------------------------------------------------- @@ -1283,7 +1252,7 @@ RayCastHelper m_RayIntersectionVoxelIndex[2] += dz; int totalRayVoxelPlanes - = dx + dy*m_NumberOfVoxelsInX + dz*m_NumberOfVoxelsInX*m_NumberOfVoxelsInY; + = dx + dy*m_NumberOfVoxelsInX + dz*m_NumberOfVoxelsInX*m_NumberOfVoxelsInY; m_RayIntersectionVoxels[0] += totalRayVoxelPlanes; m_RayIntersectionVoxels[1] += totalRayVoxelPlanes; @@ -1304,45 +1273,39 @@ RayCastHelper double a, b, c, d; double y, z; - if (! m_ValidRay) - { + if (! m_ValidRay) { return 0; - } + } a = (double) (*m_RayIntersectionVoxels[0]); b = (double) (*m_RayIntersectionVoxels[1] - a); c = (double) (*m_RayIntersectionVoxels[2] - a); d = (double) (*m_RayIntersectionVoxels[3] - a - b - c); - switch( m_TraversalDirection ) - { - case TRANSVERSE_IN_X: - { - y = m_Position3Dvox[1] - vcl_floor(m_Position3Dvox[1]); - z = m_Position3Dvox[2] - vcl_floor(m_Position3Dvox[2]); - break; - } - case TRANSVERSE_IN_Y: - { - y = m_Position3Dvox[0] - vcl_floor(m_Position3Dvox[0]); - z = m_Position3Dvox[2] - vcl_floor(m_Position3Dvox[2]); - break; - } - case TRANSVERSE_IN_Z: - { - y = m_Position3Dvox[0] - vcl_floor(m_Position3Dvox[0]); - z = m_Position3Dvox[1] - vcl_floor(m_Position3Dvox[1]); - break; - } - default: - { - itk::ExceptionObject err(__FILE__, __LINE__); - err.SetLocation( ITK_LOCATION ); - err.SetDescription( "The ray traversal direction is unset " - "- GetCurrentIntensity()."); - throw err; - return 0; - } - } + switch( m_TraversalDirection ) { + case TRANSVERSE_IN_X: { + y = m_Position3Dvox[1] - vcl_floor(m_Position3Dvox[1]); + z = m_Position3Dvox[2] - vcl_floor(m_Position3Dvox[2]); + break; + } + case TRANSVERSE_IN_Y: { + y = m_Position3Dvox[0] - vcl_floor(m_Position3Dvox[0]); + z = m_Position3Dvox[2] - vcl_floor(m_Position3Dvox[2]); + break; + } + case TRANSVERSE_IN_Z: { + y = m_Position3Dvox[0] - vcl_floor(m_Position3Dvox[0]); + z = m_Position3Dvox[1] - vcl_floor(m_Position3Dvox[1]); + break; + } + default: { + itk::ExceptionObject err(__FILE__, __LINE__); + err.SetLocation( ITK_LOCATION ); + err.SetDescription( "The ray traversal direction is unset " + "- GetCurrentIntensity()."); + throw err; + return 0; + } + } return a + b*y + c*z + d*y*z; } @@ -1358,10 +1321,9 @@ RayCastHelper { short inc = (short) vcl_floor(increment + 0.5); - if (! m_ValidRay) - { + if (! m_ValidRay) { return; - } + } *m_RayIntersectionVoxels[0] += inc; *m_RayIntersectionVoxels[1] += inc; *m_RayIntersectionVoxels[2] += inc; @@ -1387,25 +1349,22 @@ RayCastHelper // Check if this is a valid ray - if (! m_ValidRay) - { + if (! m_ValidRay) { return false; - } + } /* Step along the ray as quickly as possible integrating the interpolated intensities. */ for (m_NumVoxelPlanesTraversed=0; m_NumVoxelPlanesTraversedGetCurrentIntensity(); - if (intensity > threshold) - { + if (intensity > threshold) { integral += intensity - threshold; - } - this->IncrementVoxelPointers(); } + this->IncrementVoxelPointers(); + } /* The ray passes through the volume one plane of voxels at a time, however, if its moving diagonally the ray points will be further @@ -1437,39 +1396,32 @@ RayCastHelper m_VoxelDimensionInY = 0; m_VoxelDimensionInZ = 0; - for (i=0; i<3; i++) - { + for (i=0; i<3; i++) { m_CurrentRayPositionInMM[i] = 0.; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_RayDirectionInMM[i] = 0.; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_RayVoxelStartPosition[i] = 0.; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_RayVoxelEndPosition[i] = 0.; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_VoxelIncrement[i] = 0.; - } + } m_TraversalDirection = UNDEFINED_DIRECTION; m_TotalRayVoxelPlanes = 0; m_NumVoxelPlanesTraversed = -1; - for (i=0; i<4; i++) - { + for (i=0; i<4; i++) { m_RayIntersectionVoxels[i] = 0; - } - for (i=0; i<3; i++) - { + } + for (i=0; i<3; i++) { m_RayIntersectionVoxelIndex[i] = 0; - } + } } }; // end of anonymous namespace @@ -1533,7 +1485,7 @@ RayCastInterpolateImageFunctionWithOrigin< TInputImage, TCoordRep > double integral = 0; OutputPointType transformedFocalPoint - = m_Transform->TransformPoint( m_FocalPoint ); + = m_Transform->TransformPoint( m_FocalPoint ); DirectionType direction = transformedFocalPoint - point; diff --git a/itk/itkVTKImageToImageFilter.txx b/itk/itkVTKImageToImageFilter.txx index 035035b..c749a0f 100644 --- a/itk/itkVTKImageToImageFilter.txx +++ b/itk/itkVTKImageToImageFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -15,130 +15,129 @@ - BSD See included LICENSE.txt file - CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html ======================================================================-====*/ -#ifndef _itkVTKImageToImageFilter_txx -#define _itkVTKImageToImageFilter_txx -#include "itkVTKImageToImageFilter.h" - -namespace itk -{ - - - -/** - * Constructor - */ -template -VTKImageToImageFilter -::VTKImageToImageFilter() -{ - - m_Exporter = vtkImageExport::New(); - - m_Importer = ImporterFilterType::New(); - - m_Importer->SetUpdateInformationCallback( m_Exporter->GetUpdateInformationCallback()); - m_Importer->SetPipelineModifiedCallback( m_Exporter->GetPipelineModifiedCallback()); - m_Importer->SetWholeExtentCallback( m_Exporter->GetWholeExtentCallback()); - m_Importer->SetSpacingCallback( m_Exporter->GetSpacingCallback()); - m_Importer->SetOriginCallback( m_Exporter->GetOriginCallback()); - m_Importer->SetScalarTypeCallback( m_Exporter->GetScalarTypeCallback()); - m_Importer->SetNumberOfComponentsCallback( m_Exporter->GetNumberOfComponentsCallback()); - m_Importer->SetPropagateUpdateExtentCallback( m_Exporter->GetPropagateUpdateExtentCallback()); - m_Importer->SetUpdateDataCallback( m_Exporter->GetUpdateDataCallback()); - m_Importer->SetDataExtentCallback( m_Exporter->GetDataExtentCallback()); - m_Importer->SetBufferPointerCallback( m_Exporter->GetBufferPointerCallback()); - m_Importer->SetCallbackUserData( m_Exporter->GetCallbackUserData()); - -} - - - - -/** - * Destructor - */ -template -VTKImageToImageFilter -::~VTKImageToImageFilter() -{ - if ( m_Exporter ) - { - m_Exporter->Delete(); - m_Exporter = 0; - } -} - - - -/** - * Set a vtkImageData as input - */ -template -void -VTKImageToImageFilter -::SetInput( vtkImageData * inputImage ) -{ - m_Exporter->SetInput( inputImage ); -} - - - -/** - * Get an itk::Image as output - */ -template -const typename VTKImageToImageFilter::OutputImageType * -VTKImageToImageFilter -::GetOutput() const -{ - return m_Importer->GetOutput(); -} - - - - -/** - * Get the exporter filter - */ -template -vtkImageExport * -VTKImageToImageFilter -::GetExporter() const -{ - return m_Exporter; -} - - - -/** - * Get the importer filter - */ -template -typename VTKImageToImageFilter::ImporterFilterType * -VTKImageToImageFilter -::GetImporter() const -{ - return m_Importer; -} - - - - -/** - * Delegate the Update to the importer - */ -template -void -VTKImageToImageFilter -::Update() -{ - m_Importer->Update(); -} - - - - -} // end namespace itk - -#endif - +#ifndef _itkVTKImageToImageFilter_txx +#define _itkVTKImageToImageFilter_txx +#include "itkVTKImageToImageFilter.h" + +namespace itk +{ + + + +/** + * Constructor + */ +template +VTKImageToImageFilter +::VTKImageToImageFilter() +{ + + m_Exporter = vtkImageExport::New(); + + m_Importer = ImporterFilterType::New(); + + m_Importer->SetUpdateInformationCallback( m_Exporter->GetUpdateInformationCallback()); + m_Importer->SetPipelineModifiedCallback( m_Exporter->GetPipelineModifiedCallback()); + m_Importer->SetWholeExtentCallback( m_Exporter->GetWholeExtentCallback()); + m_Importer->SetSpacingCallback( m_Exporter->GetSpacingCallback()); + m_Importer->SetOriginCallback( m_Exporter->GetOriginCallback()); + m_Importer->SetScalarTypeCallback( m_Exporter->GetScalarTypeCallback()); + m_Importer->SetNumberOfComponentsCallback( m_Exporter->GetNumberOfComponentsCallback()); + m_Importer->SetPropagateUpdateExtentCallback( m_Exporter->GetPropagateUpdateExtentCallback()); + m_Importer->SetUpdateDataCallback( m_Exporter->GetUpdateDataCallback()); + m_Importer->SetDataExtentCallback( m_Exporter->GetDataExtentCallback()); + m_Importer->SetBufferPointerCallback( m_Exporter->GetBufferPointerCallback()); + m_Importer->SetCallbackUserData( m_Exporter->GetCallbackUserData()); + +} + + + + +/** + * Destructor + */ +template +VTKImageToImageFilter +::~VTKImageToImageFilter() +{ + if ( m_Exporter ) { + m_Exporter->Delete(); + m_Exporter = 0; + } +} + + + +/** + * Set a vtkImageData as input + */ +template +void +VTKImageToImageFilter +::SetInput( vtkImageData * inputImage ) +{ + m_Exporter->SetInput( inputImage ); +} + + + +/** + * Get an itk::Image as output + */ +template +const typename VTKImageToImageFilter::OutputImageType * +VTKImageToImageFilter +::GetOutput() const +{ + return m_Importer->GetOutput(); +} + + + + +/** + * Get the exporter filter + */ +template +vtkImageExport * +VTKImageToImageFilter +::GetExporter() const +{ + return m_Exporter; +} + + + +/** + * Get the importer filter + */ +template +typename VTKImageToImageFilter::ImporterFilterType * +VTKImageToImageFilter +::GetImporter() const +{ + return m_Importer; +} + + + + +/** + * Delegate the Update to the importer + */ +template +void +VTKImageToImageFilter +::Update() +{ + m_Importer->Update(); +} + + + + +} // end namespace itk + +#endif + diff --git a/tools/clitkAffineTransform.cxx b/tools/clitkAffineTransform.cxx index 0f699b4..c6b08d5 100644 --- a/tools/clitkAffineTransform.cxx +++ b/tools/clitkAffineTransform.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,11 +18,11 @@ /* ================================================= * @file clitkAffineTransform.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ @@ -32,7 +32,8 @@ #include "clitkAffineTransformGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkAffineTransform, args_info); @@ -41,7 +42,7 @@ int main(int argc, char * argv[]) { // Filter typedef clitk::AffineTransformGenericFilter FilterType; FilterType::Pointer genericFilter = FilterType::New(); - + genericFilter->SetArgsInfo(args_info); genericFilter->Update(); diff --git a/tools/clitkAffineTransformGenericFilter.cxx b/tools/clitkAffineTransformGenericFilter.cxx index c9420ff..2cf44f4 100644 --- a/tools/clitkAffineTransformGenericFilter.cxx +++ b/tools/clitkAffineTransformGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkAffineTransformGenericFilter.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ #include "clitkAffineTransformGenericFilter.h" diff --git a/tools/clitkAffineTransformGenericFilter.txx b/tools/clitkAffineTransformGenericFilter.txx index 1853b02..4d110f3 100644 --- a/tools/clitkAffineTransformGenericFilter.txx +++ b/tools/clitkAffineTransformGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,340 +20,310 @@ /* ================================================= * @file clitkAffineTransformGenericFilter.txx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ namespace clitk { - //----------------------------------------------------------- - // Constructor - //----------------------------------------------------------- - template - AffineTransformGenericFilter::AffineTransformGenericFilter() - { - m_Verbose=false; - m_InputFileName=""; +//----------------------------------------------------------- +// Constructor +//----------------------------------------------------------- +template +AffineTransformGenericFilter::AffineTransformGenericFilter() +{ + m_Verbose=false; + m_InputFileName=""; +} + + +//----------------------------------------------------------- +// Update +//----------------------------------------------------------- +template +void AffineTransformGenericFilter::Update() +{ + // Read the Dimension and PixelType + int Dimension, Components; + std::string PixelType; + ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType, Components); + + + // Call UpdateWithDim + if(Dimension==2) UpdateWithDim<2>(PixelType, Components); + else if(Dimension==3) UpdateWithDim<3>(PixelType, Components); + else if (Dimension==4)UpdateWithDim<4>(PixelType, Components); + else { + std::cout<<"Error, Only for 2, 3 or 4 Dimensions!!!"< +template +void +AffineTransformGenericFilter::UpdateWithDim(std::string PixelType, int Components) +{ + if (m_Verbose) std::cout << "Image was detected to be "<(); + } + // else if(PixelType == "unsigned_short"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + else if (PixelType == "unsigned_char") { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; + UpdateWithDimAndPixelType(); + } + + // else if (PixelType == "char"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + else { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; + UpdateWithDimAndPixelType(); + } } + else if (Components==3) { + if (m_Verbose) std::cout << "Launching transform in "<< Dimension <<"D and 3D float (DVF)" << std::endl; + UpdateWithDimAndVectorType >(); + } + + else std::cerr<<"Number of components is "< +template +void +AffineTransformGenericFilter::UpdateWithDimAndPixelType() +{ + + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image OutputImageType; + + // Read the input + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer reader = InputReaderType::New(); + reader->SetFileName( m_InputFileName); + reader->Update(); + typename InputImageType::Pointer input= reader->GetOutput(); + + //Filter + typedef itk::ResampleImageFilter< InputImageType,OutputImageType > ResampleFilterType; + typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); + + // Matrix + typename itk::Matrix matrix; + if (m_ArgsInfo.matrix_given) { + matrix= clitk::ReadMatrix(m_ArgsInfo.matrix_arg); + if (m_Verbose) std::cout<<"Reading the matrix..."< rotationMatrix=clitk::GetRotationalPartMatrix(matrix); + typename itk::Vector translationPart= clitk::GetTranslationPartMatrix(matrix); + + // Transform + typedef itk::AffineTransform AffineTransformType; + typename AffineTransformType::Pointer affineTransform=AffineTransformType::New(); + affineTransform->SetMatrix(rotationMatrix); + affineTransform->SetTranslation(translationPart); + + // Interp + typedef clitk::GenericInterpolator GenericInterpolatorType; + typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); + genericInterpolator->SetArgsInfo(m_ArgsInfo); + + // Properties + if (m_ArgsInfo.like_given) { + typename InputReaderType::Pointer likeReader=InputReaderType::New(); + likeReader->SetFileName(m_ArgsInfo.like_arg); + likeReader->Update(); + resampler->SetOutputParametersFromImage(likeReader->GetOutput()); + } else { + //Size + typename OutputImageType::SizeType outputSize; + if (m_ArgsInfo.size_given) { + for(unsigned int i=0; i< Dimension; i++) + outputSize[i]=m_ArgsInfo.size_arg[i]; + } else outputSize=input->GetLargestPossibleRegion().GetSize(); + std::cout<<"Setting the size to "<GetSpacing(); + std::cout<<"Setting the spacing to "<GetOrigin(); + std::cout<<"Setting the origin to "<SetSize( outputSize ); + resampler->SetOutputSpacing( outputSpacing ); + resampler->SetOutputOrigin( outputOrigin ); - //----------------------------------------------------------- - // Update - //----------------------------------------------------------- - template - void AffineTransformGenericFilter::Update() - { - // Read the Dimension and PixelType - int Dimension, Components; - std::string PixelType; - ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType, Components); - - - // Call UpdateWithDim - if(Dimension==2) UpdateWithDim<2>(PixelType, Components); - else if(Dimension==3) UpdateWithDim<3>(PixelType, Components); - else if (Dimension==4)UpdateWithDim<4>(PixelType, Components); - else - { - std::cout<<"Error, Only for 2, 3 or 4 Dimensions!!!"< - template - void - AffineTransformGenericFilter::UpdateWithDim(std::string PixelType, int Components) - { - if (m_Verbose) std::cout << "Image was detected to be "<(); - } - // else if(PixelType == "unsigned_short"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - else if (PixelType == "unsigned_char"){ - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; - UpdateWithDimAndPixelType(); - } - - // else if (PixelType == "char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - else { - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; - UpdateWithDimAndPixelType(); - } - } - - else if (Components==3) - { - if (m_Verbose) std::cout << "Launching transform in "<< Dimension <<"D and 3D float (DVF)" << std::endl; - UpdateWithDimAndVectorType >(); - } - - else std::cerr<<"Number of components is "<SetInput( input ); + resampler->SetTransform( affineTransform ); + resampler->SetInterpolator( genericInterpolator->GetInterpolatorPointer()); + resampler->SetDefaultPixelValue( static_cast(m_ArgsInfo.pad_arg) ); + try { + resampler->Update(); + } catch(itk::ExceptionObject) { + std::cerr<<"Error resampling the image"<GetOutput(); + + // Output + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_ArgsInfo.output_arg); + writer->SetInput(output); + writer->Update(); + +} - //------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //------------------------------------------------------------------- - template - template - void - AffineTransformGenericFilter::UpdateWithDimAndPixelType() - { - - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - - // Read the input - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer reader = InputReaderType::New(); - reader->SetFileName( m_InputFileName); - reader->Update(); - typename InputImageType::Pointer input= reader->GetOutput(); - - //Filter - typedef itk::ResampleImageFilter< InputImageType,OutputImageType > ResampleFilterType; - typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); - - // Matrix - typename itk::Matrix matrix; - if (m_ArgsInfo.matrix_given) - { - matrix= clitk::ReadMatrix(m_ArgsInfo.matrix_arg); - if (m_Verbose) std::cout<<"Reading the matrix..."< rotationMatrix=clitk::GetRotationalPartMatrix(matrix); - typename itk::Vector translationPart= clitk::GetTranslationPartMatrix(matrix); - - // Transform - typedef itk::AffineTransform AffineTransformType; - typename AffineTransformType::Pointer affineTransform=AffineTransformType::New(); - affineTransform->SetMatrix(rotationMatrix); - affineTransform->SetTranslation(translationPart); - - // Interp - typedef clitk::GenericInterpolator GenericInterpolatorType; - typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); - genericInterpolator->SetArgsInfo(m_ArgsInfo); - - // Properties - if (m_ArgsInfo.like_given) - { - typename InputReaderType::Pointer likeReader=InputReaderType::New(); - likeReader->SetFileName(m_ArgsInfo.like_arg); - likeReader->Update(); - resampler->SetOutputParametersFromImage(likeReader->GetOutput()); - } - else - { - //Size - typename OutputImageType::SizeType outputSize; - if (m_ArgsInfo.size_given) - { - for(unsigned int i=0; i< Dimension; i++) - outputSize[i]=m_ArgsInfo.size_arg[i]; - } - else outputSize=input->GetLargestPossibleRegion().GetSize(); - std::cout<<"Setting the size to "<GetSpacing(); - std::cout<<"Setting the spacing to "<GetOrigin(); - std::cout<<"Setting the origin to "<SetSize( outputSize ); - resampler->SetOutputSpacing( outputSpacing ); - resampler->SetOutputOrigin( outputOrigin ); - - } - - resampler->SetInput( input ); - resampler->SetTransform( affineTransform ); - resampler->SetInterpolator( genericInterpolator->GetInterpolatorPointer()); - resampler->SetDefaultPixelValue( static_cast(m_ArgsInfo.pad_arg) ); - - try - { - resampler->Update(); - } - catch(itk::ExceptionObject) - { - std::cerr<<"Error resampling the image"<GetOutput(); - - // Output - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_ArgsInfo.output_arg); - writer->SetInput(output); - writer->Update(); +//------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype (components) +//------------------------------------------------------------------- +template +template +void AffineTransformGenericFilter::UpdateWithDimAndVectorType() +{ + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image OutputImageType; + + // Read the input + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer reader = InputReaderType::New(); + reader->SetFileName( m_InputFileName); + reader->Update(); + typename InputImageType::Pointer input= reader->GetOutput(); + + //Filter + typedef itk::VectorResampleImageFilter< InputImageType,OutputImageType, double > ResampleFilterType; + typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); + + // Matrix + typename itk::Matrix matrix; + if (m_ArgsInfo.matrix_given) + matrix= clitk::ReadMatrix(m_ArgsInfo.matrix_arg); + else + matrix.SetIdentity(); + if (m_Verbose) std::cout<<"Using the following matrix:"< rotationMatrix=clitk::GetRotationalPartMatrix(matrix); + typename itk::Vector translationPart= clitk::GetTranslationPartMatrix(matrix); + + // Transform + typedef itk::AffineTransform AffineTransformType; + typename AffineTransformType::Pointer affineTransform=AffineTransformType::New(); + affineTransform->SetMatrix(rotationMatrix); + affineTransform->SetTranslation(translationPart); + + // Interp + typedef clitk::GenericVectorInterpolator GenericInterpolatorType; + typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); + genericInterpolator->SetArgsInfo(m_ArgsInfo); + + // Properties + if (m_ArgsInfo.like_given) { + typename InputReaderType::Pointer likeReader=InputReaderType::New(); + likeReader->SetFileName(m_ArgsInfo.like_arg); + likeReader->Update(); + resampler->SetSize( likeReader->GetOutput()->GetLargestPossibleRegion().GetSize() ); + resampler->SetOutputSpacing( likeReader->GetOutput()->GetSpacing() ); + resampler->SetOutputOrigin( likeReader->GetOutput()->GetOrigin() ); + } else { + //Size + typename OutputImageType::SizeType outputSize; + if (m_ArgsInfo.size_given) { + for(unsigned int i=0; i< Dimension; i++) + outputSize[i]=m_ArgsInfo.size_arg[i]; + } else outputSize=input->GetLargestPossibleRegion().GetSize(); + std::cout<<"Setting the size to "<GetSpacing(); + std::cout<<"Setting the spacing to "<GetOrigin(); + std::cout<<"Setting the origin to "<SetSize( outputSize ); + resampler->SetOutputSpacing( outputSpacing ); + resampler->SetOutputOrigin( outputOrigin ); } - //------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype (components) - //------------------------------------------------------------------- - template - template - void AffineTransformGenericFilter::UpdateWithDimAndVectorType() - { - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - - // Read the input - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer reader = InputReaderType::New(); - reader->SetFileName( m_InputFileName); - reader->Update(); - typename InputImageType::Pointer input= reader->GetOutput(); - - //Filter - typedef itk::VectorResampleImageFilter< InputImageType,OutputImageType, double > ResampleFilterType; - typename ResampleFilterType::Pointer resampler = ResampleFilterType::New(); - - // Matrix - typename itk::Matrix matrix; - if (m_ArgsInfo.matrix_given) - matrix= clitk::ReadMatrix(m_ArgsInfo.matrix_arg); - else - matrix.SetIdentity(); - if (m_Verbose) std::cout<<"Using the following matrix:"< rotationMatrix=clitk::GetRotationalPartMatrix(matrix); - typename itk::Vector translationPart= clitk::GetTranslationPartMatrix(matrix); - - // Transform - typedef itk::AffineTransform AffineTransformType; - typename AffineTransformType::Pointer affineTransform=AffineTransformType::New(); - affineTransform->SetMatrix(rotationMatrix); - affineTransform->SetTranslation(translationPart); - - // Interp - typedef clitk::GenericVectorInterpolator GenericInterpolatorType; - typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); - genericInterpolator->SetArgsInfo(m_ArgsInfo); - - // Properties - if (m_ArgsInfo.like_given) - { - typename InputReaderType::Pointer likeReader=InputReaderType::New(); - likeReader->SetFileName(m_ArgsInfo.like_arg); - likeReader->Update(); - resampler->SetSize( likeReader->GetOutput()->GetLargestPossibleRegion().GetSize() ); - resampler->SetOutputSpacing( likeReader->GetOutput()->GetSpacing() ); - resampler->SetOutputOrigin( likeReader->GetOutput()->GetOrigin() ); - } - else - { - //Size - typename OutputImageType::SizeType outputSize; - if (m_ArgsInfo.size_given) - { - for(unsigned int i=0; i< Dimension; i++) - outputSize[i]=m_ArgsInfo.size_arg[i]; - } - else outputSize=input->GetLargestPossibleRegion().GetSize(); - std::cout<<"Setting the size to "<GetSpacing(); - std::cout<<"Setting the spacing to "<GetOrigin(); - std::cout<<"Setting the origin to "<SetSize( outputSize ); - resampler->SetOutputSpacing( outputSpacing ); - resampler->SetOutputOrigin( outputOrigin ); - - } - - resampler->SetInput( input ); - resampler->SetTransform( affineTransform ); - resampler->SetInterpolator( genericInterpolator->GetInterpolatorPointer()); - resampler->SetDefaultPixelValue( static_cast(m_ArgsInfo.pad_arg) ); - - try - { - resampler->Update(); - } - catch(itk::ExceptionObject) - { - std::cerr<<"Error resampling the image"<GetOutput(); - - // Output - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_ArgsInfo.output_arg); - writer->SetInput(output); - writer->Update(); + resampler->SetInput( input ); + resampler->SetTransform( affineTransform ); + resampler->SetInterpolator( genericInterpolator->GetInterpolatorPointer()); + resampler->SetDefaultPixelValue( static_cast(m_ArgsInfo.pad_arg) ); + try { + resampler->Update(); + } catch(itk::ExceptionObject) { + std::cerr<<"Error resampling the image"<GetOutput(); + + // Output + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_ArgsInfo.output_arg); + writer->SetInput(output); + writer->Update(); + +} + } //end clitk - + #endif //#define clitkAffineTransformGenericFilter_txx diff --git a/tools/clitkAverageTemporalDimension.cxx b/tools/clitkAverageTemporalDimension.cxx index 1e9e6b6..72832e5 100644 --- a/tools/clitkAverageTemporalDimension.cxx +++ b/tools/clitkAverageTemporalDimension.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,11 +18,11 @@ /* ================================================= * @file clitkAverageTemporalDimension.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ @@ -33,7 +33,8 @@ //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkAverageTemporalDimension, args_info); @@ -42,7 +43,7 @@ int main(int argc, char * argv[]) { // Filter typedef clitk::AverageTemporalDimensionGenericFilter FilterType; FilterType::Pointer genericFilter = FilterType::New(); - + genericFilter->SetArgsInfo(args_info); genericFilter->Update(); diff --git a/tools/clitkAverageTemporalDimensionGenericFilter.cxx b/tools/clitkAverageTemporalDimensionGenericFilter.cxx index 0d5d9fd..ea1a6e6 100644 --- a/tools/clitkAverageTemporalDimensionGenericFilter.cxx +++ b/tools/clitkAverageTemporalDimensionGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkAverageTemporalDimensionGenericFilter.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ #include "clitkAverageTemporalDimensionGenericFilter.h" diff --git a/tools/clitkAverageTemporalDimensionGenericFilter.txx b/tools/clitkAverageTemporalDimensionGenericFilter.txx index 473e36f..3d0aff8 100644 --- a/tools/clitkAverageTemporalDimensionGenericFilter.txx +++ b/tools/clitkAverageTemporalDimensionGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,225 +20,215 @@ /* ================================================= * @file clitkAverageTemporalDimensionGenericFilter.txx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ namespace clitk { - //----------------------------------------------------------- - // Constructor - //----------------------------------------------------------- - template - AverageTemporalDimensionGenericFilter::AverageTemporalDimensionGenericFilter() - { - m_Verbose=false; - m_InputFileName=""; +//----------------------------------------------------------- +// Constructor +//----------------------------------------------------------- +template +AverageTemporalDimensionGenericFilter::AverageTemporalDimensionGenericFilter() +{ + m_Verbose=false; + m_InputFileName=""; +} + + +//----------------------------------------------------------- +// Update +//----------------------------------------------------------- +template +void AverageTemporalDimensionGenericFilter::Update() +{ + // Read the Dimension and PixelType + int Dimension, Components; + std::string PixelType; + ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType, Components); + + + // Call UpdateWithDim + if (m_ArgsInfo.input_given>1) Dimension+=1; + if(Dimension==2) UpdateWithDim<2>(PixelType, Components); + else if(Dimension==3)UpdateWithDim<3>(PixelType, Components); + else if (Dimension==4)UpdateWithDim<4>(PixelType, Components); + else { + std::cout<<"Error, Only for 2, 3 or 4D!!!"< +template +void +AverageTemporalDimensionGenericFilter::UpdateWithDim(const std::string PixelType, const int Components) +{ + if (m_Verbose) std::cout << "Image was detected to be "<(); + } + // else if(PixelType == "unsigned_short"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + else if (PixelType == "unsigned_char") { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; + UpdateWithDimAndPixelType(); + } + + // else if (PixelType == "char"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + else { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; + UpdateWithDimAndPixelType(); + } } + // else if (Components==2) + // { + // if (m_Verbose) std::cout << "Launching transform in "<< Dimension <<"D and 3D float (DVF)" << std::endl; + // UpdateWithDimAndPixelType >(); + // } - //----------------------------------------------------------- - // Update - //----------------------------------------------------------- - template - void AverageTemporalDimensionGenericFilter::Update() - { - // Read the Dimension and PixelType - int Dimension, Components; - std::string PixelType; - ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType, Components); - - - // Call UpdateWithDim - if (m_ArgsInfo.input_given>1) Dimension+=1; - if(Dimension==2) UpdateWithDim<2>(PixelType, Components); - else if(Dimension==3)UpdateWithDim<3>(PixelType, Components); - else if (Dimension==4)UpdateWithDim<4>(PixelType, Components); - else - { - std::cout<<"Error, Only for 2, 3 or 4D!!!"< >(); } - //------------------------------------------------------------------- - // Update with the number of dimensions - //------------------------------------------------------------------- - template - template - void - AverageTemporalDimensionGenericFilter::UpdateWithDim(const std::string PixelType, const int Components) - { - if (m_Verbose) std::cout << "Image was detected to be "<(); - } - // else if(PixelType == "unsigned_short"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - else if (PixelType == "unsigned_char"){ - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; - UpdateWithDimAndPixelType(); - } - - // else if (PixelType == "char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - else { - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; - UpdateWithDimAndPixelType(); - } - } - - // else if (Components==2) - // { - // if (m_Verbose) std::cout << "Launching transform in "<< Dimension <<"D and 3D float (DVF)" << std::endl; - // UpdateWithDimAndPixelType >(); - // } - - else if (Components==3) - { - if (m_Verbose) std::cout << "Launching transform in "<< Dimension <<"D and 3D float (DVF)" << std::endl; - UpdateWithDimAndPixelType >(); - } - - // else if (Components==4) - // { - // if (m_Verbose) std::cout << "Launching transform in "<< Dimension <<"D and 3D float (DVF)" << std::endl; - // UpdateWithDimAndPixelType >(); - // } - else std::cerr<<"Number of components is "< >(); + // } + else std::cerr<<"Number of components is "< +template +void +AverageTemporalDimensionGenericFilter::UpdateWithDimAndPixelType() +{ + + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image OutputImageType; + typename InputImageType::Pointer input; + + if (m_ArgsInfo.input_given ==1 ) { + // Read the input + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer reader = InputReaderType::New(); + reader->SetFileName( m_InputFileName); + reader->Update(); + input= reader->GetOutput(); + } + + else { + // Read and join multiple inputs + if (m_Verbose) std::cout< filenames; + for(unsigned int i=0; i ImageReaderType; + typename ImageReaderType::Pointer reader= ImageReaderType::New(); + reader->SetFileNames(filenames); + reader->Update(); + input =reader->GetOutput(); } - //------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //------------------------------------------------------------------- - template - template - void - AverageTemporalDimensionGenericFilter::UpdateWithDimAndPixelType() - { - - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - typename InputImageType::Pointer input; - - if (m_ArgsInfo.input_given ==1 ) - { - // Read the input - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer reader = InputReaderType::New(); - reader->SetFileName( m_InputFileName); - reader->Update(); - input= reader->GetOutput(); - } - - else - { - // Read and join multiple inputs - if (m_Verbose) std::cout< filenames; - for(unsigned int i=0; i ImageReaderType; - typename ImageReaderType::Pointer reader= ImageReaderType::New(); - reader->SetFileNames(filenames); - reader->Update(); - input =reader->GetOutput(); - } - - - // Output properties - typename OutputImageType::RegionType region; - typename OutputImageType::RegionType::SizeType size; - typename OutputImageType::IndexType index; - typename OutputImageType::SpacingType spacing; - typename OutputImageType::PointType origin; - typename InputImageType::RegionType region4D=input->GetLargestPossibleRegion(); - typename InputImageType::RegionType::SizeType size4D=region4D.GetSize(); - typename InputImageType::IndexType index4D=region4D.GetIndex(); - typename InputImageType::SpacingType spacing4D=input->GetSpacing(); - typename InputImageType::PointType origin4D=input->GetOrigin(); - - for (unsigned int i=0; i< Dimension-1; i++) - { - size[i]=size4D[i]; - index[i]=index4D[i]; - spacing[i]=spacing4D[i]; - origin[i]=origin4D[i]; - } - region.SetSize(size); - region.SetIndex(index); - typename OutputImageType::Pointer output= OutputImageType::New(); - output->SetRegions(region); - output->SetSpacing(spacing); - output->SetOrigin(origin); - output->Allocate(); - - - // Region iterators - typedef itk::ImageRegionIterator IteratorType; - std::vector iterators(size4D[Dimension-1]); - for (unsigned int i=0; i< size4D[Dimension-1]; i++) - { - typename InputImageType::RegionType regionIt=region4D; - typename InputImageType::RegionType::SizeType sizeIt=regionIt.GetSize(); - sizeIt[Dimension-1]=1; - regionIt.SetSize(sizeIt); - typename InputImageType::IndexType indexIt=regionIt.GetIndex(); - indexIt[Dimension-1]=i; - regionIt.SetIndex(indexIt); - iterators[i]=IteratorType(input, regionIt); - } - - typedef itk::ImageRegionIterator OutputIteratorType; - OutputIteratorType avIt(output, output->GetLargestPossibleRegion()); - - // Average - PixelType vector; - PixelType zeroVector=itk::NumericTraits::Zero; - //zeroVector.Fill(0.0); - while (!(iterators[0]).IsAtEnd()) - { - vector=zeroVector; - for (unsigned int i=0; i WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_ArgsInfo.output_arg); - writer->SetInput(output); - writer->Update(); + // Output properties + typename OutputImageType::RegionType region; + typename OutputImageType::RegionType::SizeType size; + typename OutputImageType::IndexType index; + typename OutputImageType::SpacingType spacing; + typename OutputImageType::PointType origin; + typename InputImageType::RegionType region4D=input->GetLargestPossibleRegion(); + typename InputImageType::RegionType::SizeType size4D=region4D.GetSize(); + typename InputImageType::IndexType index4D=region4D.GetIndex(); + typename InputImageType::SpacingType spacing4D=input->GetSpacing(); + typename InputImageType::PointType origin4D=input->GetOrigin(); + + for (unsigned int i=0; i< Dimension-1; i++) { + size[i]=size4D[i]; + index[i]=index4D[i]; + spacing[i]=spacing4D[i]; + origin[i]=origin4D[i]; + } + region.SetSize(size); + region.SetIndex(index); + typename OutputImageType::Pointer output= OutputImageType::New(); + output->SetRegions(region); + output->SetSpacing(spacing); + output->SetOrigin(origin); + output->Allocate(); + + + // Region iterators + typedef itk::ImageRegionIterator IteratorType; + std::vector iterators(size4D[Dimension-1]); + for (unsigned int i=0; i< size4D[Dimension-1]; i++) { + typename InputImageType::RegionType regionIt=region4D; + typename InputImageType::RegionType::SizeType sizeIt=regionIt.GetSize(); + sizeIt[Dimension-1]=1; + regionIt.SetSize(sizeIt); + typename InputImageType::IndexType indexIt=regionIt.GetIndex(); + indexIt[Dimension-1]=i; + regionIt.SetIndex(indexIt); + iterators[i]=IteratorType(input, regionIt); + } + typedef itk::ImageRegionIterator OutputIteratorType; + OutputIteratorType avIt(output, output->GetLargestPossibleRegion()); + + // Average + PixelType vector; + PixelType zeroVector=itk::NumericTraits::Zero; + //zeroVector.Fill(0.0); + while (!(iterators[0]).IsAtEnd()) { + vector=zeroVector; + for (unsigned int i=0; i WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_ArgsInfo.output_arg); + writer->SetInput(output); + writer->Update(); + +} + }//end clitk - + #endif //#define clitkAverageTemporalDimensionGenericFilter_txx diff --git a/tools/clitkBinarizeImage.cxx b/tools/clitkBinarizeImage.cxx index 18b2fad..345959d 100644 --- a/tools/clitkBinarizeImage.cxx +++ b/tools/clitkBinarizeImage.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,9 +20,9 @@ * @file clitkBinarizeImageGenericFilter.txx * @author Jef Vandemeulebroucke * @date 29 June 2009 - * + * * @brief Binarize an image - * + * ===================================================*/ // clitk @@ -30,7 +30,8 @@ #include "clitkBinarizeImageGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkBinarizeImage, args_info); @@ -39,7 +40,7 @@ int main(int argc, char * argv[]) { // Filter typedef clitk::BinarizeImageGenericFilter FilterType; FilterType::Pointer filter = FilterType::New(); - + filter->SetArgsInfo(args_info); filter->Update(); diff --git a/tools/clitkCorrelationRatioImageToImageMetric.txx b/tools/clitkCorrelationRatioImageToImageMetric.txx index 827dbad..2b45c2f 100644 --- a/tools/clitkCorrelationRatioImageToImageMetric.txx +++ b/tools/clitkCorrelationRatioImageToImageMetric.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkCorrelationRatioImageToImageMetric.txx * @author Jef Vandemeulebroucke * @date July 30 18:14:53 2007 - * + * * @brief Compute the correlation ratio between 2 images - * - * + * + * */ #include "clitkCorrelationRatioImageToImageMetric.h" @@ -39,7 +39,7 @@ namespace clitk /* * Constructor */ -template +template CorrelationRatioImageToImageMetric ::CorrelationRatioImageToImageMetric() { @@ -47,39 +47,36 @@ CorrelationRatioImageToImageMetric } -template +template void CorrelationRatioImageToImageMetric ::Initialize(void) throw ( ExceptionObject ) { this->Superclass::Initialize(); - + // Compute the minimum and maximum for the FixedImage over the FixedImageRegion. // We can't use StatisticsImageFilter to do this because the filter computes the min/max for the largest possible region double fixedImageMin = NumericTraits::max(); double fixedImageMax = NumericTraits::NonpositiveMin(); typedef ImageRegionConstIterator FixedIteratorType; - FixedIteratorType fixedImageIterator( + FixedIteratorType fixedImageIterator( this->m_FixedImage, this->GetFixedImageRegion() ); - for ( fixedImageIterator.GoToBegin(); - !fixedImageIterator.IsAtEnd(); ++fixedImageIterator ) - { + for ( fixedImageIterator.GoToBegin(); + !fixedImageIterator.IsAtEnd(); ++fixedImageIterator ) { double sample = static_cast( fixedImageIterator.Get() ); - if ( sample < fixedImageMin ) - { + if ( sample < fixedImageMin ) { fixedImageMin = sample; - } + } - if ( sample > fixedImageMax ) - { + if ( sample > fixedImageMax ) { fixedImageMax = sample; - } } + } // Compute binsize for the fixedImage m_FixedImageBinSize = ( fixedImageMax - fixedImageMin ) / m_NumberOfBins; @@ -94,7 +91,7 @@ CorrelationRatioImageToImageMetric /* * Get the match Measure */ -template +template typename CorrelationRatioImageToImageMetric::MeasureType CorrelationRatioImageToImageMetric ::GetValue( const TransformParametersType & parameters ) const @@ -104,10 +101,9 @@ CorrelationRatioImageToImageMetric FixedImageConstPointer fixedImage = this->m_FixedImage; - if( !fixedImage ) - { + if( !fixedImage ) { itkExceptionMacro( << "Fixed image has not been assigned" ); - } + } typedef itk::ImageRegionConstIteratorWithIndex FixedIteratorType; @@ -122,86 +118,79 @@ CorrelationRatioImageToImageMetric this->SetTransformParameters( parameters ); - //temporary measures for the calculation + //temporary measures for the calculation RealType mSMV=0; RealType mMSV=0; - while(!ti.IsAtEnd()) - { + while(!ti.IsAtEnd()) { index = ti.GetIndex(); - + typename Superclass::InputPointType inputPoint; fixedImage->TransformIndexToPhysicalPoint( index, inputPoint ); // Verify that the point is in the fixed Image Mask - if( this->m_FixedImageMask && !this->m_FixedImageMask->IsInside( inputPoint ) ) - { + if( this->m_FixedImageMask && !this->m_FixedImageMask->IsInside( inputPoint ) ) { ++ti; continue; - } + } typename Superclass::OutputPointType transformedPoint = this->m_Transform->TransformPoint( inputPoint ); //Verify that the point is in the moving Image Mask - if( this->m_MovingImageMask && !this->m_MovingImageMask->IsInside( transformedPoint ) ) - { + if( this->m_MovingImageMask && !this->m_MovingImageMask->IsInside( transformedPoint ) ) { ++ti; continue; - } + } // Verify is the interpolated value is in the buffer - if( this->m_Interpolator->IsInsideBuffer( transformedPoint ) ) - { - //Accumulate calculations for the correlation ratio - //For each pixel the is in both masks and the buffer we adapt the following measures: - //movingMeanSquaredValue mMSV; movingSquaredMeanValue mSMV; - //movingMeanSquaredValuePerBin[i] mSMVPB; movingSquaredMeanValuePerBin[i] mSMVPB - //NumberOfPixelsCounted, NumberOfPixelsCountedPerBin[i] - - //get the value of the moving image - const RealType movingValue = this->m_Interpolator->Evaluate( transformedPoint ); - // for the variance of the overlapping moving image we accumulate the following measures - const RealType movingSquaredValue=movingValue*movingValue; - mMSV+=movingSquaredValue; - mSMV+=movingValue; - - //get the fixed value - const RealType fixedValue = ti.Get(); - - //check in which bin the fixed value belongs, get the index - const double fixedImageBinTerm = (fixedValue - m_FixedImageMin) / m_FixedImageBinSize; - const unsigned int fixedImageBinIndex = static_cast( vcl_floor(fixedImageBinTerm ) ); - //adapt the measures per bin - this->m_mMSVPB[fixedImageBinIndex]+=movingSquaredValue; - this->m_mSMVPB[fixedImageBinIndex]+=movingValue; - //increase the fixed image bin and the total pixel count - this->m_NumberOfPixelsCountedPerBin[fixedImageBinIndex]+=1; - this->m_NumberOfPixelsCounted++; - } - - ++ti; + if( this->m_Interpolator->IsInsideBuffer( transformedPoint ) ) { + //Accumulate calculations for the correlation ratio + //For each pixel the is in both masks and the buffer we adapt the following measures: + //movingMeanSquaredValue mMSV; movingSquaredMeanValue mSMV; + //movingMeanSquaredValuePerBin[i] mSMVPB; movingSquaredMeanValuePerBin[i] mSMVPB + //NumberOfPixelsCounted, NumberOfPixelsCountedPerBin[i] + + //get the value of the moving image + const RealType movingValue = this->m_Interpolator->Evaluate( transformedPoint ); + // for the variance of the overlapping moving image we accumulate the following measures + const RealType movingSquaredValue=movingValue*movingValue; + mMSV+=movingSquaredValue; + mSMV+=movingValue; + + //get the fixed value + const RealType fixedValue = ti.Get(); + + //check in which bin the fixed value belongs, get the index + const double fixedImageBinTerm = (fixedValue - m_FixedImageMin) / m_FixedImageBinSize; + const unsigned int fixedImageBinIndex = static_cast( vcl_floor(fixedImageBinTerm ) ); + //adapt the measures per bin + this->m_mMSVPB[fixedImageBinIndex]+=movingSquaredValue; + this->m_mSMVPB[fixedImageBinIndex]+=movingValue; + //increase the fixed image bin and the total pixel count + this->m_NumberOfPixelsCountedPerBin[fixedImageBinIndex]+=1; + this->m_NumberOfPixelsCounted++; } - if( !this->m_NumberOfPixelsCounted ) - { - itkExceptionMacro(<<"All the points mapped to outside of the moving image"); - } - else - { - - //apdapt the measures per bin - for (unsigned int i=0; i< m_NumberOfBins; i++ ){ - if (this->m_NumberOfPixelsCountedPerBin[i]>0){ - measure+=(this->m_mMSVPB[i]-((this->m_mSMVPB[i]*this->m_mSMVPB[i])/this->m_NumberOfPixelsCountedPerBin[i])); - } - } + ++ti; + } - //Normalize with the global measures - measure /= (mMSV-((mSMV*mSMV)/ this->m_NumberOfPixelsCounted)); - return measure; + if( !this->m_NumberOfPixelsCounted ) { + itkExceptionMacro(<<"All the points mapped to outside of the moving image"); + } else { + //apdapt the measures per bin + for (unsigned int i=0; i< m_NumberOfBins; i++ ) { + if (this->m_NumberOfPixelsCountedPerBin[i]>0) { + measure+=(this->m_mMSVPB[i]-((this->m_mSMVPB[i]*this->m_mSMVPB[i])/this->m_NumberOfPixelsCountedPerBin[i])); + } } + + //Normalize with the global measures + measure /= (mMSV-((mSMV*mSMV)/ this->m_NumberOfPixelsCounted)); + return measure; + + } } @@ -211,7 +200,7 @@ CorrelationRatioImageToImageMetric /* * Get the Derivative Measure */ -template < class TFixedImage, class TMovingImage> +template < class TFixedImage, class TMovingImage> void CorrelationRatioImageToImageMetric ::GetDerivative( const TransformParametersType & parameters, @@ -219,27 +208,25 @@ CorrelationRatioImageToImageMetric { itkDebugMacro("GetDerivative( " << parameters << " ) "); - - if( !this->GetGradientImage() ) - { + + if( !this->GetGradientImage() ) { itkExceptionMacro(<<"The gradient image is null, maybe you forgot to call Initialize()"); - } + } FixedImageConstPointer fixedImage = this->m_FixedImage; - if( !fixedImage ) - { + if( !fixedImage ) { itkExceptionMacro( << "Fixed image has not been assigned" ); - } + } const unsigned int ImageDimension = FixedImageType::ImageDimension; typedef itk::ImageRegionConstIteratorWithIndex< - FixedImageType> FixedIteratorType; + FixedImageType> FixedIteratorType; typedef itk::ImageRegionConstIteratorWithIndex< - ITK_TYPENAME Superclass::GradientImageType> GradientIteratorType; + ITK_TYPENAME Superclass::GradientImageType> GradientIteratorType; FixedIteratorType ti( fixedImage, this->GetFixedImageRegion() ); @@ -256,119 +243,106 @@ CorrelationRatioImageToImageMetric ti.GoToBegin(); - while(!ti.IsAtEnd()) - { + while(!ti.IsAtEnd()) { index = ti.GetIndex(); - + typename Superclass::InputPointType inputPoint; fixedImage->TransformIndexToPhysicalPoint( index, inputPoint ); - if( this->m_FixedImageMask && !this->m_FixedImageMask->IsInside( inputPoint ) ) - { + if( this->m_FixedImageMask && !this->m_FixedImageMask->IsInside( inputPoint ) ) { ++ti; continue; - } + } typename Superclass::OutputPointType transformedPoint = this->m_Transform->TransformPoint( inputPoint ); - if( this->m_MovingImageMask && !this->m_MovingImageMask->IsInside( transformedPoint ) ) - { + if( this->m_MovingImageMask && !this->m_MovingImageMask->IsInside( transformedPoint ) ) { ++ti; continue; - } + } - if( this->m_Interpolator->IsInsideBuffer( transformedPoint ) ) - { + if( this->m_Interpolator->IsInsideBuffer( transformedPoint ) ) { const RealType movingValue = this->m_Interpolator->Evaluate( transformedPoint ); const TransformJacobianType & jacobian = - this->m_Transform->GetJacobian( inputPoint ); + this->m_Transform->GetJacobian( inputPoint ); + - const RealType fixedValue = ti.Value(); this->m_NumberOfPixelsCounted++; - const RealType diff = movingValue - fixedValue; + const RealType diff = movingValue - fixedValue; - // Get the gradient by NearestNeighboorInterpolation: + // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. typedef typename Superclass::OutputPointType OutputPointType; typedef typename OutputPointType::CoordRepType CoordRepType; typedef ContinuousIndex - MovingImageContinuousIndexType; + MovingImageContinuousIndexType; MovingImageContinuousIndexType tempIndex; this->m_MovingImage->TransformPhysicalPointToContinuousIndex( transformedPoint, tempIndex ); - typename MovingImageType::IndexType mappedIndex; - for( unsigned int j = 0; j < MovingImageType::ImageDimension; j++ ) - { + typename MovingImageType::IndexType mappedIndex; + for( unsigned int j = 0; j < MovingImageType::ImageDimension; j++ ) { mappedIndex[j] = static_cast( vnl_math_rnd( tempIndex[j] ) ); - } + } - const GradientPixelType gradient = + const GradientPixelType gradient = this->GetGradientImage()->GetPixel( mappedIndex ); - for(unsigned int par=0; par::Zero; - for(unsigned int dim=0; dimm_NumberOfPixelsCounted ) - { + if( !this->m_NumberOfPixelsCounted ) { itkExceptionMacro(<<"All the points mapped to outside of the moving image"); - } - else - { - for(unsigned int i=0; im_NumberOfPixelsCounted; - } } + } } /* - * Get both the match Measure and the Derivative Measure + * Get both the match Measure and the Derivative Measure */ -template +template void CorrelationRatioImageToImageMetric -::GetValueAndDerivative(const TransformParametersType & parameters, +::GetValueAndDerivative(const TransformParametersType & parameters, MeasureType & value, DerivativeType & derivative) const { itkDebugMacro("GetValueAndDerivative( " << parameters << " ) "); - if( !this->GetGradientImage() ) - { + if( !this->GetGradientImage() ) { itkExceptionMacro(<<"The gradient image is null, maybe you forgot to call Initialize()"); - } + } FixedImageConstPointer fixedImage = this->m_FixedImage; - if( !fixedImage ) - { + if( !fixedImage ) { itkExceptionMacro( << "Fixed image has not been assigned" ); - } + } const unsigned int ImageDimension = FixedImageType::ImageDimension; typedef itk::ImageRegionConstIteratorWithIndex< - FixedImageType> FixedIteratorType; + FixedImageType> FixedIteratorType; typedef itk::ImageRegionConstIteratorWithIndex< - ITK_TYPENAME Superclass::GradientImageType> GradientIteratorType; + ITK_TYPENAME Superclass::GradientImageType> GradientIteratorType; FixedIteratorType ti( fixedImage, this->GetFixedImageRegion() ); @@ -387,88 +361,77 @@ CorrelationRatioImageToImageMetric ti.GoToBegin(); - while(!ti.IsAtEnd()) - { + while(!ti.IsAtEnd()) { index = ti.GetIndex(); - + typename Superclass::InputPointType inputPoint; fixedImage->TransformIndexToPhysicalPoint( index, inputPoint ); - if( this->m_FixedImageMask && !this->m_FixedImageMask->IsInside( inputPoint ) ) - { + if( this->m_FixedImageMask && !this->m_FixedImageMask->IsInside( inputPoint ) ) { ++ti; continue; - } + } typename Superclass::OutputPointType transformedPoint = this->m_Transform->TransformPoint( inputPoint ); - if( this->m_MovingImageMask && !this->m_MovingImageMask->IsInside( transformedPoint ) ) - { + if( this->m_MovingImageMask && !this->m_MovingImageMask->IsInside( transformedPoint ) ) { ++ti; continue; - } + } - if( this->m_Interpolator->IsInsideBuffer( transformedPoint ) ) - { + if( this->m_Interpolator->IsInsideBuffer( transformedPoint ) ) { const RealType movingValue = this->m_Interpolator->Evaluate( transformedPoint ); const TransformJacobianType & jacobian = - this->m_Transform->GetJacobian( inputPoint ); + this->m_Transform->GetJacobian( inputPoint ); + - const RealType fixedValue = ti.Value(); this->m_NumberOfPixelsCounted++; - const RealType diff = movingValue - fixedValue; - + const RealType diff = movingValue - fixedValue; + measure += diff * diff; - // Get the gradient by NearestNeighboorInterpolation: + // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. typedef typename Superclass::OutputPointType OutputPointType; typedef typename OutputPointType::CoordRepType CoordRepType; typedef ContinuousIndex - MovingImageContinuousIndexType; + MovingImageContinuousIndexType; MovingImageContinuousIndexType tempIndex; this->m_MovingImage->TransformPhysicalPointToContinuousIndex( transformedPoint, tempIndex ); - typename MovingImageType::IndexType mappedIndex; - for( unsigned int j = 0; j < MovingImageType::ImageDimension; j++ ) - { + typename MovingImageType::IndexType mappedIndex; + for( unsigned int j = 0; j < MovingImageType::ImageDimension; j++ ) { mappedIndex[j] = static_cast( vnl_math_rnd( tempIndex[j] ) ); - } + } - const GradientPixelType gradient = + const GradientPixelType gradient = this->GetGradientImage()->GetPixel( mappedIndex ); - for(unsigned int par=0; par::Zero; - for(unsigned int dim=0; dimm_NumberOfPixelsCounted ) - { + if( !this->m_NumberOfPixelsCounted ) { itkExceptionMacro(<<"All the points mapped to outside of the moving image"); - } - else - { - for(unsigned int i=0; im_NumberOfPixelsCounted; - } - measure /= this->m_NumberOfPixelsCounted; } + measure /= this->m_NumberOfPixelsCounted; + } value = measure; diff --git a/tools/clitkDicomInfo.cxx b/tools/clitkDicomInfo.cxx index 4c31e09..303b1f5 100644 --- a/tools/clitkDicomInfo.cxx +++ b/tools/clitkDicomInfo.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -30,7 +30,8 @@ #include "gdcmFile.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // init command line GGO(clitkDicomInfo, args_info); @@ -47,7 +48,7 @@ int main(int argc, char * argv[]) { header->Print(); } - // this is the end my friend + // this is the end my friend return 0; } //-------------------------------------------------------------------- diff --git a/tools/clitkFooImage.cxx b/tools/clitkFooImage.cxx index 9cca95b..1ec94ae 100644 --- a/tools/clitkFooImage.cxx +++ b/tools/clitkFooImage.cxx @@ -30,20 +30,21 @@ #include "clitkFooImageGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ - // Init command line - GGO(clitkFooImage, args_info); - CLITK_INIT; + // Init command line + GGO(clitkFooImage, args_info); + CLITK_INIT; - // Filter - typedef clitk::FooImageGenericFilter FilterType; - FilterType::Pointer filter = FilterType::New(); + // Filter + typedef clitk::FooImageGenericFilter FilterType; + FilterType::Pointer filter = FilterType::New(); - filter->SetArgsInfo(args_info); - filter->Update(); + filter->SetArgsInfo(args_info); + filter->Update(); - return EXIT_SUCCESS; + return EXIT_SUCCESS; }// end main //-------------------------------------------------------------------- diff --git a/tools/clitkGuerreroVentilation.cxx b/tools/clitkGuerreroVentilation.cxx index f7632b8..424bb44 100644 --- a/tools/clitkGuerreroVentilation.cxx +++ b/tools/clitkGuerreroVentilation.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -28,7 +28,8 @@ #include "clitkIO.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkGuerreroVentilation, args_info); @@ -37,7 +38,7 @@ int main(int argc, char * argv[]) { // Read image dimension itk::ImageIOBase::Pointer header = clitk::readImageHeader(args_info.input_arg); //unsigned int dim = header->GetNumberOfDimensions(); - + // Check parameters // Main filter clitk::GuerreroVentilationGenericFilter filter; @@ -48,6 +49,6 @@ int main(int argc, char * argv[]) { filter.SetUseCorrectFormula(args_info.correct_flag); filter.Update(); - // this is the end my friend + // this is the end my friend return 0; } // end main diff --git a/tools/clitkImageArithm.cxx b/tools/clitkImageArithm.cxx index b7b72c0..3990f1c 100644 --- a/tools/clitkImageArithm.cxx +++ b/tools/clitkImageArithm.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -29,7 +29,8 @@ #include "clitkImageArithmGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkImageArithm, args_info); @@ -41,8 +42,8 @@ int main(int argc, char * argv[]) { // Go ! filter->SetArgsInfo(args_info); filter->Update(); - - // this is the end my friend + + // this is the end my friend return EXIT_SUCCESS; } // end main diff --git a/tools/clitkImageConvert.cxx b/tools/clitkImageConvert.cxx index 5d9eed0..0094497 100644 --- a/tools/clitkImageConvert.cxx +++ b/tools/clitkImageConvert.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,7 +31,8 @@ #include "clitkImageConvertGenericFilter.h" //-------------------------------------------------------------------= -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // init command line GGO(clitkImageConvert, args_info); @@ -48,7 +49,7 @@ int main(int argc, char * argv[]) { if (l.size() < 1) { std::cerr << "Error, you should give at least one --input option or one image filename on the commande line." << std::endl; exit(0); - } + } // Create filter clitk::ImageConvertGenericFilter::Pointer filter = clitk::ImageConvertGenericFilter::New(); @@ -58,9 +59,9 @@ int main(int argc, char * argv[]) { if (args_info.type_given) filter->SetOutputPixelType(args_info.type_arg); // Go ! - filter->Update(); + filter->Update(); - // this is the end my friend + // this is the end my friend return 0; } //-------------------------------------------------------------------= diff --git a/tools/clitkImageCreate.cxx b/tools/clitkImageCreate.cxx index d635eb5..ae9cf56 100644 --- a/tools/clitkImageCreate.cxx +++ b/tools/clitkImageCreate.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -32,7 +32,7 @@ template void NewFilledImage(int * size, float * spacing, double * origin, - double value,typename ImageType::Pointer output) + double value,typename ImageType::Pointer output) { static const unsigned int Dim = ImageType::GetImageDimension(); typename ImageType::SizeType mSize; @@ -55,7 +55,8 @@ void NewFilledImage(int * size, float * spacing, double * origin, //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkImageCreate, args_info); @@ -65,21 +66,21 @@ int main(int argc, char * argv[]) { int dim; if (args_info.like_given) { itk::ImageIOBase::Pointer header = clitk::readImageHeader(args_info.like_arg); - dim = header->GetNumberOfDimensions(); - //mPixelTypeName = header->GetComponentTypeAsString(header->GetComponentType()); - //mNbOfComponents = header->GetNumberOfComponents(); - args_info.size_given = dim; - args_info.size_arg = new int[dim]; - args_info.spacing_given = dim; - args_info.spacing_arg = new float[dim]; - args_info.origin_given = dim; - args_info.origin_arg = new double[dim]; - - for(int i=0; iGetDimensions(i); - args_info.spacing_arg[i] = header->GetSpacing(i); - args_info.origin_arg[i]= header->GetOrigin(i); - } + dim = header->GetNumberOfDimensions(); + //mPixelTypeName = header->GetComponentTypeAsString(header->GetComponentType()); + //mNbOfComponents = header->GetNumberOfComponents(); + args_info.size_given = dim; + args_info.size_arg = new int[dim]; + args_info.spacing_given = dim; + args_info.spacing_arg = new float[dim]; + args_info.origin_given = dim; + args_info.origin_arg = new double[dim]; + + for(int i=0; iGetDimensions(i); + args_info.spacing_arg[i] = header->GetSpacing(i); + args_info.origin_arg[i]= header->GetOrigin(i); + } } // Check dimension @@ -88,64 +89,61 @@ int main(int argc, char * argv[]) { exit(-1); } dim = args_info.size_given; - - // origin + + // origin std::vector origin; origin.resize(dim); for(int i=0; i spacing; spacing.resize(dim); if (args_info.spacing_given == 1) { for(int i=0; i ImageType; + typedef itk::Image ImageType; ImageType::Pointer output = ImageType::New(); NewFilledImage(args_info.size_arg, &spacing[0], &origin[0], args_info.value_arg, output); clitk::writeImage(output, args_info.output_arg); } if (dim == 3) { const int Dim=3; - typedef itk::Image ImageType; + typedef itk::Image ImageType; ImageType::Pointer output = ImageType::New(); NewFilledImage(args_info.size_arg, &spacing[0], &origin[0], args_info.value_arg, output); clitk::writeImage(output, args_info.output_arg); } if (dim == 4) { const int Dim=4; - typedef itk::Image ImageType; + typedef itk::Image ImageType; ImageType::Pointer output = ImageType::New(); NewFilledImage(args_info.size_arg, &spacing[0], &origin[0], args_info.value_arg, output); clitk::writeImage(output, args_info.output_arg); } - - // this is the end my friend + + // this is the end my friend return 0; } // end main diff --git a/tools/clitkImageExtractLine.cxx b/tools/clitkImageExtractLine.cxx index 1f826b6..0cf9454 100644 --- a/tools/clitkImageExtractLine.cxx +++ b/tools/clitkImageExtractLine.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,7 +31,8 @@ #include //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkImageExtractLine, args_info); @@ -41,7 +42,7 @@ int main(int argc, char * argv[]) { typedef float PixelType; const unsigned int Dimension=3; typedef itk::Image ImageType; - + // Check options if (args_info.firstIndex_given != Dimension) { std::cerr << "Please give " << Dimension << "values to --firstIndex option" << std::endl; @@ -63,7 +64,7 @@ int main(int argc, char * argv[]) { double length = 0.0; for(unsigned int i=0; i - * @date 23 Feb 2008 + * @date 23 Feb 2008 ------------------------------------------------=*/ // clitk include @@ -30,7 +30,8 @@ #include "clitkIO.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkImageFillRegion, args_info); @@ -39,84 +40,74 @@ int main(int argc, char * argv[]) { // Read image dimension itk::ImageIOBase::Pointer header = clitk::readImageHeader(args_info.input_arg); unsigned int dim = header->GetNumberOfDimensions(); - + // Main filter clitk::ImageFillRegionGenericFilter filter; filter.SetInputFilename(args_info.input_arg); filter.SetOutputFilename(args_info.output_arg); filter.SetFillPixelValue(args_info.value_arg); - - if(!args_info.ellips_flag && !args_info.rect_flag) - { - std::cerr << "ERROR : No type of region specified!"<< std::endl; - exit(-1); - } - if(args_info.ellips_flag && args_info.rect_flag) - { - std::cerr << "ERROR : Multiple types of regions specified!"<< std::endl; - exit(-1); - } + if(!args_info.ellips_flag && !args_info.rect_flag) { + std::cerr << "ERROR : No type of region specified!"<< std::endl; + exit(-1); + } + + if(args_info.ellips_flag && args_info.rect_flag) { + std::cerr << "ERROR : Multiple types of regions specified!"<< std::endl; + exit(-1); + } - if(args_info.rect_flag) - { - if (args_info.size_given && args_info.start_given) { - // Check parameters - if (args_info.size_given != dim) { - std::cerr << "ERROR : image has " << dim << "dimensions, --size should have the same number of values." << std::endl; - exit(-1); - } - if (args_info.start_given != dim) { - std::cerr << "ERROR : image has " << dim << "dimensions, --size should have the same number of values." << std::endl; - exit(-1); - } - filter.SetRegion(args_info.size_arg, args_info.start_arg); + if(args_info.rect_flag) { + if (args_info.size_given && args_info.start_given) { + // Check parameters + if (args_info.size_given != dim) { + std::cerr << "ERROR : image has " << dim << "dimensions, --size should have the same number of values." << std::endl; + exit(-1); } - else { - std::cerr << "ERROR : both size and start should be given!"<< std::endl; - exit(-1); + if (args_info.start_given != dim) { + std::cerr << "ERROR : image has " << dim << "dimensions, --size should have the same number of values." << std::endl; + exit(-1); } + filter.SetRegion(args_info.size_arg, args_info.start_arg); + } else { + std::cerr << "ERROR : both size and start should be given!"<< std::endl; + exit(-1); } + } - if(args_info.ellips_flag) - { - - std::vector c, a; - if (args_info.center_given) - { - if (args_info.center_given != dim) - { - std::cerr << "ERROR : image has " << dim << "dimensions, --center should have the same number of values." << std::endl; - exit(-1); - } - for(unsigned int i=0; i c, a; + if (args_info.center_given) { + if (args_info.center_given != dim) { + std::cerr << "ERROR : image has " << dim << "dimensions, --center should have the same number of values." << std::endl; + exit(-1); + } + for(unsigned int i=0; i sigma; sigma.resize(args_info.gauss_given); @@ -128,12 +127,11 @@ int main(int argc, char * argv[]) { if (args_info.gauss_given) { if (args_info.gauss_given != dim) { if (args_info.gauss_given == 1) { - sigma.resize(dim); - for(unsigned int i=0; iSetGaussianSigma(sigma); filter->SetOutputFilename(args_info.output_arg); - - // Go ! + + // Go ! filter->Update(); - // this is the end my friend + // this is the end my friend return 0; }// end main //-------------------------------------------------------------------- diff --git a/tools/clitkInvertVF.cxx b/tools/clitkInvertVF.cxx index 609c4e3..43f7251 100644 --- a/tools/clitkInvertVF.cxx +++ b/tools/clitkInvertVF.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,11 +18,11 @@ /* ================================================= * @file clitkInvertVF.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ @@ -33,7 +33,8 @@ //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkInvertVF, args_info); @@ -42,7 +43,7 @@ int main(int argc, char * argv[]) { // Filter typedef clitk::InvertVFGenericFilter FilterType; FilterType::Pointer genericFilter = FilterType::New(); - + genericFilter->SetArgsInfo(args_info); genericFilter->Update(); diff --git a/tools/clitkInvertVFGenericFilter.cxx b/tools/clitkInvertVFGenericFilter.cxx index 9206787..6ec318f 100644 --- a/tools/clitkInvertVFGenericFilter.cxx +++ b/tools/clitkInvertVFGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkInvertVFGenericFilter.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ #include "clitkInvertVFGenericFilter.h" diff --git a/tools/clitkInvertVFGenericFilter.txx b/tools/clitkInvertVFGenericFilter.txx index 8c430b5..0cf6cb4 100644 --- a/tools/clitkInvertVFGenericFilter.txx +++ b/tools/clitkInvertVFGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,164 +20,159 @@ /* ================================================= * @file clitkInvertVFGenericFilter.txx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ namespace clitk { - //----------------------------------------------------------- - // Constructor - //----------------------------------------------------------- - template - InvertVFGenericFilter::InvertVFGenericFilter() - { - m_Verbose=false; - m_InputFileName=""; - } +//----------------------------------------------------------- +// Constructor +//----------------------------------------------------------- +template +InvertVFGenericFilter::InvertVFGenericFilter() +{ + m_Verbose=false; + m_InputFileName=""; +} - //----------------------------------------------------------- - // Update - //----------------------------------------------------------- - template - void InvertVFGenericFilter::Update() - { - // Read the Dimension and PixelType - int Dimension; - std::string PixelType; - ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType); - - - // Call UpdateWithDim - if(Dimension==2) UpdateWithDim<2>(PixelType); - else if(Dimension==3) UpdateWithDim<3>(PixelType); - // else if (Dimension==4)UpdateWithDim<4>(PixelType); - else - { - std::cout<<"Error, Only for 2 or 3 Dimensions!!!"< +void InvertVFGenericFilter::Update() +{ + // Read the Dimension and PixelType + int Dimension; + std::string PixelType; + ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType); + + + // Call UpdateWithDim + if(Dimension==2) UpdateWithDim<2>(PixelType); + else if(Dimension==3) UpdateWithDim<3>(PixelType); + // else if (Dimension==4)UpdateWithDim<4>(PixelType); + else { + std::cout<<"Error, Only for 2 or 3 Dimensions!!!"< +template +void +InvertVFGenericFilter::UpdateWithDim(std::string PixelType) +{ + if (m_Verbose) std::cout << "Image was detected to be "<(); + // } + // else if(PixelType == "unsigned_short"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + // else if (PixelType == "unsigned_char"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + // else if (PixelType == "char"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + // else { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; + UpdateWithDimAndPixelType >(); + // } +} + + +//------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//------------------------------------------------------------------- +template +template +void +InvertVFGenericFilter::UpdateWithDimAndPixelType() +{ - //------------------------------------------------------------------- - // Update with the number of dimensions - //------------------------------------------------------------------- - template - template - void - InvertVFGenericFilter::UpdateWithDim(std::string PixelType) - { - if (m_Verbose) std::cout << "Image was detected to be "<(); - // } - // else if(PixelType == "unsigned_short"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - // else if (PixelType == "unsigned_char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - // else if (PixelType == "char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - // else { - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; - UpdateWithDimAndPixelType >(); - // } + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image OutputImageType; + + // Read the input + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer reader = InputReaderType::New(); + reader->SetFileName( m_InputFileName); + reader->Update(); + typename InputImageType::Pointer input= reader->GetOutput(); + + // Filter + typename OutputImageType::Pointer output; + switch (m_ArgsInfo.type_arg) { + + // clitk filter + case 0: { + // Create the InvertVFFilter + typedef clitk::InvertVFFilter FilterType; + typename FilterType::Pointer filter =FilterType::New(); + filter->SetInput(input); + filter->SetVerbose(m_Verbose); + if (m_ArgsInfo.threads_given) filter->SetNumberOfThreads(m_ArgsInfo.threads_arg); + if (m_ArgsInfo.pad_given) { + PixelType pad; + if (m_ArgsInfo.pad_given != (pad.GetNumberOfComponents()) ) + pad.Fill(m_ArgsInfo.pad_arg[0]); + else + for(unsigned int i=0; iSetThreadSafe(m_ArgsInfo.threadSafe_flag); + filter->Update(); + output=filter->GetOutput(); + + break; } + case 1: { + // Create the InverseDeformationFieldFilter + typedef itk::InverseDeformationFieldImageFilter FilterType; + typename FilterType::Pointer filter =FilterType::New(); + filter->SetInput(input); + filter->SetOutputOrigin(input->GetOrigin()); + filter->SetOutputSpacing(input->GetSpacing()); + filter->SetSize(input->GetLargestPossibleRegion().GetSize()); + filter->SetSubsamplingFactor(m_ArgsInfo.sampling_arg); + filter->Update(); + output=filter->GetOutput(); + + break; + } - //------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //------------------------------------------------------------------- - template - template - void - InvertVFGenericFilter::UpdateWithDimAndPixelType() - { - - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - - // Read the input - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer reader = InputReaderType::New(); - reader->SetFileName( m_InputFileName); - reader->Update(); - typename InputImageType::Pointer input= reader->GetOutput(); - - // Filter - typename OutputImageType::Pointer output; - switch (m_ArgsInfo.type_arg) - { - - // clitk filter - case 0: - { - // Create the InvertVFFilter - typedef clitk::InvertVFFilter FilterType; - typename FilterType::Pointer filter =FilterType::New(); - filter->SetInput(input); - filter->SetVerbose(m_Verbose); - if (m_ArgsInfo.threads_given) filter->SetNumberOfThreads(m_ArgsInfo.threads_arg); - if (m_ArgsInfo.pad_given) - { - PixelType pad; - if (m_ArgsInfo.pad_given != (pad.GetNumberOfComponents()) ) - pad.Fill(m_ArgsInfo.pad_arg[0]); - else - for(unsigned int i=0; iSetThreadSafe(m_ArgsInfo.threadSafe_flag); - filter->Update(); - output=filter->GetOutput(); - - break; - } - - case 1: - { - // Create the InverseDeformationFieldFilter - typedef itk::InverseDeformationFieldImageFilter FilterType; - typename FilterType::Pointer filter =FilterType::New(); - filter->SetInput(input); - filter->SetOutputOrigin(input->GetOrigin()); - filter->SetOutputSpacing(input->GetSpacing()); - filter->SetSize(input->GetLargestPossibleRegion().GetSize()); - filter->SetSubsamplingFactor(m_ArgsInfo.sampling_arg); - filter->Update(); - output=filter->GetOutput(); - - break; - } - - } - - // Output - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_ArgsInfo.output_arg); - writer->SetInput(output); - writer->Update(); - } - - + + // Output + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_ArgsInfo.output_arg); + writer->SetInput(output); + writer->Update(); + +} + + }//end clitk - + #endif //#define clitkInvertVFGenericFilter_txx diff --git a/tools/clitkMedianImageFilter.cxx b/tools/clitkMedianImageFilter.cxx index 7c8dcc8..bcf2cb4 100644 --- a/tools/clitkMedianImageFilter.cxx +++ b/tools/clitkMedianImageFilter.cxx @@ -1,22 +1,22 @@ /*------------------------------------------------------------------------ - + Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de l'Image). All rights reserved. See Doc/License.txt or http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html 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. - + ------------------------------------------------------------------------*/ /* ================================================= * @file clitkMedianImageGenericFilter.txx * @author Bharath Navalpakkam * @date 18 March 2010 - * + * * @brief Apply Median Filter to an Image - * + * ===================================================*/ // clitk @@ -24,21 +24,22 @@ #include "clitkMedianImageGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkMedianImageFilter, args_info); CLITK_INIT; // Filter - clitk::MedianImageGenericFilter::Pointer filter = + clitk::MedianImageGenericFilter::Pointer filter = clitk::MedianImageGenericFilter::New(); - - - filter->SetOutputFilename(args_info.output_arg); - + + + filter->SetOutputFilename(args_info.output_arg); + filter->SetArgsInfo(args_info); - + filter->Update(); return EXIT_SUCCESS; diff --git a/tools/clitkResampleImage.cxx b/tools/clitkResampleImage.cxx index acecb05..f289128 100644 --- a/tools/clitkResampleImage.cxx +++ b/tools/clitkResampleImage.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,7 +22,8 @@ #include "clitkResampleImageGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkResampleImage, args_info); @@ -30,11 +31,11 @@ int main(int argc, char * argv[]) { // Filter typedef clitk::ResampleImageGenericFilter FilterType; FilterType::Pointer filter = FilterType::New(); - + filter->SetArgsInfo(args_info); filter->Update(); - // this is the end my friend + // this is the end my friend return EXIT_SUCCESS; }// end main diff --git a/tools/clitkRigidRegistration.cxx b/tools/clitkRigidRegistration.cxx index f9d6efa..1db3e75 100644 --- a/tools/clitkRigidRegistration.cxx +++ b/tools/clitkRigidRegistration.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,9 +20,9 @@ * @file clitkRigidRegistration.cxx * @author Jef Vandemeulebroucke * @date 14 August 2007 - * + * * @brief Perform a rigid registration between 2 images - * + * -------------------------------------------------*/ @@ -39,9 +39,9 @@ using namespace std; int main( int argc, char *argv[] ) { //init command line and check options - GGO(args_info); + GGO(args_info); CLITK_INIT; - + //--------------------------------------------------------------------------- //Set all the options passed through the commandline @@ -51,7 +51,7 @@ int main( int argc, char *argv[] ) rigidRegistration.SetGradient(args_info.gradient_flag); rigidRegistration.SetZeroOrigin(args_info.zero_origin_flag); - //Input +//Input rigidRegistration.SetFixedImageName(args_info.reference_arg); rigidRegistration.SetMovingImageName(args_info.object_arg); rigidRegistration.SetFixedImageMaskGiven(args_info.mask_given); @@ -83,9 +83,9 @@ int main( int argc, char *argv[] ) rigidRegistration.SetTransZ(args_info.transZ_arg); //Optimizer - rigidRegistration.SetLevels(args_info.levels_arg); - rigidRegistration.SetIstep(args_info.Istep_arg); - rigidRegistration.SetFstep(args_info.Fstep_arg); + rigidRegistration.SetLevels(args_info.levels_arg); + rigidRegistration.SetIstep(args_info.Istep_arg); + rigidRegistration.SetFstep(args_info.Fstep_arg); rigidRegistration.SetRelax(args_info.relax_arg); rigidRegistration.SetInc(args_info.inc_arg); rigidRegistration.SetDec(args_info.dec_arg); @@ -101,9 +101,9 @@ int main( int argc, char *argv[] ) rigidRegistration.SetStdDev(args_info.stdDev_arg); //Preprocessing - rigidRegistration.SetBlur(args_info.blur_arg); - rigidRegistration.SetNormalize(args_info.normalize_flag); + rigidRegistration.SetBlur(args_info.blur_arg); + rigidRegistration.SetNormalize(args_info.normalize_flag); rigidRegistration.Update(); - + } diff --git a/tools/clitkSetBackground.cxx b/tools/clitkSetBackground.cxx index 1a44e9a..420f4fe 100644 --- a/tools/clitkSetBackground.cxx +++ b/tools/clitkSetBackground.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,11 +18,11 @@ /* ================================================= * @file clitkSetBackground.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ @@ -33,7 +33,8 @@ //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkSetBackground,args_info); @@ -41,7 +42,7 @@ int main(int argc, char * argv[]) { // Filter clitk::SetBackgroundGenericFilter::Pointer genericFilter=clitk::SetBackgroundGenericFilter::New(); - + genericFilter->SetArgsInfo(args_info); genericFilter->Update(); diff --git a/tools/clitkSetBackgroundGenericFilter.cxx b/tools/clitkSetBackgroundGenericFilter.cxx index e0c37d6..5ad22aa 100644 --- a/tools/clitkSetBackgroundGenericFilter.cxx +++ b/tools/clitkSetBackgroundGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkSetBackgroundGenericFilter.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ #include "clitkSetBackgroundGenericFilter.h" @@ -34,37 +34,36 @@ namespace clitk { - //----------------------------------------------------------- - // Constructor - //----------------------------------------------------------- - SetBackgroundGenericFilter::SetBackgroundGenericFilter() - { - m_Verbose=false; - m_InputFileName=""; - } +//----------------------------------------------------------- +// Constructor +//----------------------------------------------------------- +SetBackgroundGenericFilter::SetBackgroundGenericFilter() +{ + m_Verbose=false; + m_InputFileName=""; +} - //----------------------------------------------------------- - // Update - //----------------------------------------------------------- - void SetBackgroundGenericFilter::Update() - { - // Read the Dimension and PixelType - int Dimension; - std::string PixelType; - ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType); - - - // Call UpdateWithDim - if(Dimension==2) UpdateWithDim<2>(PixelType); - else if(Dimension==3) UpdateWithDim<3>(PixelType); - else if (Dimension==4)UpdateWithDim<4>(PixelType); - else - { - std::cout<<"Error, Only for 2 , 3 or 4 Dimensions!!!"<(PixelType); + else if(Dimension==3) UpdateWithDim<3>(PixelType); + else if (Dimension==4)UpdateWithDim<4>(PixelType); + else { + std::cout<<"Error, Only for 2 , 3 or 4 Dimensions!!!"< - void - SetBackgroundGenericFilter::UpdateWithDim(std::string PixelType) - { - if (m_Verbose) std::cout << "Image was detected to be "<(); - } - // else if(PixelType == "unsigned_short"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - else if (PixelType == "unsigned_char"){ - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; - UpdateWithDimAndPixelType(); - } - - // else if (PixelType == "char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - else { - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; - UpdateWithDimAndPixelType(); - } +//------------------------------------------------------------------- +// Update with the number of dimensions +//------------------------------------------------------------------- +template +void +SetBackgroundGenericFilter::UpdateWithDim(std::string PixelType) +{ + if (m_Verbose) std::cout << "Image was detected to be "<(); + } + // else if(PixelType == "unsigned_short"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + else if (PixelType == "unsigned_char") { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; + UpdateWithDimAndPixelType(); } + // else if (PixelType == "char"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + else { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; + UpdateWithDimAndPixelType(); + } +} - //------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //------------------------------------------------------------------- - template - void - SetBackgroundGenericFilter::UpdateWithDimAndPixelType() - { - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image MaskImageType; - - // Read the input - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer reader = InputReaderType::New(); - reader->SetFileName( m_InputFileName); - typename InputImageType::Pointer input= reader->GetOutput(); - - // Read the mask - typedef itk::ImageFileReader MaskReaderType; - typename MaskReaderType::Pointer maskReader = MaskReaderType::New(); - maskReader->SetFileName( m_ArgsInfo.mask_arg); - typename MaskImageType::Pointer mask= maskReader->GetOutput(); - - // Filter setting background - typedef clitk::SetBackgroundImageFilter SetBackgroundFilterType; - typename SetBackgroundFilterType::Pointer setBackgroundFilter = SetBackgroundFilterType::New(); - setBackgroundFilter->SetInput(input); - setBackgroundFilter->SetInput2(mask); - if(m_ArgsInfo.fg_flag) setBackgroundFilter->SetForeground(m_ArgsInfo.fg_flag); - if(m_ArgsInfo.maskValue_given) setBackgroundFilter->SetMaskValue(m_ArgsInfo.maskValue_arg); - if(m_ArgsInfo.outsideValue_given) setBackgroundFilter->SetOutsideValue(m_ArgsInfo.outsideValue_arg); - setBackgroundFilter->Update(); - typename InputImageType::Pointer output =setBackgroundFilter->GetOutput(); - - // Output - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_ArgsInfo.output_arg); - writer->SetInput(output); - writer->Update(); +//------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//------------------------------------------------------------------- +template +void +SetBackgroundGenericFilter::UpdateWithDimAndPixelType() +{ - } + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image MaskImageType; + + // Read the input + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer reader = InputReaderType::New(); + reader->SetFileName( m_InputFileName); + typename InputImageType::Pointer input= reader->GetOutput(); + + // Read the mask + typedef itk::ImageFileReader MaskReaderType; + typename MaskReaderType::Pointer maskReader = MaskReaderType::New(); + maskReader->SetFileName( m_ArgsInfo.mask_arg); + typename MaskImageType::Pointer mask= maskReader->GetOutput(); + + // Filter setting background + typedef clitk::SetBackgroundImageFilter SetBackgroundFilterType; + typename SetBackgroundFilterType::Pointer setBackgroundFilter = SetBackgroundFilterType::New(); + setBackgroundFilter->SetInput(input); + setBackgroundFilter->SetInput2(mask); + if(m_ArgsInfo.fg_flag) setBackgroundFilter->SetForeground(m_ArgsInfo.fg_flag); + if(m_ArgsInfo.maskValue_given) setBackgroundFilter->SetMaskValue(m_ArgsInfo.maskValue_arg); + if(m_ArgsInfo.outsideValue_given) setBackgroundFilter->SetOutsideValue(m_ArgsInfo.outsideValue_arg); + setBackgroundFilter->Update(); + typename InputImageType::Pointer output =setBackgroundFilter->GetOutput(); + + // Output + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_ArgsInfo.output_arg); + writer->SetInput(output); + writer->Update(); + +} }//end clitk - + #endif //#define clitkSetBackgroundGenericFilter_txx diff --git a/tools/clitkSplitImage.cxx b/tools/clitkSplitImage.cxx index ba30592..a76f88c 100644 --- a/tools/clitkSplitImage.cxx +++ b/tools/clitkSplitImage.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -28,7 +28,8 @@ #include "clitkIO.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkSplitImage, args_info); @@ -36,13 +37,12 @@ int main(int argc, char * argv[]) { // Read image dimension itk::ImageIOBase::Pointer header = clitk::readImageHeader(args_info.input_arg); - if (header.IsNull()) - { - std::cerr << "Unable to read image file " << args_info.input_arg << std::endl; - std::exit(1); + if (header.IsNull()) { + std::cerr << "Unable to read image file " << args_info.input_arg << std::endl; + std::exit(1); } unsigned int dim = header->GetNumberOfDimensions(); - + // Check parameters if (args_info.dimension_given >= dim) { std::cerr << "ERROR : image has " << dim << "dimensions, split dimension should be between 0 and " << dim-1 << "." << std::endl; @@ -56,6 +56,6 @@ int main(int argc, char * argv[]) { filter.SetVerbose(args_info.verbose_flag); filter.Update(); - // this is the end my friend + // this is the end my friend return 0; } // end main diff --git a/tools/clitkUnsharpMask.cxx b/tools/clitkUnsharpMask.cxx index d222ca1..2e6c3c1 100644 --- a/tools/clitkUnsharpMask.cxx +++ b/tools/clitkUnsharpMask.cxx @@ -30,20 +30,21 @@ #include "clitkUnsharpMaskGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ - // Init command line - GGO(clitkUnsharpMask, args_info); - CLITK_INIT; + // Init command line + GGO(clitkUnsharpMask, args_info); + CLITK_INIT; - // Filter - typedef clitk::UnsharpMaskGenericFilter FilterType; - FilterType::Pointer filter = FilterType::New(); + // Filter + typedef clitk::UnsharpMaskGenericFilter FilterType; + FilterType::Pointer filter = FilterType::New(); - filter->SetArgsInfo(args_info); - filter->Update(); + filter->SetArgsInfo(args_info); + filter->Update(); - return EXIT_SUCCESS; + return EXIT_SUCCESS; }// end main //-------------------------------------------------------------------- diff --git a/tools/clitkVFMerge.cxx b/tools/clitkVFMerge.cxx index 738c966..d98cfef 100644 --- a/tools/clitkVFMerge.cxx +++ b/tools/clitkVFMerge.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,10 +22,10 @@ * @file clitkVFMerge.cxx * @author Jef Vandemeulebroucke * @date June 15 10:14:53 2007 - * + * * @brief Read in one VF (ex mhd, vf) and write to another. Transforming from mm to voxels needed for the vf format is implemented in clitkVfImageIO.cxx . - * - * + * + * */ // clitk include @@ -48,104 +48,100 @@ int main( int argc, char *argv[] ) GGO(clitkVFMerge, args_info); CLITK_INIT; -const unsigned int SpaceDimension = 3; -const unsigned int ModelDimension = 4; -typedef itk::Vector< float, SpaceDimension > Displacement; -typedef itk::Image< Displacement, SpaceDimension > DeformationFieldType; -typedef itk::Image< Displacement, ModelDimension > DynamicDeformationFieldType; -typedef itk::ImageFileReader< DeformationFieldType > DeformationFieldReaderType; -typedef itk::ImageFileWriter< DynamicDeformationFieldType > DynamicDeformationFieldWriterType; + const unsigned int SpaceDimension = 3; + const unsigned int ModelDimension = 4; + typedef itk::Vector< float, SpaceDimension > Displacement; + typedef itk::Image< Displacement, SpaceDimension > DeformationFieldType; + typedef itk::Image< Displacement, ModelDimension > DynamicDeformationFieldType; + typedef itk::ImageFileReader< DeformationFieldType > DeformationFieldReaderType; + typedef itk::ImageFileWriter< DynamicDeformationFieldType > DynamicDeformationFieldWriterType; + - //declare the dynamic - DynamicDeformationFieldType::Pointer dynamicDeformationField=DynamicDeformationFieldType::New(); - - - //declare their iterators - typedef itk::ImageRegionIterator< DynamicDeformationFieldType> DynamicDeformationFieldIteratorType; - DynamicDeformationFieldIteratorType *dynamicIteratorPointer= new DynamicDeformationFieldIteratorType; - - for (unsigned int i=0 ; i< args_info.inputs_num ; i ++) - { - //read in the deformation field i - DeformationFieldReaderType::Pointer deformationFieldReader = DeformationFieldReaderType::New(); - deformationFieldReader->SetFileName( args_info.inputs[i]); - if (args_info.verbose_flag) std::cout<<"Reading VF number "<< i+1 << std::endl; - deformationFieldReader->Update(); - DeformationFieldType::Pointer currentDeformationField = deformationFieldReader->GetOutput(); - - //create an iterator for the current deformation field - typedef itk::ImageRegionIterator FieldIteratorType; - FieldIteratorType fieldIterator(currentDeformationField, currentDeformationField->GetLargestPossibleRegion()); - - //Allocate memory for the dynamic components - if (i==0) - { - DynamicDeformationFieldType::RegionType dynamicDeformationFieldRegion; - DynamicDeformationFieldType::RegionType::SizeType dynamicDeformationFieldSize; - DeformationFieldType::RegionType::SizeType deformationFieldSize; - deformationFieldSize= currentDeformationField->GetLargestPossibleRegion().GetSize(); - dynamicDeformationFieldSize[0]=deformationFieldSize[0]; - dynamicDeformationFieldSize[1]=deformationFieldSize[1]; - dynamicDeformationFieldSize[2]=deformationFieldSize[2]; - dynamicDeformationFieldSize[3]=args_info.inputs_num; - dynamicDeformationFieldRegion.SetSize(dynamicDeformationFieldSize); - DynamicDeformationFieldType::IndexType start; - start.Fill(0); - dynamicDeformationFieldRegion.SetIndex(start); - dynamicDeformationField->SetRegions(dynamicDeformationFieldRegion); - dynamicDeformationField->Allocate(); - - - //Set the spacing - DeformationFieldType::SpacingType spacing= currentDeformationField->GetSpacing(); - DynamicDeformationFieldType::SpacingType dynamicSpacing; - dynamicSpacing[0]=spacing[0]; - dynamicSpacing[1]=spacing[1]; - dynamicSpacing[2]=spacing[2]; - dynamicSpacing[3]=args_info.spacing_arg; //JV par exemple - dynamicDeformationField->SetSpacing(dynamicSpacing); - DynamicDeformationFieldType::PointType origin; - origin[0]=args_info.xorigin_arg; - origin[1]=args_info.yorigin_arg; - origin[2]=args_info.zorigin_arg; - origin[3]=0; //temporal origin is always 0 - dynamicDeformationField->SetOrigin(origin); - - // Creating iterators for the currentDeformationField and the DynamicDeformationField - DynamicDeformationFieldIteratorType *dynamicIterator= new DynamicDeformationFieldIteratorType(dynamicDeformationField, dynamicDeformationField->GetLargestPossibleRegion()); - dynamicIteratorPointer=dynamicIterator; - dynamicIteratorPointer->GoToBegin(); - } - if (args_info.verbose_flag) std::cout<<"Merging VF number "<< i+1 << std::endl; - //Copy the current component of the input into dynamicDeformationFieldComponent - fieldIterator.GoToBegin(); - while(!fieldIterator.IsAtEnd()) - { - dynamicIteratorPointer->Set(fieldIterator.Get()); - ++fieldIterator; - ++(*dynamicIteratorPointer); - } - } - + DynamicDeformationFieldType::Pointer dynamicDeformationField=DynamicDeformationFieldType::New(); + + +//declare their iterators + typedef itk::ImageRegionIterator< DynamicDeformationFieldType> DynamicDeformationFieldIteratorType; + DynamicDeformationFieldIteratorType *dynamicIteratorPointer= new DynamicDeformationFieldIteratorType; + + for (unsigned int i=0 ; i< args_info.inputs_num ; i ++) { + //read in the deformation field i + DeformationFieldReaderType::Pointer deformationFieldReader = DeformationFieldReaderType::New(); + deformationFieldReader->SetFileName( args_info.inputs[i]); + if (args_info.verbose_flag) std::cout<<"Reading VF number "<< i+1 << std::endl; + deformationFieldReader->Update(); + DeformationFieldType::Pointer currentDeformationField = deformationFieldReader->GetOutput(); + + //create an iterator for the current deformation field + typedef itk::ImageRegionIterator FieldIteratorType; + FieldIteratorType fieldIterator(currentDeformationField, currentDeformationField->GetLargestPossibleRegion()); + + //Allocate memory for the dynamic components + if (i==0) { + DynamicDeformationFieldType::RegionType dynamicDeformationFieldRegion; + DynamicDeformationFieldType::RegionType::SizeType dynamicDeformationFieldSize; + DeformationFieldType::RegionType::SizeType deformationFieldSize; + deformationFieldSize= currentDeformationField->GetLargestPossibleRegion().GetSize(); + dynamicDeformationFieldSize[0]=deformationFieldSize[0]; + dynamicDeformationFieldSize[1]=deformationFieldSize[1]; + dynamicDeformationFieldSize[2]=deformationFieldSize[2]; + dynamicDeformationFieldSize[3]=args_info.inputs_num; + dynamicDeformationFieldRegion.SetSize(dynamicDeformationFieldSize); + DynamicDeformationFieldType::IndexType start; + start.Fill(0); + dynamicDeformationFieldRegion.SetIndex(start); + dynamicDeformationField->SetRegions(dynamicDeformationFieldRegion); + dynamicDeformationField->Allocate(); + + + //Set the spacing + DeformationFieldType::SpacingType spacing= currentDeformationField->GetSpacing(); + DynamicDeformationFieldType::SpacingType dynamicSpacing; + dynamicSpacing[0]=spacing[0]; + dynamicSpacing[1]=spacing[1]; + dynamicSpacing[2]=spacing[2]; + dynamicSpacing[3]=args_info.spacing_arg; //JV par exemple + dynamicDeformationField->SetSpacing(dynamicSpacing); + DynamicDeformationFieldType::PointType origin; + origin[0]=args_info.xorigin_arg; + origin[1]=args_info.yorigin_arg; + origin[2]=args_info.zorigin_arg; + origin[3]=0; //temporal origin is always 0 + dynamicDeformationField->SetOrigin(origin); + + // Creating iterators for the currentDeformationField and the DynamicDeformationField + DynamicDeformationFieldIteratorType *dynamicIterator= new DynamicDeformationFieldIteratorType(dynamicDeformationField, dynamicDeformationField->GetLargestPossibleRegion()); + dynamicIteratorPointer=dynamicIterator; + dynamicIteratorPointer->GoToBegin(); + } + if (args_info.verbose_flag) std::cout<<"Merging VF number "<< i+1 << std::endl; + //Copy the current component of the input into dynamicDeformationFieldComponent + fieldIterator.GoToBegin(); + while(!fieldIterator.IsAtEnd()) { + dynamicIteratorPointer->Set(fieldIterator.Get()); + ++fieldIterator; + ++(*dynamicIteratorPointer); + } + } + //Write the vector field - DynamicDeformationFieldWriterType::Pointer writer = DynamicDeformationFieldWriterType::New(); - writer->SetInput( dynamicDeformationField ); - writer->SetFileName( args_info.output_arg ); - if (args_info.verbose_flag) std::cout<<"Writing the dynamic VF"<< std::endl; - - - try { - - writer->Update( ); - } - catch( itk::ExceptionObject & excp ) { - std::cerr << "Problem writing the output file" << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } - return EXIT_SUCCESS; + DynamicDeformationFieldWriterType::Pointer writer = DynamicDeformationFieldWriterType::New(); + writer->SetInput( dynamicDeformationField ); + writer->SetFileName( args_info.output_arg ); + if (args_info.verbose_flag) std::cout<<"Writing the dynamic VF"<< std::endl; + + + try { + + writer->Update( ); + } catch( itk::ExceptionObject & excp ) { + std::cerr << "Problem writing the output file" << std::endl; + std::cerr << excp << std::endl; + return EXIT_FAILURE; + } + return EXIT_SUCCESS; } #endif diff --git a/tools/clitkVFResample.cxx b/tools/clitkVFResample.cxx index 0e25054..91e4094 100644 --- a/tools/clitkVFResample.cxx +++ b/tools/clitkVFResample.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -30,7 +30,8 @@ #include "clitkVFResampleGenericFilter.h" //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkImageResample, args_info); @@ -83,10 +84,10 @@ int main(int argc, char * argv[]) { exit(0); } for(unsigned int i=0; i sigma; sigma.resize(args_info.gauss_given); @@ -128,12 +127,11 @@ int main(int argc, char * argv[]) { if (args_info.gauss_given) { if (args_info.gauss_given != dim) { if (args_info.gauss_given == 1) { - sigma.resize(dim); - for(unsigned int i=0; iSetGaussianSigma(sigma); filter->SetOutputFilename(args_info.output_arg); - - // Go ! + + // Go ! filter->Update(); - // this is the end my friend + // this is the end my friend return 0; }// end main //-------------------------------------------------------------------- diff --git a/tools/clitkWarpImage.cxx b/tools/clitkWarpImage.cxx index f46085d..8c3a67f 100644 --- a/tools/clitkWarpImage.cxx +++ b/tools/clitkWarpImage.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,11 +18,11 @@ /* ================================================= * @file clitkWarpImage.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ @@ -33,7 +33,8 @@ //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkWarpImage, args_info); @@ -41,7 +42,7 @@ int main(int argc, char * argv[]) { // Filter clitk::WarpImageGenericFilter::Pointer genericFilter=clitk::WarpImageGenericFilter::New(); - + genericFilter->SetArgsInfo(args_info); genericFilter->Update(); diff --git a/tools/clitkWarpImageGenericFilter.cxx b/tools/clitkWarpImageGenericFilter.cxx index 5e7348a..9f2f71c 100644 --- a/tools/clitkWarpImageGenericFilter.cxx +++ b/tools/clitkWarpImageGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkWarpImageGenericFilter.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ #include "clitkWarpImageGenericFilter.h" @@ -34,37 +34,36 @@ namespace clitk { - //----------------------------------------------------------- - // Constructor - //----------------------------------------------------------- - WarpImageGenericFilter::WarpImageGenericFilter() - { - m_Verbose=false; - m_InputFileName=""; - } +//----------------------------------------------------------- +// Constructor +//----------------------------------------------------------- +WarpImageGenericFilter::WarpImageGenericFilter() +{ + m_Verbose=false; + m_InputFileName=""; +} - //----------------------------------------------------------- - // Update - //----------------------------------------------------------- - void WarpImageGenericFilter::Update() - { - // Read the Dimension and PixelType - int Dimension; - std::string PixelType; - ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType); - - - // Call UpdateWithDim - if(Dimension==2) UpdateWithDim<2>(PixelType); - else if(Dimension==3) UpdateWithDim<3>(PixelType); - // else if (Dimension==4)UpdateWithDim<4>(PixelType); - else - { - std::cout<<"Error, Only for 2 or 3 Dimensions!!!"<(PixelType); + else if(Dimension==3) UpdateWithDim<3>(PixelType); + // else if (Dimension==4)UpdateWithDim<4>(PixelType); + else { + std::cout<<"Error, Only for 2 or 3 Dimensions!!!"< - void - WarpImageGenericFilter::UpdateWithDim(std::string PixelType) - { - if (m_Verbose) std::cout << "Image was detected to be "<(); - } - // else if(PixelType == "unsigned_short"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - else if (PixelType == "unsigned_char"){ - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; - UpdateWithDimAndPixelType(); - } - - // else if (PixelType == "char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - else { - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; - UpdateWithDimAndPixelType(); - } +//------------------------------------------------------------------- +// Update with the number of dimensions +//------------------------------------------------------------------- +template +void +WarpImageGenericFilter::UpdateWithDim(std::string PixelType) +{ + if (m_Verbose) std::cout << "Image was detected to be "<(); } + // else if(PixelType == "unsigned_short"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + else if (PixelType == "unsigned_char") { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; + UpdateWithDimAndPixelType(); + } + + // else if (PixelType == "char"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + else { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; + UpdateWithDimAndPixelType(); + } +} - //------------------------------------------------------------------- - // Update with the number of dimensions and the pixeltype - //------------------------------------------------------------------- - template - void - WarpImageGenericFilter::UpdateWithDimAndPixelType() - { - - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - typedef itk::Vector DisplacementType; - typedef itk::Image DeformationFieldType; - - - // Read the input - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer reader = InputReaderType::New(); - reader->SetFileName( m_InputFileName); - reader->Update(); - typename InputImageType::Pointer input= reader->GetOutput(); - - //Read the deformation field - typedef itk::ImageFileReader DeformationFieldReaderType; - typename DeformationFieldReaderType::Pointer deformationFieldReader= DeformationFieldReaderType::New(); - deformationFieldReader->SetFileName(m_ArgsInfo.vf_arg); - deformationFieldReader->Update(); - typename DeformationFieldType::Pointer deformationField =deformationFieldReader->GetOutput(); - - // Intensity interpolator +//------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//------------------------------------------------------------------- +template +void +WarpImageGenericFilter::UpdateWithDimAndPixelType() +{ + + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image OutputImageType; + typedef itk::Vector DisplacementType; + typedef itk::Image DeformationFieldType; + + + // Read the input + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer reader = InputReaderType::New(); + reader->SetFileName( m_InputFileName); + reader->Update(); + typename InputImageType::Pointer input= reader->GetOutput(); + + //Read the deformation field + typedef itk::ImageFileReader DeformationFieldReaderType; + typename DeformationFieldReaderType::Pointer deformationFieldReader= DeformationFieldReaderType::New(); + deformationFieldReader->SetFileName(m_ArgsInfo.vf_arg); + deformationFieldReader->Update(); + typename DeformationFieldType::Pointer deformationField =deformationFieldReader->GetOutput(); + + // Intensity interpolator + typedef clitk::GenericVectorInterpolator GenericInterpolatorType; + typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); + genericInterpolator->SetArgsInfo(m_ArgsInfo); + + + // ------------------------------------------- + // Spacing like DVF + // ------------------------------------------- + if (m_ArgsInfo.spacing_arg == 0) { + // Calculate the region + typename DeformationFieldType::SizeType newSize; + for (unsigned int i=0 ; i GetLargestPossibleRegion().GetSize()[i]*input->GetSpacing()[i]/deformationField->GetSpacing()[i]); + + // Get the interpolator typedef clitk::GenericVectorInterpolator GenericInterpolatorType; typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); genericInterpolator->SetArgsInfo(m_ArgsInfo); - - - // ------------------------------------------- - // Spacing like DVF - // ------------------------------------------- - if (m_ArgsInfo.spacing_arg == 0) - { - // Calculate the region - typename DeformationFieldType::SizeType newSize; - for (unsigned int i=0 ; i GetLargestPossibleRegion().GetSize()[i]*input->GetSpacing()[i]/deformationField->GetSpacing()[i]); - - // Get the interpolator - typedef clitk::GenericVectorInterpolator GenericInterpolatorType; - typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); - genericInterpolator->SetArgsInfo(m_ArgsInfo); - - // Resample to match the extent of the input - typename itk::VectorResampleImageFilter::Pointer - resampler =itk::VectorResampleImageFilter::New(); - resampler->SetInput(deformationField); - resampler->SetOutputSpacing(deformationField->GetSpacing()); - resampler->SetSize(newSize); - resampler->SetOutputOrigin(input->GetOrigin()); - resampler->SetInterpolator(genericInterpolator->GetInterpolatorPointer()); - - // Update - if (m_Verbose) std::cout<< "Resampling the VF..." <Update(); - } - catch( itk::ExceptionObject & excp ) { - std::cerr << "Problem resampling the input vector field file" << std::endl; - std::cerr << excp << std::endl; - return; - } - deformationField= resampler->GetOutput(); - - } - - // ------------------------------------------- - // Spacing like input - // ------------------------------------------- - else - { - // Get size - typename DeformationFieldType::SizeType newSize; - for (unsigned int i=0 ; i GetLargestPossibleRegion().GetSize()[i]; - - // Resample to match the extent of the input - typename itk::VectorResampleImageFilter::Pointer - resampler =itk::VectorResampleImageFilter::New(); - resampler->SetInput(deformationField); - resampler->SetOutputSpacing(input->GetSpacing()); - resampler->SetSize(newSize); - resampler->SetOutputOrigin(input->GetOrigin()); - resampler->SetInterpolator(genericInterpolator->GetInterpolatorPointer()); - - // Update - if (m_Verbose) std::cout<< "Resampling the VF..." <Update(); - } - catch( itk::ExceptionObject & excp ) { - std::cerr << "Problem resampling the input vector field file" << std::endl; - std::cerr << excp << std::endl; - return; - } - deformationField= resampler->GetOutput(); - } - - - // ------------------------------------------- - // Forward Warp - // ------------------------------------------- - typename itk::ImageToImageFilter::Pointer warpFilter; - if (m_ArgsInfo.forward_flag) - { - //Forward warping: always linear - typedef clitk::ForwardWarpImageFilter ForwardWarpFilterType; - typename ForwardWarpFilterType::Pointer forwardWarpFilter= ForwardWarpFilterType::New(); - forwardWarpFilter->SetDeformationField( deformationField ); - forwardWarpFilter->SetEdgePaddingValue( static_cast(m_ArgsInfo.pad_arg) ); - warpFilter=forwardWarpFilter; - } - - // ------------------------------------------- - // Backward Warp - // ------------------------------------------- - else - { - // Get the interpolator - typedef clitk::GenericInterpolator GenericInterpolatorType; - typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); - genericInterpolator->SetArgsInfo(m_ArgsInfo); - - //Backward mapping - typedef itk::WarpImageFilter BackwardWarpFilterType; - typename BackwardWarpFilterType::Pointer backwardWarpFilter= BackwardWarpFilterType::New(); - backwardWarpFilter->SetDeformationField( deformationField ); - backwardWarpFilter->SetEdgePaddingValue( static_cast(m_ArgsInfo.pad_arg) ); - backwardWarpFilter->SetOutputSpacing( deformationField->GetSpacing() ); - backwardWarpFilter->SetOutputOrigin( input->GetOrigin() ); - backwardWarpFilter->SetOutputSize( deformationField->GetLargestPossibleRegion().GetSize() ); - typename itk::VectorResampleImageFilter::Pointer - resampler =itk::VectorResampleImageFilter::New(); - backwardWarpFilter->SetInterpolator(genericInterpolator->GetInterpolatorPointer()); - warpFilter=backwardWarpFilter; - } - - - // ------------------------------------------- + + // Resample to match the extent of the input + typename itk::VectorResampleImageFilter::Pointer + resampler =itk::VectorResampleImageFilter::New(); + resampler->SetInput(deformationField); + resampler->SetOutputSpacing(deformationField->GetSpacing()); + resampler->SetSize(newSize); + resampler->SetOutputOrigin(input->GetOrigin()); + resampler->SetInterpolator(genericInterpolator->GetInterpolatorPointer()); + // Update - // ------------------------------------------- - warpFilter->SetInput(input); - if (m_Verbose) std::cout<< "Warping the input..." <Update(); + resampler->Update(); + } catch( itk::ExceptionObject & excp ) { + std::cerr << "Problem resampling the input vector field file" << std::endl; + std::cerr << excp << std::endl; + return; } - catch( itk::ExceptionObject & excp ) { - std::cerr << "Problem warping the input image" << std::endl; + deformationField= resampler->GetOutput(); + + } + + // ------------------------------------------- + // Spacing like input + // ------------------------------------------- + else { + // Get size + typename DeformationFieldType::SizeType newSize; + for (unsigned int i=0 ; i GetLargestPossibleRegion().GetSize()[i]; + + // Resample to match the extent of the input + typename itk::VectorResampleImageFilter::Pointer + resampler =itk::VectorResampleImageFilter::New(); + resampler->SetInput(deformationField); + resampler->SetOutputSpacing(input->GetSpacing()); + resampler->SetSize(newSize); + resampler->SetOutputOrigin(input->GetOrigin()); + resampler->SetInterpolator(genericInterpolator->GetInterpolatorPointer()); + + // Update + if (m_Verbose) std::cout<< "Resampling the VF..." <Update(); + } catch( itk::ExceptionObject & excp ) { + std::cerr << "Problem resampling the input vector field file" << std::endl; std::cerr << excp << std::endl; return; - } - + } + deformationField= resampler->GetOutput(); + } - // Output - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_ArgsInfo.output_arg); - writer->SetInput(warpFilter->GetOutput()); - writer->Update(); + // ------------------------------------------- + // Forward Warp + // ------------------------------------------- + typename itk::ImageToImageFilter::Pointer warpFilter; + if (m_ArgsInfo.forward_flag) { + //Forward warping: always linear + typedef clitk::ForwardWarpImageFilter ForwardWarpFilterType; + typename ForwardWarpFilterType::Pointer forwardWarpFilter= ForwardWarpFilterType::New(); + forwardWarpFilter->SetDeformationField( deformationField ); + forwardWarpFilter->SetEdgePaddingValue( static_cast(m_ArgsInfo.pad_arg) ); + warpFilter=forwardWarpFilter; } + // ------------------------------------------- + // Backward Warp + // ------------------------------------------- + else { + // Get the interpolator + typedef clitk::GenericInterpolator GenericInterpolatorType; + typename GenericInterpolatorType::Pointer genericInterpolator=GenericInterpolatorType::New(); + genericInterpolator->SetArgsInfo(m_ArgsInfo); + + //Backward mapping + typedef itk::WarpImageFilter BackwardWarpFilterType; + typename BackwardWarpFilterType::Pointer backwardWarpFilter= BackwardWarpFilterType::New(); + backwardWarpFilter->SetDeformationField( deformationField ); + backwardWarpFilter->SetEdgePaddingValue( static_cast(m_ArgsInfo.pad_arg) ); + backwardWarpFilter->SetOutputSpacing( deformationField->GetSpacing() ); + backwardWarpFilter->SetOutputOrigin( input->GetOrigin() ); + backwardWarpFilter->SetOutputSize( deformationField->GetLargestPossibleRegion().GetSize() ); + typename itk::VectorResampleImageFilter::Pointer + resampler =itk::VectorResampleImageFilter::New(); + backwardWarpFilter->SetInterpolator(genericInterpolator->GetInterpolatorPointer()); + warpFilter=backwardWarpFilter; + } + + + // ------------------------------------------- + // Update + // ------------------------------------------- + warpFilter->SetInput(input); + if (m_Verbose) std::cout<< "Warping the input..." <Update(); + } catch( itk::ExceptionObject & excp ) { + std::cerr << "Problem warping the input image" << std::endl; + std::cerr << excp << std::endl; + return; + } + + + // Output + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_ArgsInfo.output_arg); + writer->SetInput(warpFilter->GetOutput()); + writer->Update(); + +} + }//end clitk - + #endif //#define clitkWarpImageGenericFilter_txx diff --git a/tools/clitkWriteDicomSeries.cxx b/tools/clitkWriteDicomSeries.cxx index a54d1ad..607b13b 100644 --- a/tools/clitkWriteDicomSeries.cxx +++ b/tools/clitkWriteDicomSeries.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,9 +20,9 @@ * @file clitkWriteDicomSeries.cxx * @author Jef Vandemeulebroucke * @date 4th of August - * + * * @brief Write a volume into a series with the header of another series - * + * ===================================================*/ @@ -33,7 +33,8 @@ //-------------------------------------------------------------------- -int main(int argc, char * argv[]) { +int main(int argc, char * argv[]) +{ // Init command line GGO(clitkWriteDicomSeries, args_info); @@ -42,7 +43,7 @@ int main(int argc, char * argv[]) { // Filter typedef clitk::WriteDicomSeriesGenericFilter FilterType; FilterType::Pointer genericFilter = FilterType::New(); - + genericFilter->SetArgsInfo(args_info); genericFilter->Update(); diff --git a/tools/clitkWriteDicomSeriesGenericFilter.cxx b/tools/clitkWriteDicomSeriesGenericFilter.cxx index 2ee1d99..f3a6b02 100644 --- a/tools/clitkWriteDicomSeriesGenericFilter.cxx +++ b/tools/clitkWriteDicomSeriesGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkWriteDicomSeriesGenericFilter.cxx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ #include "clitkWriteDicomSeriesGenericFilter.h" diff --git a/tools/clitkWriteDicomSeriesGenericFilter.txx b/tools/clitkWriteDicomSeriesGenericFilter.txx index 21612e4..113eaab 100644 --- a/tools/clitkWriteDicomSeriesGenericFilter.txx +++ b/tools/clitkWriteDicomSeriesGenericFilter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,11 +20,11 @@ /* ================================================= * @file clitkWriteDicomSeriesGenericFilter.txx - * @author - * @date - * - * @brief - * + * @author + * @date + * + * @brief + * ===================================================*/ @@ -32,179 +32,169 @@ namespace clitk { - //----------------------------------------------------------- - // Constructor - //----------------------------------------------------------- - template - WriteDicomSeriesGenericFilter::WriteDicomSeriesGenericFilter() - { - m_Verbose=false; - m_InputFileName=""; +//----------------------------------------------------------- +// Constructor +//----------------------------------------------------------- +template +WriteDicomSeriesGenericFilter::WriteDicomSeriesGenericFilter() +{ + m_Verbose=false; + m_InputFileName=""; +} + + +//----------------------------------------------------------- +// Update +//----------------------------------------------------------- +template +void WriteDicomSeriesGenericFilter::Update() +{ + // Read the Dimension and PixelType + int Dimension; + std::string PixelType; + ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType); + + + // Call UpdateWithDim + if(Dimension==2) UpdateWithDim<2>(PixelType); + else if(Dimension==3) UpdateWithDim<3>(PixelType); + // else if (Dimension==4)UpdateWithDim<4>(PixelType); + else { + std::cout<<"Error, Only for 2 or 3 Dimensions!!!"< +template +void +WriteDicomSeriesGenericFilter::UpdateWithDim(std::string PixelType) +{ + if (m_Verbose) std::cout << "Image was detected to be "<(); + } + // else if(PixelType == "unsigned_short"){ + // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; + // UpdateWithDimAndPixelType(); + // } + + else if (PixelType == "unsigned_char") { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; + UpdateWithDimAndPixelType(); + } - //----------------------------------------------------------- - // Update - //----------------------------------------------------------- - template - void WriteDicomSeriesGenericFilter::Update() - { - // Read the Dimension and PixelType - int Dimension; - std::string PixelType; - ReadImageDimensionAndPixelType(m_InputFileName, Dimension, PixelType); - - - // Call UpdateWithDim - if(Dimension==2) UpdateWithDim<2>(PixelType); - else if(Dimension==3) UpdateWithDim<3>(PixelType); - // else if (Dimension==4)UpdateWithDim<4>(PixelType); - else - { - std::cout<<"Error, Only for 2 or 3 Dimensions!!!"<(); + // } + else { + if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; + UpdateWithDimAndPixelType(); } +} - //------------------------------------------------------------------- - // Update with the number of dimensions - //------------------------------------------------------------------- - template - template - void - WriteDicomSeriesGenericFilter::UpdateWithDim(std::string PixelType) - { - if (m_Verbose) std::cout << "Image was detected to be "<(); - } - // else if(PixelType == "unsigned_short"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_short..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - - else if (PixelType == "unsigned_char"){ - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and unsigned_char..." << std::endl; - UpdateWithDimAndPixelType(); - } - - // else if (PixelType == "char"){ - // if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and signed_char..." << std::endl; - // UpdateWithDimAndPixelType(); - // } - else { - if (m_Verbose) std::cout << "Launching filter in "<< Dimension <<"D and float..." << std::endl; - UpdateWithDimAndPixelType(); + +//------------------------------------------------------------------- +// Update with the number of dimensions and the pixeltype +//------------------------------------------------------------------- +template +template +void +WriteDicomSeriesGenericFilter::UpdateWithDimAndPixelType() +{ + + // ImageTypes + typedef itk::Image InputImageType; + typedef itk::Image OutputImageType; + + // Read the input (volumetric) + typedef itk::ImageFileReader InputReaderType; + typename InputReaderType::Pointer volumeReader = InputReaderType::New(); + volumeReader->SetFileName( m_InputFileName); + volumeReader->Update(); + typename InputImageType::Pointer input= volumeReader->GetOutput(); + + // Read the dicom directory + typedef itk::ImageSeriesReader< InputImageType > ReaderType; + typedef itk::GDCMImageIO ImageIOType; + typedef itk::GDCMSeriesFileNames NamesGeneratorType; + + ImageIOType::Pointer gdcmIO = ImageIOType::New(); + NamesGeneratorType::Pointer namesGenerator = NamesGeneratorType::New(); + namesGenerator->SetInputDirectory( m_ArgsInfo.inputDir_arg ); + typename ReaderType::FileNamesContainer filenames = namesGenerator->GetInputFileNames(); + + // Output the dicom files + unsigned int numberOfFilenames = filenames.size(); + if (m_Verbose) { + std::cout << numberOfFilenames <<" were read in the directory "< - template - void - WriteDicomSeriesGenericFilter::UpdateWithDimAndPixelType() - { - - // ImageTypes - typedef itk::Image InputImageType; - typedef itk::Image OutputImageType; - - // Read the input (volumetric) - typedef itk::ImageFileReader InputReaderType; - typename InputReaderType::Pointer volumeReader = InputReaderType::New(); - volumeReader->SetFileName( m_InputFileName); - volumeReader->Update(); - typename InputImageType::Pointer input= volumeReader->GetOutput(); - - // Read the dicom directory - typedef itk::ImageSeriesReader< InputImageType > ReaderType; - typedef itk::GDCMImageIO ImageIOType; - typedef itk::GDCMSeriesFileNames NamesGeneratorType; - - ImageIOType::Pointer gdcmIO = ImageIOType::New(); - NamesGeneratorType::Pointer namesGenerator = NamesGeneratorType::New(); - namesGenerator->SetInputDirectory( m_ArgsInfo.inputDir_arg ); - typename ReaderType::FileNamesContainer filenames = namesGenerator->GetInputFileNames(); - - // Output the dicom files - unsigned int numberOfFilenames = filenames.size(); - if (m_Verbose) - { - std::cout << numberOfFilenames <<" were read in the directory "<* dictionary = reader->GetMetaDataDictionaryArray(); - - // Get keys - unsigned int numberOfKeysGiven=0; - if(m_ArgsInfo.midP_flag && m_ArgsInfo.key_given) - std::cerr<<"Error: both keys and midP option are given"<( *((*dictionary)[fni]), entryId, value ); - } - - // Output directory and filenames - itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist - typedef itk::ImageSeriesWriter SeriesWriterType; - typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New(); - - seriesWriter->SetInput( volumeReader->GetOutput() ); - seriesWriter->SetImageIO( gdcmIO ); - namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg ); - seriesWriter->SetFileNames( namesGenerator->GetOutputFileNames() ); - //seriesWriter->SetMetaDataDictionaryArray( dictionary ); - seriesWriter->SetMetaDataDictionaryArray( dictionary ); - - // Write - try - { - seriesWriter->Update(); - } - catch( itk::ExceptionObject & excp ) - { - std::cerr << "Error: Exception thrown while writing the series!!" << std::endl; - std::cerr << excp << std::endl; - } + // Modify the meta dictionary + typedef itk::MetaDataDictionary DictionaryType; + const std::vector* dictionary = reader->GetMetaDataDictionaryArray(); + + // Get keys + unsigned int numberOfKeysGiven=0; + if(m_ArgsInfo.midP_flag && m_ArgsInfo.key_given) + std::cerr<<"Error: both keys and midP option are given"<( *((*dictionary)[fni]), entryId, value ); + } + // Output directory and filenames + itksys::SystemTools::MakeDirectory( m_ArgsInfo.outputDir_arg ); // create if it doesn't exist + typedef itk::ImageSeriesWriter SeriesWriterType; + typename SeriesWriterType::Pointer seriesWriter = SeriesWriterType::New(); + + seriesWriter->SetInput( volumeReader->GetOutput() ); + seriesWriter->SetImageIO( gdcmIO ); + namesGenerator->SetOutputDirectory( m_ArgsInfo.outputDir_arg ); + seriesWriter->SetFileNames( namesGenerator->GetOutputFileNames() ); + //seriesWriter->SetMetaDataDictionaryArray( dictionary ); + seriesWriter->SetMetaDataDictionaryArray( dictionary ); + + // Write + try { + seriesWriter->Update(); + } catch( itk::ExceptionObject & excp ) { + std::cerr << "Error: Exception thrown while writing the series!!" << std::endl; + std::cerr << excp << std::endl; } +} + }//end clitk - + #endif //#define clitkWriteDicomSeriesGenericFilter_txx diff --git a/tools/clitkZeroVF.cxx b/tools/clitkZeroVF.cxx index 9901321..65f46c4 100644 --- a/tools/clitkZeroVF.cxx +++ b/tools/clitkZeroVF.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,9 +22,9 @@ * @file clitkZeroVF.cxx * @author Joel Schaerer * @date July 20 10:14:53 2007 - * + * * @brief Creates a VF filled with zeros the size of the input VF - * + * */ // clitk include @@ -35,11 +35,11 @@ int main( int argc, char *argv[] ) { - + // Init command line GGO(clitkZeroVF, args_info); CLITK_INIT; - + //Creation of the generic filter clitk::ZeroVFGenericFilter::Pointer zeroVFGenericFilter= clitk::ZeroVFGenericFilter::New(); @@ -49,7 +49,7 @@ int main( int argc, char *argv[] ) zeroVFGenericFilter->SetVerbose(args_info.verbose_flag); //update - zeroVFGenericFilter->Update(); + zeroVFGenericFilter->Update(); return EXIT_SUCCESS; } #endif diff --git a/tools/clitkZeroVFGenericFilter.cxx b/tools/clitkZeroVFGenericFilter.cxx index 2444a94..4da1026 100644 --- a/tools/clitkZeroVFGenericFilter.cxx +++ b/tools/clitkZeroVFGenericFilter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,31 +20,31 @@ #include "clitkZeroVFGenericFilter.h" -namespace clitk { - - clitk::ZeroVFGenericFilter::ZeroVFGenericFilter() - { - m_Verbose=false; - } +namespace clitk +{ +clitk::ZeroVFGenericFilter::ZeroVFGenericFilter() +{ + m_Verbose=false; +} - void clitk::ZeroVFGenericFilter::Update() - { - //Get the image Dimension and PixelType - int Dimension; - std::string PixelType; - clitk::ReadImageDimensionAndPixelType(m_InputName, Dimension, PixelType); +void clitk::ZeroVFGenericFilter::Update() +{ + //Get the image Dimension and PixelType + int Dimension; + std::string PixelType; - if(Dimension==2) UpdateWithDim<2>(PixelType); - else if(Dimension==3) UpdateWithDim<3>(PixelType); - else - { - std::cout<<"Error, Only for 2 and 3 Dimensions!!!"<(PixelType); + else if(Dimension==3) UpdateWithDim<3>(PixelType); + else { + std::cout<<"Error, Only for 2 and 3 Dimensions!!!"< - void ZeroVFGenericFilter::UpdateWithDim(std::string PixelType) - { - if (PixelType=="double") - { - UpdateWithDimAndPixelType(); - } - else - { - UpdateWithDimAndPixelType(); - } +template +void ZeroVFGenericFilter::UpdateWithDim(std::string PixelType) +{ + if (PixelType=="double") { + UpdateWithDimAndPixelType(); + } else { + UpdateWithDimAndPixelType(); } +} + +template +void ZeroVFGenericFilter::UpdateWithDimAndPixelType() +{ + //Define the image type + typedef itk::Vector DisplacementType; + typedef itk::Image ImageType; - template - void ZeroVFGenericFilter::UpdateWithDimAndPixelType() - { - //Define the image type - typedef itk::Vector DisplacementType; - typedef itk::Image ImageType; + //Read the image + typedef itk::ImageFileReader ImageReaderType; + typename ImageReaderType::Pointer reader= ImageReaderType::New(); + reader->SetFileName(m_InputName); + reader->Update(); // not very efficient :-p + typename ImageType::Pointer image =reader->GetOutput(); + DisplacementType zero; + zero.Fill(0); + image->FillBuffer(zero); - //Read the image - typedef itk::ImageFileReader ImageReaderType; - typename ImageReaderType::Pointer reader= ImageReaderType::New(); - reader->SetFileName(m_InputName); - reader->Update(); // not very efficient :-p - typename ImageType::Pointer image =reader->GetOutput(); - DisplacementType zero; - zero.Fill(0); - image->FillBuffer(zero); - - //Write the output - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(m_OutputName); - writer->SetInput(image); - writer->Update(); - } + //Write the output + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(m_OutputName); + writer->SetInput(image); + writer->Update(); +} } diff --git a/vv/QTreePushButton.cxx b/vv/QTreePushButton.cxx index 88d5cd7..a373ccb 100644 --- a/vv/QTreePushButton.cxx +++ b/vv/QTreePushButton.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -19,14 +19,14 @@ QTreePushButton::QTreePushButton():QPushButton() { - m_item = NULL; - m_index = 0; - m_column = 0; - connect(this,SIGNAL(clicked()),this, SLOT(clickedIntoATree())); + m_item = NULL; + m_index = 0; + m_column = 0; + connect(this,SIGNAL(clicked()),this, SLOT(clickedIntoATree())); } void QTreePushButton::clickedIntoATree() { - emit clickedInto(m_item,m_column); - emit clickedInto(m_index,m_column); + emit clickedInto(m_item,m_column); + emit clickedInto(m_index,m_column); } diff --git a/vv/vtkVOXImageWriter.cxx b/vv/vtkVOXImageWriter.cxx index 4b9adb6..97c2944 100644 --- a/vv/vtkVOXImageWriter.cxx +++ b/vv/vtkVOXImageWriter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -40,135 +40,130 @@ vtkStandardNewMacro(vtkVOXImageWriter); //---------------------------------------------------------------------------- vtkVOXImageWriter::vtkVOXImageWriter() { - this->FileName = 0; - this->FileLowerLeft = 1; + this->FileName = 0; + this->FileLowerLeft = 1; } //---------------------------------------------------------------------------- vtkVOXImageWriter::~vtkVOXImageWriter() { - this->SetFileName(0); + this->SetFileName(0); } //---------------------------------------------------------------------------- void vtkVOXImageWriter::Write( ) { - this->SetErrorCode(vtkErrorCode::NoError); - - this->GetInput()->UpdateInformation(); - - // Error checking - if (this->GetInput() == NULL ) - { - vtkErrorMacro(<<"Write:Please specify an input!"); - return; + this->SetErrorCode(vtkErrorCode::NoError); + + this->GetInput()->UpdateInformation(); + + // Error checking + if (this->GetInput() == NULL ) { + vtkErrorMacro(<<"Write:Please specify an input!"); + return; + } + + if ( this->FileName == 0) { + vtkErrorMacro("Output file name not specified"); + return; + } + + int nDims = 3; + int * ext = this->GetInput()->GetWholeExtent(); + if ( ext[4] == ext[5] ) { + nDims = 2; + if ( ext[2] == ext[3] ) { + nDims = 1; } - - if ( this->FileName == 0) - { - vtkErrorMacro("Output file name not specified"); - return; - } - - int nDims = 3; - int * ext = this->GetInput()->GetWholeExtent(); - if ( ext[4] == ext[5] ) - { - nDims = 2; - if ( ext[2] == ext[3] ) - { - nDims = 1; - } - } - - double * origin = this->GetInput()->GetOrigin(); - double * spacingDouble = this->GetInput()->GetSpacing(); - - float spacing[3]; - spacing[0] = spacingDouble[0]; - spacing[1] = spacingDouble[1]; - spacing[2] = spacingDouble[2]; - - int dimSize[3]; - dimSize[0] = ext[1]-ext[0]+1; - dimSize[1] = ext[3]-ext[2]+1; - dimSize[2] = ext[5]-ext[4]+1; - - std::string elementType; - - int scalarType = this->GetInput()->GetScalarType(); - switch ( scalarType ) - { - case VTK_CHAR: - elementType = "schar"; - break; - case VTK_UNSIGNED_CHAR: - elementType = "uchar"; - break; - case VTK_SHORT: - elementType = "sshort"; - break; - case VTK_UNSIGNED_SHORT: - elementType = "ushort"; - break; - case VTK_INT: - elementType = "int"; - break; - case VTK_UNSIGNED_INT: - elementType = "uint"; - break; - case VTK_LONG: - elementType = "slong"; - break; - case VTK_UNSIGNED_LONG: - elementType = "ulong"; - break; - case VTK_FLOAT: - elementType = "float"; - break; - case VTK_DOUBLE: - elementType = "double"; - break; - default: - vtkErrorMacro("Unknown scalar type." ); - return ; - } - - origin[0] += ext[0] * spacing[0]; - origin[1] += ext[2] * spacing[1]; - origin[2] += ext[4] * spacing[2]; - - this->GetInput()->SetUpdateExtent(ext[0], ext[1], - ext[2], ext[3], - ext[4], ext[5]); - this->GetInput()->UpdateData(); - - - this->SetFileDimensionality(nDims); - - this->InvokeEvent(vtkCommand::StartEvent); - this->UpdateProgress(0.0); - //write here - std::cout << "Writing to file " << this->GetFileName() << " ..." << std::endl; - std::cout.flush(); - fstream out(this->GetFileName(),ios::out|ios::binary); - out << "VOX v2\n# Size\n" << dimSize[0] << " " << dimSize[1] << " " - << dimSize[2] << std::endl << "# Spacing" << std::endl - << spacing[0] << " " << spacing[1] << " " << spacing[2] << std::endl - << "# Image dim" << std::endl << nDims << std::endl - << "# Image type" << std::endl << elementType << std::endl; - out.write((char*)this->GetInput()->GetScalarPointer(), - dimSize[0]*dimSize[1]*dimSize[2]*this->GetInput()->GetScalarSize()); - out.close(); - - this->UpdateProgress(1.0); - this->InvokeEvent(vtkCommand::EndEvent); + } + + double * origin = this->GetInput()->GetOrigin(); + double * spacingDouble = this->GetInput()->GetSpacing(); + + float spacing[3]; + spacing[0] = spacingDouble[0]; + spacing[1] = spacingDouble[1]; + spacing[2] = spacingDouble[2]; + + int dimSize[3]; + dimSize[0] = ext[1]-ext[0]+1; + dimSize[1] = ext[3]-ext[2]+1; + dimSize[2] = ext[5]-ext[4]+1; + + std::string elementType; + + int scalarType = this->GetInput()->GetScalarType(); + switch ( scalarType ) { + case VTK_CHAR: + elementType = "schar"; + break; + case VTK_UNSIGNED_CHAR: + elementType = "uchar"; + break; + case VTK_SHORT: + elementType = "sshort"; + break; + case VTK_UNSIGNED_SHORT: + elementType = "ushort"; + break; + case VTK_INT: + elementType = "int"; + break; + case VTK_UNSIGNED_INT: + elementType = "uint"; + break; + case VTK_LONG: + elementType = "slong"; + break; + case VTK_UNSIGNED_LONG: + elementType = "ulong"; + break; + case VTK_FLOAT: + elementType = "float"; + break; + case VTK_DOUBLE: + elementType = "double"; + break; + default: + vtkErrorMacro("Unknown scalar type." ); + return ; + } + + origin[0] += ext[0] * spacing[0]; + origin[1] += ext[2] * spacing[1]; + origin[2] += ext[4] * spacing[2]; + + this->GetInput()->SetUpdateExtent(ext[0], ext[1], + ext[2], ext[3], + ext[4], ext[5]); + this->GetInput()->UpdateData(); + + + this->SetFileDimensionality(nDims); + + this->InvokeEvent(vtkCommand::StartEvent); + this->UpdateProgress(0.0); + //write here + std::cout << "Writing to file " << this->GetFileName() << " ..." << std::endl; + std::cout.flush(); + fstream out(this->GetFileName(),ios::out|ios::binary); + out << "VOX v2\n# Size\n" << dimSize[0] << " " << dimSize[1] << " " + << dimSize[2] << std::endl << "# Spacing" << std::endl + << spacing[0] << " " << spacing[1] << " " << spacing[2] << std::endl + << "# Image dim" << std::endl << nDims << std::endl + << "# Image type" << std::endl << elementType << std::endl; + out.write((char*)this->GetInput()->GetScalarPointer(), + dimSize[0]*dimSize[1]*dimSize[2]*this->GetInput()->GetScalarSize()); + out.close(); + + this->UpdateProgress(1.0); + this->InvokeEvent(vtkCommand::EndEvent); } //---------------------------------------------------------------------------- void vtkVOXImageWriter::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); - os << indent << "FileName: " << (this->FileName==0?this->FileName:"(none)") << endl; + this->Superclass::PrintSelf(os,indent); + os << indent << "FileName: " << (this->FileName==0?this->FileName:"(none)") << endl; } diff --git a/vv/vv.cxx b/vv/vv.cxx index 7d40972..141b915 100644 --- a/vv/vv.cxx +++ b/vv/vv.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,65 +31,59 @@ int main( int argc, char** argv ) { #ifdef _WIN32 - HWND hWnd = GetConsoleWindow(); - ShowWindow( hWnd, SW_HIDE ); + HWND hWnd = GetConsoleWindow(); + ShowWindow( hWnd, SW_HIDE ); #endif - CLITK_INIT; + CLITK_INIT; - QApplication app( argc, argv ); - Q_INIT_RESOURCE(vvIcons); - //QPixmap pixmap(":/splashscreen.PNG"); - QSplashScreen *splash = new QSplashScreen(QPixmap(QString::fromUtf8(":/new/prefix1/splashscreen.PNG"))); - /*splash->showMessage("VV 1.0 developped by Léon Bérard c`ancer center http://oncora1.lyon.fnclcc.fr and CREATIS-LRMN http://www.creatis.insa-lyon.fr",(Qt::AlignRight | Qt::AlignBottom));*/ - // splash->show(); - QTimer::singleShot(2000, splash, SLOT(close())); - while (!splash->isHidden()) - app.processEvents(); + QApplication app( argc, argv ); + Q_INIT_RESOURCE(vvIcons); + //QPixmap pixmap(":/splashscreen.PNG"); + QSplashScreen *splash = new QSplashScreen(QPixmap(QString::fromUtf8(":/new/prefix1/splashscreen.PNG"))); + /*splash->showMessage("VV 1.0 developped by Léon Bérard c`ancer center http://oncora1.lyon.fnclcc.fr and CREATIS-LRMN http://www.creatis.insa-lyon.fr",(Qt::AlignRight | Qt::AlignBottom));*/ + // splash->show(); + QTimer::singleShot(2000, splash, SLOT(close())); + while (!splash->isHidden()) + app.processEvents(); - vvMainWindow window; + vvMainWindow window; - //Try to give the window a sensible default size - int width=QApplication::desktop()->width()*0.8; - int height=QApplication::desktop()->height()*0.9; - if (width> 1.5*height) - width=1.5*height; - window.resize(width,height); + //Try to give the window a sensible default size + int width=QApplication::desktop()->width()*0.8; + int height=QApplication::desktop()->height()*0.9; + if (width> 1.5*height) + width=1.5*height; + window.resize(width,height); - window.show(); + window.show(); - std::vector filenames; - std::vector > overlays; - std::vector > vector_fields; - if (argc >1) - { - for (int i = 1; i < argc; i++) - { - std::string temp = argv[i]; - if (temp=="--vf") - { - assert(filenames.size()>=1); - vector_fields.push_back(std::make_pair(filenames.size()-1,argv[i+1])); - i++; //skip vf name - } - else if (temp=="--overlay") - { - assert(filenames.size()>=1); - overlays.push_back(std::make_pair(filenames.size()-1,argv[i+1])); - i++; //skip overlay name - } - else - filenames.push_back(temp); - } - window.LoadImages(filenames,IMAGE); - for (std::vector >::iterator i=overlays.begin(); - i!=overlays.end();i++) - window.AddOverlayImage((*i).first,(*i).second.c_str()); - for (std::vector >::iterator i=vector_fields.begin(); - i!=vector_fields.end();i++) - window.AddField((*i).second.c_str(), (*i).first); - + std::vector filenames; + std::vector > overlays; + std::vector > vector_fields; + if (argc >1) { + for (int i = 1; i < argc; i++) { + std::string temp = argv[i]; + if (temp=="--vf") { + assert(filenames.size()>=1); + vector_fields.push_back(std::make_pair(filenames.size()-1,argv[i+1])); + i++; //skip vf name + } else if (temp=="--overlay") { + assert(filenames.size()>=1); + overlays.push_back(std::make_pair(filenames.size()-1,argv[i+1])); + i++; //skip overlay name + } else + filenames.push_back(temp); } + window.LoadImages(filenames,IMAGE); + for (std::vector >::iterator i=overlays.begin(); + i!=overlays.end(); i++) + window.AddOverlayImage((*i).first,(*i).second.c_str()); + for (std::vector >::iterator i=vector_fields.begin(); + i!=vector_fields.end(); i++) + window.AddField((*i).second.c_str(), (*i).first); - return app.exec(); + } + + return app.exec(); } diff --git a/vv/vvBinaryImageOverlayActor.cxx b/vv/vvBinaryImageOverlayActor.cxx index 7d6d26c..0405cdb 100644 --- a/vv/vvBinaryImageOverlayActor.cxx +++ b/vv/vvBinaryImageOverlayActor.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -30,7 +30,8 @@ #include //------------------------------------------------------------------------------ -vvBinaryImageOverlayActor::vvBinaryImageOverlayActor() { +vvBinaryImageOverlayActor::vvBinaryImageOverlayActor() +{ mTSlice = -1; mSlice = 0; mColor.resize(3); @@ -43,7 +44,8 @@ vvBinaryImageOverlayActor::vvBinaryImageOverlayActor() { //------------------------------------------------------------------------------ -vvBinaryImageOverlayActor::~vvBinaryImageOverlayActor() { +vvBinaryImageOverlayActor::~vvBinaryImageOverlayActor() +{ for (unsigned int i = 0; i < mSlicer->GetImage()->GetVTKImages().size(); i++) { mSlicer->GetRenderer()->RemoveActor(mImageActorList[i]); } @@ -54,7 +56,8 @@ vvBinaryImageOverlayActor::~vvBinaryImageOverlayActor() { //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::SetColor(double r, double g, double b) { +void vvBinaryImageOverlayActor::SetColor(double r, double g, double b) +{ mColor[0] = r; mColor[1] = g; mColor[2] = b; @@ -63,26 +66,28 @@ void vvBinaryImageOverlayActor::SetColor(double r, double g, double b) { //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::SetSlicer(vvSlicer * slicer) { +void vvBinaryImageOverlayActor::SetSlicer(vvSlicer * slicer) +{ mSlicer = slicer; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::Initialize() { +void vvBinaryImageOverlayActor::Initialize() +{ if (!mSlicer) { std::cerr << "ERROR. Please use setSlicer before setSlicer in vvBinaryImageOverlayActor." << std::endl; exit(0); } - + if (!mImage) { std::cerr << "ERROR. Please use setImage before setSlicer in vvBinaryImageOverlayActor." << std::endl; exit(0); } // Create an actor for each time slice for (unsigned int numImage = 0; numImage < mSlicer->GetImage()->GetVTKImages().size(); numImage++) { - // how many intensity ? + // how many intensity ? vtkImageMapToRGBA * mOverlayMapper = vtkImageMapToRGBA::New(); mOverlayMapper->SetInput(mImage->GetVTKImages()[0]); // DS TODO : to change if it is 4D !!! mColorLUT->SetRange(0,1); @@ -90,7 +95,7 @@ void vvBinaryImageOverlayActor::Initialize() { mColorLUT->SetTableValue(mBackgroundValue, 0, 0, 0, 0.0); // BG mColorLUT->SetTableValue(1, mColor[0], mColor[1], mColor[2], mAlpha); // FG mOverlayMapper->SetLookupTable(mColorLUT); - + vtkImageActor * mOverlayActor = vtkImageActor::New(); mOverlayActor->SetInput(mOverlayMapper->GetOutput()); mOverlayActor->SetPickable(0); @@ -99,14 +104,15 @@ void vvBinaryImageOverlayActor::Initialize() { mMapperList.push_back(mOverlayMapper); mImageActorList.push_back(mOverlayActor); - mSlicer->GetRenderer()->AddActor(mOverlayActor); + mSlicer->GetRenderer()->AddActor(mOverlayActor); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::SetOpacity(double d) { +void vvBinaryImageOverlayActor::SetOpacity(double d) +{ mAlpha = d; } //------------------------------------------------------------------------------ @@ -117,10 +123,10 @@ void vvBinaryImageOverlayActor::SetOpacity(double d) { // mAlpha = d; // mColorLUT->SetTableValue(1, mColor[0], mColor[1], mColor[2], mAlpha); // FG // for (unsigned int numImage = 0; numImage < mSlicer->GetImage()->GetVTKImages().size(); numImage++) { -// // how many intensity ? +// // how many intensity ? // vtkImageMapToRGBA * mOverlayMapper = mMapperList[numImage]; // mOverlayMapper->SetLookupTable(mColorLUT); - + // vtkImageActor * mOverlayActor = mImageActorList[numImage]; // mOverlayActor->SetInput(mOverlayMapper->GetOutput()); // } @@ -130,15 +136,15 @@ void vvBinaryImageOverlayActor::SetOpacity(double d) { //------------------------------------------------------------------------------ // void vvBinaryImageOverlayActor::SetColor(double r, double v, double b) { -// mColor[0] = r; -// mColor[1] = v; -// mColor[2] = b; +// mColor[0] = r; +// mColor[1] = v; +// mColor[2] = b; // // mColorLUT->SetTableValue(1, mColor[0], mColor[1], mColor[2], mAlpha); // FG // // for (unsigned int numImage = 0; numImage < mSlicer->GetImage()->GetVTKImages().size(); numImage++) { -// // // how many intensity ? +// // // how many intensity ? // // vtkImageMapToRGBA * mOverlayMapper = mMapperList[numImage]; // // mOverlayMapper->SetLookupTable(mColorLUT); - + // // vtkImageActor * mOverlayActor = mImageActorList[numImage]; // // mOverlayActor->SetInput(mOverlayMapper->GetOutput()); // // } @@ -147,7 +153,8 @@ void vvBinaryImageOverlayActor::SetOpacity(double d) { //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::SetImage(vvImage::Pointer image, double bg) { +void vvBinaryImageOverlayActor::SetImage(vvImage::Pointer image, double bg) +{ mImage = image; mBackgroundValue = bg; } @@ -155,7 +162,8 @@ void vvBinaryImageOverlayActor::SetImage(vvImage::Pointer image, double bg) { //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::HideActors() { +void vvBinaryImageOverlayActor::HideActors() +{ if (!mSlicer) return; mSlice = mSlicer->GetSlice(); for(unsigned int i=0; iGetSlice(); mTSlice = mSlicer->GetTSlice(); @@ -179,15 +188,16 @@ void vvBinaryImageOverlayActor::ShowActors() { } //------------------------------------------------------------------------------ - + //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::UpdateColor() { +void vvBinaryImageOverlayActor::UpdateColor() +{ mColorLUT->SetTableValue(1, mColor[0], mColor[1], mColor[2], mAlpha); // FG for (unsigned int numImage = 0; numImage < mSlicer->GetImage()->GetVTKImages().size(); numImage++) { - // how many intensity ? + // how many intensity ? vtkImageMapToRGBA * mOverlayMapper = mMapperList[numImage]; mOverlayMapper->SetLookupTable(mColorLUT); - + vtkImageActor * mOverlayActor = mImageActorList[numImage]; mOverlayActor->SetInput(mOverlayMapper->GetOutput()); } @@ -195,7 +205,8 @@ void vvBinaryImageOverlayActor::UpdateColor() { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::UpdateSlice(int slicer, int slice) { +void vvBinaryImageOverlayActor::UpdateSlice(int slicer, int slice) +{ if (!mSlicer) return; if (mPreviousSlice == mSlicer->GetSlice()) { @@ -216,13 +227,13 @@ void vvBinaryImageOverlayActor::UpdateSlice(int slicer, int slice) { ComputeExtent(orientation, mSlice, imageExtent, maskExtent); //ComputeExtent(imageExtent, maskExtent, mSlicer->GetImage()->GetFirstVTKImageData(), mImage->GetFirstVTKImageData()); ComputeExtent(maskExtent, maskExtent, mSlicer->GetImage()->GetFirstVTKImageData(), mImage->GetFirstVTKImageData()); - // std::cout << "maskExtent = " << maskExtent[0] << " " << maskExtent[1] << " " << maskExtent[2] << " " + // std::cout << "maskExtent = " << maskExtent[0] << " " << maskExtent[1] << " " << maskExtent[2] << " " // << maskExtent[3] << " " << maskExtent[4] << " " << maskExtent[5] << std::endl; mSlicer->ClipDisplayedExtent(maskExtent, mMapperList[mTSlice]->GetInput()->GetWholeExtent()); - // std::cout << "maskExtent = " << maskExtent[0] << " " << maskExtent[1] << " " << maskExtent[2] << " " + // std::cout << "maskExtent = " << maskExtent[0] << " " << maskExtent[1] << " " << maskExtent[2] << " " // << maskExtent[3] << " " << maskExtent[4] << " " << maskExtent[5] << std::endl; SetDisplayExtentAndCameraPosition(orientation, mSlice, maskExtent, mImageActorList[mTSlice], 0.0); - + // set previous slice mPreviousTSlice = mSlicer->GetTSlice(); mPreviousSlice = mSlicer->GetSlice(); @@ -231,29 +242,30 @@ void vvBinaryImageOverlayActor::UpdateSlice(int slicer, int slice) { //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::ComputeExtent(int orientation, - int slice, - int * inExtent, - int * outExtent) { - // std::cout << "InExtent = " << inExtent[0] << " " << inExtent[1] << " " << inExtent[2] << " " +void vvBinaryImageOverlayActor::ComputeExtent(int orientation, + int slice, + int * inExtent, + int * outExtent) +{ + // std::cout << "InExtent = " << inExtent[0] << " " << inExtent[1] << " " << inExtent[2] << " " // << inExtent[3] << " " << inExtent[4] << " " << inExtent[5] << std::endl; // DD(orientation); switch (orientation) { case vtkImageViewer2::SLICE_ORIENTATION_XY: for(int i=0; i<4; i++) outExtent[i] = inExtent[i]; - outExtent[4] = outExtent[5] = slice; + outExtent[4] = outExtent[5] = slice; break; case vtkImageViewer2::SLICE_ORIENTATION_XZ: for(int i=0; i<2; i++) outExtent[i] = inExtent[i]; for(int i=4; i<6; i++) outExtent[i] = inExtent[i]; - outExtent[2] = outExtent[3] = slice; + outExtent[2] = outExtent[3] = slice; break; case vtkImageViewer2::SLICE_ORIENTATION_YZ: for(int i=2; i<6; i++) outExtent[i] = inExtent[i]; - outExtent[0] = outExtent[1] = slice; + outExtent[0] = outExtent[1] = slice; break; } - // std::cout << "OutExtent = " << outExtent[0] << " " << outExtent[1] << " " << outExtent[2] << " " + // std::cout << "OutExtent = " << outExtent[0] << " " << outExtent[1] << " " << outExtent[2] << " " // << outExtent[3] << " " << outExtent[4] << " " << outExtent[5] << std::endl; } //------------------------------------------------------------------------------ @@ -263,49 +275,50 @@ void vvBinaryImageOverlayActor::ComputeExtent(int orientation, void vvBinaryImageOverlayActor::ComputeExtent(int * inExtent, int * outExtent, vtkImageData * image, vtkImageData * overlay) { outExtent[0] = (( image->GetOrigin()[0] + inExtent[0]*image->GetSpacing()[0] ) - overlay->GetOrigin()[0]) / - overlay->GetSpacing()[0]; + overlay->GetSpacing()[0]; outExtent[1] = (( image->GetOrigin()[0] + inExtent[1]*image->GetSpacing()[0] ) - overlay->GetOrigin()[0]) / - overlay->GetSpacing()[0]; + overlay->GetSpacing()[0]; outExtent[2] = (( image->GetOrigin()[1] + inExtent[2]*image->GetSpacing()[1] ) - overlay->GetOrigin()[1]) / - overlay->GetSpacing()[1]; + overlay->GetSpacing()[1]; outExtent[3] = (( image->GetOrigin()[1] + inExtent[3]*image->GetSpacing()[1] ) - overlay->GetOrigin()[1]) / - overlay->GetSpacing()[1]; + overlay->GetSpacing()[1]; outExtent[4] = (( image->GetOrigin()[2] + inExtent[4]*image->GetSpacing()[2] ) - overlay->GetOrigin()[2]) / - overlay->GetSpacing()[2]; + overlay->GetSpacing()[2]; outExtent[5] = (( image->GetOrigin()[2] + inExtent[5]*image->GetSpacing()[2] ) - overlay->GetOrigin()[2]) / - overlay->GetSpacing()[2]; + overlay->GetSpacing()[2]; } //---------------------------------------------------------------------------- //------------------------------------------------------------------------------ -void vvBinaryImageOverlayActor::SetDisplayExtentAndCameraPosition(int orientation, - int slice, - int * extent, - vtkImageActor * actor, - double position) { +void vvBinaryImageOverlayActor::SetDisplayExtentAndCameraPosition(int orientation, + int slice, + int * extent, + vtkImageActor * actor, + double position) +{ actor->SetDisplayExtent(extent); - + // Set position if (orientation == vtkImageViewer2::SLICE_ORIENTATION_XY) { if (mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[2] > slice) actor->SetPosition(0,0, position); else - actor->SetPosition(0,0, -position); + actor->SetPosition(0,0, -position); } if (orientation == vtkImageViewer2::SLICE_ORIENTATION_XZ) { if (mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[1] > slice) actor->SetPosition(0,position,0); else - actor->SetPosition(0,-position,0); + actor->SetPosition(0,-position,0); } if (orientation == vtkImageViewer2::SLICE_ORIENTATION_YZ) { if (mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[0] > slice) actor->SetPosition(position,0, 0); else - actor->SetPosition(-position,0, 0); + actor->SetPosition(-position,0, 0); } - + } //------------------------------------------------------------------------------ diff --git a/vv/vvBlendImageActor.cxx b/vv/vvBlendImageActor.cxx index f28ba32..65a18ae 100755 --- a/vv/vvBlendImageActor.cxx +++ b/vv/vvBlendImageActor.cxx @@ -1,20 +1,20 @@ - /*========================================================================= - Program: vv http://www.creatis.insa-lyon.fr/rio/vv +/*========================================================================= +Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: - - University of LYON http://www.universite-lyon.fr/ - - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr +Authors belong to: +- University of LYON http://www.universite-lyon.fr/ +- Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr +- CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the copyright notices for more information. - It is distributed under dual licence +It is distributed under dual licence - - BSD See included LICENSE.txt file - - CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html - ======================================================================-====*/ +- BSD See included LICENSE.txt file +- CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html +======================================================================-====*/ #include "vvBlendImageActor.h" @@ -41,20 +41,18 @@ void vvBlendImageActor::Render(vtkRenderer *ren) //Change blending to maximum per component instead of weighted sum vtkOpenGLRenderWindow *renwin = dynamic_cast(ren->GetRenderWindow()); vtkOpenGLExtensionManager *extensions = renwin->GetExtensionManager(); - if (extensions->ExtensionSupported("GL_EXT_blend_minmax")) - { + if (extensions->ExtensionSupported("GL_EXT_blend_minmax")) { extensions->LoadExtension("GL_EXT_blend_minmax"); vtkgl::BlendEquationEXT( vtkgl::MAX ); - } + } //Call normal render vtkOpenGLImageActor::Render(ren); //Move back blending to weighted sum - if (vtkgl::BlendEquationEXT!=0) - { + if (vtkgl::BlendEquationEXT!=0) { vtkgl::BlendEquationEXT( vtkgl::FUNC_ADD ); - } + } } void vvBlendImageActor::PrintSelf(ostream& os, vtkIndent indent) diff --git a/vv/vvCropDialog.cxx b/vv/vvCropDialog.cxx index 1af8c16..daf6367 100644 --- a/vv/vvCropDialog.cxx +++ b/vv/vvCropDialog.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -27,64 +27,63 @@ #include "clitkCommon.h" vvCropDialog::vvCropDialog(std::vector sms,int current) : - mSlicerManagers(sms) + mSlicerManagers(sms) { - setupUi(this); - for (unsigned int i=0;iaddItem(vtksys::SystemTools::GetFilenameName(mSlicerManagers[i]->GetFileName()).c_str()); - connect(inputSequenceBox,SIGNAL(currentIndexChanged(int)),this,SLOT(ImageChanged(int))); - inputSequenceBox->setCurrentIndex(current); - ImageChanged(current); - connect(this,SIGNAL(accepted()),this,SLOT(ComputeCroppedImage())); + setupUi(this); + for (unsigned int i=0; iaddItem(vtksys::SystemTools::GetFilenameName(mSlicerManagers[i]->GetFileName()).c_str()); + connect(inputSequenceBox,SIGNAL(currentIndexChanged(int)),this,SLOT(ImageChanged(int))); + inputSequenceBox->setCurrentIndex(current); + ImageChanged(current); + connect(this,SIGNAL(accepted()),this,SLOT(ComputeCroppedImage())); } void vvCropDialog::ImageChanged(int newindex) { - std::vector imsize=mSlicerManagers[newindex]->GetImage()->GetSize(); - xminSlider->setMaximum(imsize[0]-1); - xmaxSlider->setMaximum(imsize[0]-1); - xmaxSlider->setValue(imsize[0]-1); - yminSlider->setMaximum(imsize[1]-1); - ymaxSlider->setMaximum(imsize[1]-1); - ymaxSlider->setValue(imsize[1]-1); - zminSlider->setMaximum(imsize[2]-1); - zmaxSlider->setMaximum(imsize[2]-1); - zmaxSlider->setValue(imsize[2]-1); - spin_xmin->setMaximum(imsize[0]-1); - spin_xmax->setMaximum(imsize[0]-1); - spin_xmax->setValue(imsize[0]-1); - spin_ymin->setMaximum(imsize[1]-1); - spin_ymax->setMaximum(imsize[1]-1); - spin_ymax->setValue(imsize[1]-1); - spin_zmin->setMaximum(imsize[2]-1); - spin_zmax->setMaximum(imsize[2]-1); - spin_zmax->setValue(imsize[2]-1); + std::vector imsize=mSlicerManagers[newindex]->GetImage()->GetSize(); + xminSlider->setMaximum(imsize[0]-1); + xmaxSlider->setMaximum(imsize[0]-1); + xmaxSlider->setValue(imsize[0]-1); + yminSlider->setMaximum(imsize[1]-1); + ymaxSlider->setMaximum(imsize[1]-1); + ymaxSlider->setValue(imsize[1]-1); + zminSlider->setMaximum(imsize[2]-1); + zmaxSlider->setMaximum(imsize[2]-1); + zmaxSlider->setValue(imsize[2]-1); + spin_xmin->setMaximum(imsize[0]-1); + spin_xmax->setMaximum(imsize[0]-1); + spin_xmax->setValue(imsize[0]-1); + spin_ymin->setMaximum(imsize[1]-1); + spin_ymax->setMaximum(imsize[1]-1); + spin_ymax->setValue(imsize[1]-1); + spin_zmin->setMaximum(imsize[2]-1); + spin_zmax->setMaximum(imsize[2]-1); + spin_zmax->setValue(imsize[2]-1); } void vvCropDialog::ComputeCroppedImage() { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - mResult=vvImage::New(); - vvSlicerManager * current=mSlicerManagers[inputSequenceBox->currentIndex()]; - vvImage::Pointer image=current->GetImage(); - for (std::vector::const_iterator i=image->GetVTKImages().begin(); - i!=image->GetVTKImages().end();i++) - { - vtkSmartPointer filter=vtkSmartPointer::New(); - ///Vtk is very weird, you need to "translate the extent" to get the correct origin - //http://markmail.org/message/vndc2tr6kcabiakp#query:vtkImageClip%20origin+page:1+mid:6na7y57floutklvz+state:results - vtkSmartPointer translate=vtkSmartPointer::New(); - filter->SetInput(*i); - filter->SetOutputWholeExtent(xminSlider->value(),xmaxSlider->value(), - yminSlider->value(),ymaxSlider->value(), - zminSlider->value(),zmaxSlider->value()); - translate->SetTranslation(-xminSlider->value(),-yminSlider->value(),-zminSlider->value()); - translate->SetInput(filter->GetOutput()); - filter->ClipDataOn(); //Really create a cropped copy of the image - translate->Update(); - vtkImageData* output=vtkImageData::New(); - output->ShallowCopy(translate->GetOutput()); - mResult->AddImage(output); - } - QApplication::restoreOverrideCursor(); + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + mResult=vvImage::New(); + vvSlicerManager * current=mSlicerManagers[inputSequenceBox->currentIndex()]; + vvImage::Pointer image=current->GetImage(); + for (std::vector::const_iterator i=image->GetVTKImages().begin(); + i!=image->GetVTKImages().end(); i++) { + vtkSmartPointer filter=vtkSmartPointer::New(); + ///Vtk is very weird, you need to "translate the extent" to get the correct origin + //http://markmail.org/message/vndc2tr6kcabiakp#query:vtkImageClip%20origin+page:1+mid:6na7y57floutklvz+state:results + vtkSmartPointer translate=vtkSmartPointer::New(); + filter->SetInput(*i); + filter->SetOutputWholeExtent(xminSlider->value(),xmaxSlider->value(), + yminSlider->value(),ymaxSlider->value(), + zminSlider->value(),zmaxSlider->value()); + translate->SetTranslation(-xminSlider->value(),-yminSlider->value(),-zminSlider->value()); + translate->SetInput(filter->GetOutput()); + filter->ClipDataOn(); //Really create a cropped copy of the image + translate->Update(); + vtkImageData* output=vtkImageData::New(); + output->ShallowCopy(translate->GetOutput()); + mResult->AddImage(output); + } + QApplication::restoreOverrideCursor(); } diff --git a/vv/vvDeformableRegistration.cxx b/vv/vvDeformableRegistration.cxx index 22aaf77..a4d36f1 100644 --- a/vv/vvDeformableRegistration.cxx +++ b/vv/vvDeformableRegistration.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -36,162 +36,154 @@ #include "vvImageReader.h" vvDeformableRegistration::vvDeformableRegistration(vvImage::Pointer image,unsigned int ref,\ - unsigned int iter, unsigned int nthread,double a, double s,std::string output_f,unsigned int stop) : - mImage(image), - refimage(ref), - nb_iter(iter), - n_thread(nthread), - progress(0), - stop(stop), - alpha(a), - sigma(s), - output_filename(output_f), - aborted(false) + unsigned int iter, unsigned int nthread,double a, double s,std::string output_f,unsigned int stop) : + mImage(image), + refimage(ref), + nb_iter(iter), + n_thread(nthread), + progress(0), + stop(stop), + alpha(a), + sigma(s), + output_filename(output_f), + aborted(false) { } void vvDeformableRegistration::abort() { - aborted=true; - std::system("killall deformableregistration"); - std::system("killall clitkVFMerge"); + aborted=true; + std::system("killall deformableregistration"); + std::system("killall clitkVFMerge"); } unsigned int vvDeformableRegistration::getProgress() { - QMutexLocker locker(&progress_mutex); - unsigned int retval=progress; - return retval; + QMutexLocker locker(&progress_mutex); + unsigned int retval=progress; + return retval; } void vvDeformableRegistration::cleanup(int frame_number) //remove temporary files { - std::string temp_dir=mTempPath.toStdString(); - for (int i=0;iapplicationPid()); - QDir temp_qt_dir; - DD(temp_qt_dir.mkpath(mTempPath)); - std::string temp_dir=mTempPath.toStdString(); - DD(temp_dir); - std::vector images=mImage->GetVTKImages(); - for (unsigned int i=0;iSetInput(images[i]); - vox->SetFileName(filename.str().c_str()); - if (i==refimage) - ref_file=filename.str(); - vox->Write(); - } - vox->Delete(); - progress++; - int reg_per_thread=static_cast(images.size()-1)/n_thread; - int remainder=static_cast(images.size()-1) - reg_per_thread*n_thread; + clock_t start,finish; + start=clock(); + vtkVOXImageWriter * vox = vtkVOXImageWriter::New(); + std::stringstream command; + std::string ref_file; + mTempPath=QDir::tempPath()+QString("/vv-")+QString::number(qApp->applicationPid()); + QDir temp_qt_dir; + DD(temp_qt_dir.mkpath(mTempPath)); + std::string temp_dir=mTempPath.toStdString(); + DD(temp_dir); + std::vector images=mImage->GetVTKImages(); + for (unsigned int i=0; iSetInput(images[i]); + vox->SetFileName(filename.str().c_str()); + if (i==refimage) + ref_file=filename.str(); + vox->Write(); + } + vox->Delete(); + progress++; + int reg_per_thread=static_cast(images.size()-1)/n_thread; + int remainder=static_cast(images.size()-1) - reg_per_thread*n_thread; #pragma omp parallel for num_threads(n_thread) schedule(static) - for (int i=0;i(n_thread);i++) - { - ///Static scheduling - int remainder_shift=((iGetOrigin()[0]; - command << " --yorigin " << images[0]->GetOrigin()[1]; - command << " --zorigin " << images[0]->GetOrigin()[2]; - command << " -o " << output_filename << std::endl; - DD(command.str()); - std::system(command.str().c_str()); + for (int i=0; i(n_thread); i++) { + ///Static scheduling + int remainder_shift=((i(CLOCKS_PER_SEC)); - mOutput=reader.GetOutput(); + return; + } + command.str(""); + int computed_vf=(refimage==0)?1:0; //index of an image that isn't the reference image + command << "clitkZeroVF -i " << temp_dir << "/deformation_" << computed_vf << ".vf -o " << temp_dir << + "/deformation_" << refimage << ".vf"; + DD(command.str()); //create zero VF for the ref image + std::system(command.str().c_str()); + command.str(""); + command << "clitkVFMerge "; + for (unsigned int i=0; iGetOrigin()[0]; + command << " --yorigin " << images[0]->GetOrigin()[1]; + command << " --zorigin " << images[0]->GetOrigin()[2]; + command << " -o " << output_filename << std::endl; + DD(command.str()); + std::system(command.str().c_str()); + cleanup(images.size()); + if (aborted) { + std::system(("rm " + output_filename).c_str()); + return; + } + vvImageReader reader; + reader.SetInputFilename(output_filename); + reader.Update(VECTORFIELD); + finish=clock(); + DD((finish - start)/static_cast(CLOCKS_PER_SEC)); + mOutput=reader.GetOutput(); } diff --git a/vv/vvDeformationDialog.cxx b/vv/vvDeformationDialog.cxx index 8d54d70..2b6d58c 100644 --- a/vv/vvDeformationDialog.cxx +++ b/vv/vvDeformationDialog.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -45,117 +45,110 @@ vvSlicerManager * vvDeformationDialog::GetSelectedSlicer() const { - return mSlicerManagers[inputSequenceBox->currentIndex()]; + return mSlicerManagers[inputSequenceBox->currentIndex()]; } int vvDeformationDialog::GetReferenceFrameIndex() const { - return refImageSlider->value(); + return refImageSlider->value(); } vvDeformationDialog::vvDeformationDialog(int initialSlicer,const std::vector& slicerManagers) - : mSlicerManagers(slicerManagers) + : mSlicerManagers(slicerManagers) { - setupUi(this); - connect(this,SIGNAL(accepted()),this,SLOT(computeDeformationField())); - for (unsigned int i=0;iaddItem(vtksys::SystemTools::GetFilenameName(slicerManagers[i]->GetFileName()).c_str()); - connect(inputSequenceBox,SIGNAL(currentIndexChanged(int)),this,SLOT(resetSlider(int))); - connect(refImageSlider,SIGNAL(valueChanged(int)),this,SLOT(updateSliderLabel(int))); - connect(outputPushButton, SIGNAL(clicked()), this, SLOT(selectOutputFile())); - inputSequenceBox->setCurrentIndex(initialSlicer); - resetSlider(initialSlicer); - - //Compute ideal number of threads and update dialog accordingly - int best_thread=QThread::idealThreadCount(); - threadSpin->setValue(best_thread); + setupUi(this); + connect(this,SIGNAL(accepted()),this,SLOT(computeDeformationField())); + for (unsigned int i=0; iaddItem(vtksys::SystemTools::GetFilenameName(slicerManagers[i]->GetFileName()).c_str()); + connect(inputSequenceBox,SIGNAL(currentIndexChanged(int)),this,SLOT(resetSlider(int))); + connect(refImageSlider,SIGNAL(valueChanged(int)),this,SLOT(updateSliderLabel(int))); + connect(outputPushButton, SIGNAL(clicked()), this, SLOT(selectOutputFile())); + inputSequenceBox->setCurrentIndex(initialSlicer); + resetSlider(initialSlicer); + + //Compute ideal number of threads and update dialog accordingly + int best_thread=QThread::idealThreadCount(); + threadSpin->setValue(best_thread); } void vvDeformationDialog::selectOutputFile() { - QString Extensions = "MHD Images( *.mhd);;"; - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save As"), - itksys::SystemTools::GetFilenamePath( - mSlicerManagers[inputSequenceBox->currentIndex()]->GetFileName()).c_str(), - Extensions); - outputLineEdit->setText(fileName); + QString Extensions = "MHD Images( *.mhd);;"; + QString fileName = QFileDialog::getSaveFileName(this, + tr("Save As"), + itksys::SystemTools::GetFilenamePath( + mSlicerManagers[inputSequenceBox->currentIndex()]->GetFileName()).c_str(), + Extensions); + outputLineEdit->setText(fileName); } void vvDeformationDialog::updateSliderLabel(int refimage) { - QString count; - count.setNum(refimage); //Normal people start counting at 1... - QString newlabel="Reference Image ("; - newlabel+=count; - newlabel+=")"; - refImageLabel->setText(newlabel); + QString count; + count.setNum(refimage); //Normal people start counting at 1... + QString newlabel="Reference Image ("; + newlabel+=count; + newlabel+=")"; + refImageLabel->setText(newlabel); } void vvDeformationDialog::resetSlider(int slicer_index) { - refImageSlider->setRange(0,mSlicerManagers[slicer_index]->GetSlicer(0)->GetImage()->GetSize()[3]-1); - int refimage=mSlicerManagers[slicer_index]->GetSlicer(0)->GetTSlice(); - refImageSlider->setSliderPosition(refimage); - updateSliderLabel(refimage); + refImageSlider->setRange(0,mSlicerManagers[slicer_index]->GetSlicer(0)->GetImage()->GetSize()[3]-1); + int refimage=mSlicerManagers[slicer_index]->GetSlicer(0)->GetTSlice(); + refImageSlider->setSliderPosition(refimage); + updateSliderLabel(refimage); } -void vvDeformationDialog::computeDeformationField() { - vvImage::Pointer sequence=mSlicerManagers[inputSequenceBox->currentIndex()]->GetSlicer(0)->GetImage(); - vtkImageData * first_image = sequence->GetVTKImages()[0]; - if (!sequence->IsTimeSequence()) - { - this->setResult(QDialog::Rejected); - QMessageBox::warning(this,tr("Image type error"), tr("Deformable image registration only makes sense on time sequences.")); +void vvDeformationDialog::computeDeformationField() +{ + vvImage::Pointer sequence=mSlicerManagers[inputSequenceBox->currentIndex()]->GetSlicer(0)->GetImage(); + vtkImageData * first_image = sequence->GetVTKImages()[0]; + if (!sequence->IsTimeSequence()) { + this->setResult(QDialog::Rejected); + QMessageBox::warning(this,tr("Image type error"), tr("Deformable image registration only makes sense on time sequences.")); + } else if ((first_image->GetSpacing()[0] != first_image->GetSpacing()[1]) || (first_image->GetSpacing()[0] != first_image->GetSpacing()[2])) { + this->setResult(QDialog::Rejected); + QMessageBox::warning(this,tr("Image type error"), tr("Deformable registration only works well with isotropic voxels. Please resample the image.")); + return; + } else { + bool aborted=false; + QProgressDialog progress(this); + QProgressDialog cancel(this); + cancel.setLabelText("Canceling, please wait..."); + cancel.setCancelButtonText(0); + cancel.hide(); + //1 step per registration plus one for each of the image conversions + progress.setMaximum(mSlicerManagers[inputSequenceBox->currentIndex()] + ->GetSlicer(0)->GetImage()->GetSize()[3]+2); + progress.setLabelText("Computing deformation model..."); + progress.setMinimumDuration(0); + progress.setWindowModality(Qt::WindowModal); + progress.setCancelButtonText("Cancel"); + qApp->processEvents(); + QFileInfo info(outputLineEdit->text().toStdString().c_str()); + if (info.isRelative()) { //this is a bit hackish, but should work + QFileInfo im_info(mSlicerManagers[inputSequenceBox->currentIndex()]->GetFileName().c_str()); + outputLineEdit->setText((im_info.path().toStdString() + "/" + outputLineEdit->text().toStdString()).c_str()); } - else if ((first_image->GetSpacing()[0] != first_image->GetSpacing()[1]) || (first_image->GetSpacing()[0] != first_image->GetSpacing()[2])) - { + vvDeformableRegistration registrator(sequence,refImageSlider->value(), iterSpin->value(),threadSpin->value(), alphaSpin->value(), sigmaSpin->value(),outputLineEdit->text().toStdString(),stopSpin->value()); + registrator.start(); + while (!registrator.isFinished()) { + if (progress.wasCanceled() && !aborted) { this->setResult(QDialog::Rejected); - QMessageBox::warning(this,tr("Image type error"), tr("Deformable registration only works well with isotropic voxels. Please resample the image.")); - return; + registrator.abort(); + aborted=true; + progress.hide(); + cancel.show(); + } + if (!aborted) + progress.setValue(registrator.getProgress()); + qApp->processEvents(); + registrator.wait(50); } - else { - bool aborted=false; - QProgressDialog progress(this); - QProgressDialog cancel(this); - cancel.setLabelText("Canceling, please wait..."); - cancel.setCancelButtonText(0); - cancel.hide(); - //1 step per registration plus one for each of the image conversions - progress.setMaximum(mSlicerManagers[inputSequenceBox->currentIndex()] - ->GetSlicer(0)->GetImage()->GetSize()[3]+2); - progress.setLabelText("Computing deformation model..."); - progress.setMinimumDuration(0); - progress.setWindowModality(Qt::WindowModal); - progress.setCancelButtonText("Cancel"); - qApp->processEvents(); - QFileInfo info(outputLineEdit->text().toStdString().c_str()); - if (info.isRelative()) //this is a bit hackish, but should work - { - QFileInfo im_info(mSlicerManagers[inputSequenceBox->currentIndex()]->GetFileName().c_str()); - outputLineEdit->setText((im_info.path().toStdString() + "/" + outputLineEdit->text().toStdString()).c_str()); - } - vvDeformableRegistration registrator(sequence,refImageSlider->value(), iterSpin->value(),threadSpin->value(), alphaSpin->value(), sigmaSpin->value(),outputLineEdit->text().toStdString(),stopSpin->value()); - registrator.start(); - while (!registrator.isFinished()) - { - if (progress.wasCanceled() && !aborted) - { - this->setResult(QDialog::Rejected); - registrator.abort(); - aborted=true; - progress.hide(); - cancel.show(); - } - if (!aborted) - progress.setValue(registrator.getProgress()); - qApp->processEvents(); - registrator.wait(50); - } - if (!aborted) - { - mOutput=registrator.getOutput(); - } + if (!aborted) { + mOutput=registrator.getOutput(); } + } } diff --git a/vv/vvGlyph2D.cxx b/vv/vvGlyph2D.cxx index 721d425..d8ecf5a 100644 --- a/vv/vvGlyph2D.cxx +++ b/vv/vvGlyph2D.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -37,602 +37,503 @@ vtkStandardNewMacro(vvGlyph2D); vvGlyph2D::vvGlyph2D() { - mOrientation[0] = 1; - mOrientation[1] = 1; - mOrientation[2] = 1; - mUseLog = 0; + mOrientation[0] = 1; + mOrientation[1] = 1; + mOrientation[2] = 1; + mUseLog = 0; } //---------------------------------------------------------------------------- int vvGlyph2D::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **inputVector, - vtkInformationVector *outputVector) + vtkInformation *vtkNotUsed(request), + vtkInformationVector **inputVector, + vtkInformationVector *outputVector) { - // get the info objects - vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); - vtkInformation *outInfo = outputVector->GetInformationObject(0); - - // get the input and ouptut - vtkDataSet *input = vtkDataSet::SafeDownCast( - inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkPolyData *output = vtkPolyData::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - - vtkPointData *pd; - vtkDataArray *inSScalars; // Scalars for Scaling - vtkDataArray *inCScalars; // Scalars for Coloring - vtkDataArray *inVectors; - int requestedGhostLevel; - unsigned char* inGhostLevels=0; - vtkDataArray *inNormals, *sourceNormals = NULL; - vtkDataArray *sourceTCoords = NULL; - vtkIdType numPts, numSourcePts, numSourceCells, inPtId, i; - int index; - vtkPoints *sourcePts = NULL; - vtkPoints *newPts; - vtkDataArray *newScalars=NULL; - vtkDataArray *newVectors=NULL; - vtkDataArray *newNormals=NULL; - vtkDataArray *newTCoords = NULL; - double x[3], v[3], vNew[3], s = 0.0, vMag = 0.0, value, tc[3]; - vtkTransform *trans = vtkTransform::New(); - vtkCell *cell; - vtkIdList *cellPts; - int npts; - vtkIdList *pts; - vtkIdType ptIncr, cellId; - int haveVectors, haveNormals, haveTCoords = 0; - double scalex,scaley,scalez, den; - vtkPointData *outputPD = output->GetPointData(); - int numberOfSources = this->GetNumberOfInputConnections(1); - vtkPolyData *defaultSource = NULL; - vtkIdTypeArray *pointIds=0; - vtkPolyData *source = 0; - - vtkDebugMacro(<<"Generating glyphs"); - - pts = vtkIdList::New(); - pts->Allocate(VTK_CELL_SIZE); - - pd = input->GetPointData(); - inSScalars = this->GetInputArrayToProcess(0,inputVector); - inVectors = this->GetInputArrayToProcess(1,inputVector); - inNormals = this->GetInputArrayToProcess(2,inputVector); - inCScalars = this->GetInputArrayToProcess(3,inputVector); - if (inCScalars == NULL) - { - inCScalars = inSScalars; - } - - vtkDataArray* temp = 0; - if (pd) - { - temp = pd->GetArray("vtkGhostLevels"); + // get the info objects + vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation *outInfo = outputVector->GetInformationObject(0); + + // get the input and ouptut + vtkDataSet *input = vtkDataSet::SafeDownCast( + inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkPolyData *output = vtkPolyData::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + vtkPointData *pd; + vtkDataArray *inSScalars; // Scalars for Scaling + vtkDataArray *inCScalars; // Scalars for Coloring + vtkDataArray *inVectors; + int requestedGhostLevel; + unsigned char* inGhostLevels=0; + vtkDataArray *inNormals, *sourceNormals = NULL; + vtkDataArray *sourceTCoords = NULL; + vtkIdType numPts, numSourcePts, numSourceCells, inPtId, i; + int index; + vtkPoints *sourcePts = NULL; + vtkPoints *newPts; + vtkDataArray *newScalars=NULL; + vtkDataArray *newVectors=NULL; + vtkDataArray *newNormals=NULL; + vtkDataArray *newTCoords = NULL; + double x[3], v[3], vNew[3], s = 0.0, vMag = 0.0, value, tc[3]; + vtkTransform *trans = vtkTransform::New(); + vtkCell *cell; + vtkIdList *cellPts; + int npts; + vtkIdList *pts; + vtkIdType ptIncr, cellId; + int haveVectors, haveNormals, haveTCoords = 0; + double scalex,scaley,scalez, den; + vtkPointData *outputPD = output->GetPointData(); + int numberOfSources = this->GetNumberOfInputConnections(1); + vtkPolyData *defaultSource = NULL; + vtkIdTypeArray *pointIds=0; + vtkPolyData *source = 0; + + vtkDebugMacro(<<"Generating glyphs"); + + pts = vtkIdList::New(); + pts->Allocate(VTK_CELL_SIZE); + + pd = input->GetPointData(); + inSScalars = this->GetInputArrayToProcess(0,inputVector); + inVectors = this->GetInputArrayToProcess(1,inputVector); + inNormals = this->GetInputArrayToProcess(2,inputVector); + inCScalars = this->GetInputArrayToProcess(3,inputVector); + if (inCScalars == NULL) { + inCScalars = inSScalars; + } + + vtkDataArray* temp = 0; + if (pd) { + temp = pd->GetArray("vtkGhostLevels"); + } + if ( (!temp) || (temp->GetDataType() != VTK_UNSIGNED_CHAR) + || (temp->GetNumberOfComponents() != 1)) { + vtkDebugMacro("No appropriate ghost levels field available."); + } else { + inGhostLevels = ((vtkUnsignedCharArray*)temp)->GetPointer(0); + } + + requestedGhostLevel = + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()); + + numPts = input->GetNumberOfPoints(); + if (numPts < 1) { + vtkDebugMacro(<<"No points to glyph!"); + pts->Delete(); + trans->Delete(); + return 1; + } + + // Check input for consistency + // + if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) { + den = 1.0; + } + if ( this->VectorMode != VTK_VECTOR_ROTATION_OFF && + ((this->VectorMode == VTK_USE_VECTOR && inVectors != NULL) || + (this->VectorMode == VTK_USE_NORMAL && inNormals != NULL)) ) { + haveVectors = 1; + } else { + haveVectors = 0; + } + + if ( (this->IndexMode == VTK_INDEXING_BY_SCALAR && !inSScalars) || + (this->IndexMode == VTK_INDEXING_BY_VECTOR && + ((!inVectors && this->VectorMode == VTK_USE_VECTOR) || + (!inNormals && this->VectorMode == VTK_USE_NORMAL))) ) { + if ( this->GetSource(0, inputVector[1]) == NULL ) { + vtkErrorMacro(<<"Indexing on but don't have data to index with"); + pts->Delete(); + trans->Delete(); + return 1; + } else { + vtkWarningMacro(<<"Turning indexing off: no data to index with"); + this->IndexMode = VTK_INDEXING_OFF; } - if ( (!temp) || (temp->GetDataType() != VTK_UNSIGNED_CHAR) - || (temp->GetNumberOfComponents() != 1)) - { - vtkDebugMacro("No appropriate ghost levels field available."); + } + + // Allocate storage for output PolyData + // + outputPD->CopyVectorsOff(); + outputPD->CopyNormalsOff(); + outputPD->CopyTCoordsOff(); + + if (!this->GetSource(0, inputVector[1])) { + defaultSource = vtkPolyData::New(); + defaultSource->Allocate(); + vtkPoints *defaultPoints = vtkPoints::New(); + defaultPoints->Allocate(6); + defaultPoints->InsertNextPoint(0, 0, 0); + defaultPoints->InsertNextPoint(1, 0, 0); + vtkIdType defaultPointIds[2]; + defaultPointIds[0] = 0; + defaultPointIds[1] = 1; + defaultSource->SetPoints(defaultPoints); + defaultSource->InsertNextCell(VTK_LINE, 2, defaultPointIds); + defaultSource->SetUpdateExtent(0, 1, 0); + this->SetSource(defaultSource); + defaultSource->Delete(); + defaultSource = NULL; + defaultPoints->Delete(); + defaultPoints = NULL; + } + + if ( this->IndexMode != VTK_INDEXING_OFF ) { + pd = NULL; + haveNormals = 1; + for (numSourcePts=numSourceCells=i=0; i < numberOfSources; i++) { + source = this->GetSource(i, inputVector[1]); + if ( source != NULL ) { + if (source->GetNumberOfPoints() > numSourcePts) { + numSourcePts = source->GetNumberOfPoints(); + } + if (source->GetNumberOfCells() > numSourceCells) { + numSourceCells = source->GetNumberOfCells(); + } + if ( !(sourceNormals = source->GetPointData()->GetNormals()) ) { + haveNormals = 0; + } + } } - else - { - inGhostLevels = ((vtkUnsignedCharArray*)temp)->GetPointer(0); + } else { + source = this->GetSource(0, inputVector[1]); + sourcePts = source->GetPoints(); + numSourcePts = sourcePts->GetNumberOfPoints(); + numSourceCells = source->GetNumberOfCells(); + + sourceNormals = source->GetPointData()->GetNormals(); + if ( sourceNormals ) { + haveNormals = 1; + } else { + haveNormals = 0; } - requestedGhostLevel = - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS()); - - numPts = input->GetNumberOfPoints(); - if (numPts < 1) - { - vtkDebugMacro(<<"No points to glyph!"); - pts->Delete(); - trans->Delete(); - return 1; + sourceTCoords = source->GetPointData()->GetTCoords(); + if (sourceTCoords) { + haveTCoords = 1; + } else { + haveTCoords = 0; } - // Check input for consistency - // - if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) - { - den = 1.0; - } - if ( this->VectorMode != VTK_VECTOR_ROTATION_OFF && - ((this->VectorMode == VTK_USE_VECTOR && inVectors != NULL) || - (this->VectorMode == VTK_USE_NORMAL && inNormals != NULL)) ) - { - haveVectors = 1; + // Prepare to copy output. + pd = input->GetPointData(); + outputPD->CopyAllocate(pd,numPts*numSourcePts); + } + + newPts = vtkPoints::New(); + newPts->Allocate(numPts*numSourcePts); + if ( this->GeneratePointIds ) { + pointIds = vtkIdTypeArray::New(); + pointIds->SetName(this->PointIdsName); + pointIds->Allocate(numPts*numSourcePts); + outputPD->AddArray(pointIds); + pointIds->Delete(); + } + if ( this->ColorMode == VTK_COLOR_BY_SCALAR && inCScalars ) { + newScalars = inCScalars->NewInstance(); + newScalars->SetNumberOfComponents(inCScalars->GetNumberOfComponents()); + newScalars->Allocate(inCScalars->GetNumberOfComponents()*numPts*numSourcePts); + newScalars->SetName(inCScalars->GetName()); + } else if ( (this->ColorMode == VTK_COLOR_BY_SCALE) && inSScalars) { + newScalars = vtkFloatArray::New(); + newScalars->Allocate(numPts*numSourcePts); + newScalars->SetName("GlyphScale"); + if (this->ScaleMode == VTK_SCALE_BY_SCALAR) { + newScalars->SetName(inSScalars->GetName()); } - else - { - haveVectors = 0; + } else if ( (this->ColorMode == VTK_COLOR_BY_VECTOR) && haveVectors) { + newScalars = vtkFloatArray::New(); + newScalars->Allocate(numPts*numSourcePts); + newScalars->SetName("VectorMagnitude"); + } + if ( haveVectors ) { + newVectors = vtkFloatArray::New(); + newVectors->SetNumberOfComponents(3); + newVectors->Allocate(3*numPts*numSourcePts); + newVectors->SetName("GlyphVector"); + } + if ( haveNormals ) { + newNormals = vtkFloatArray::New(); + newNormals->SetNumberOfComponents(3); + newNormals->Allocate(3*numPts*numSourcePts); + newNormals->SetName("Normals"); + } + if (haveTCoords) { + newTCoords = vtkFloatArray::New(); + int numComps = sourceTCoords->GetNumberOfComponents(); + newTCoords->SetNumberOfComponents(numComps); + newTCoords->Allocate(numComps*numPts*numSourcePts); + newTCoords->SetName("TCoords"); + } + + // Setting up for calls to PolyData::InsertNextCell() + if (this->IndexMode != VTK_INDEXING_OFF ) { + output->Allocate(3*numPts*numSourceCells,numPts*numSourceCells); + } else { + output->Allocate(this->GetSource(0, inputVector[1]), + 3*numPts*numSourceCells, numPts*numSourceCells); + } + + // Traverse all Input points, transforming Source points and copying + // point attributes. + // + ptIncr=0; + for (inPtId=0; inPtId < numPts; inPtId++) { + scalex = scaley = scalez = 1.0; + if ( ! (inPtId % 10000) ) { + this->UpdateProgress ((double)inPtId/numPts); + if (this->GetAbortExecute()) { + break; + } } - if ( (this->IndexMode == VTK_INDEXING_BY_SCALAR && !inSScalars) || - (this->IndexMode == VTK_INDEXING_BY_VECTOR && - ((!inVectors && this->VectorMode == VTK_USE_VECTOR) || - (!inNormals && this->VectorMode == VTK_USE_NORMAL))) ) - { - if ( this->GetSource(0, inputVector[1]) == NULL ) - { - vtkErrorMacro(<<"Indexing on but don't have data to index with"); - pts->Delete(); - trans->Delete(); - return 1; - } - else - { - vtkWarningMacro(<<"Turning indexing off: no data to index with"); - this->IndexMode = VTK_INDEXING_OFF; - } + // Get the scalar and vector data + if ( inSScalars ) { + s = inSScalars->GetComponent(inPtId, 0); + if ( this->ScaleMode == VTK_SCALE_BY_SCALAR || + this->ScaleMode == VTK_DATA_SCALING_OFF ) { + scalex = scaley = scalez = s; + } } - // Allocate storage for output PolyData - // - outputPD->CopyVectorsOff(); - outputPD->CopyNormalsOff(); - outputPD->CopyTCoordsOff(); - - if (!this->GetSource(0, inputVector[1])) - { - defaultSource = vtkPolyData::New(); - defaultSource->Allocate(); - vtkPoints *defaultPoints = vtkPoints::New(); - defaultPoints->Allocate(6); - defaultPoints->InsertNextPoint(0, 0, 0); - defaultPoints->InsertNextPoint(1, 0, 0); - vtkIdType defaultPointIds[2]; - defaultPointIds[0] = 0; - defaultPointIds[1] = 1; - defaultSource->SetPoints(defaultPoints); - defaultSource->InsertNextCell(VTK_LINE, 2, defaultPointIds); - defaultSource->SetUpdateExtent(0, 1, 0); - this->SetSource(defaultSource); - defaultSource->Delete(); - defaultSource = NULL; - defaultPoints->Delete(); - defaultPoints = NULL; + if ( haveVectors ) { + if ( this->VectorMode == VTK_USE_NORMAL ) { + inNormals->GetTuple(inPtId, v); + } else { + inVectors->GetTuple(inPtId, v); + } + + vMag = vtkMath::Norm(v); + if ( this->ScaleMode == VTK_SCALE_BY_VECTORCOMPONENTS ) { + scalex = v[0]; + scaley = v[1]; + scalez = v[2]; + } else if ( this->ScaleMode == VTK_SCALE_BY_VECTOR ) { + scalex = scaley = scalez = vMag; + } } - if ( this->IndexMode != VTK_INDEXING_OFF ) - { - pd = NULL; - haveNormals = 1; - for (numSourcePts=numSourceCells=i=0; i < numberOfSources; i++) - { - source = this->GetSource(i, inputVector[1]); - if ( source != NULL ) - { - if (source->GetNumberOfPoints() > numSourcePts) - { - numSourcePts = source->GetNumberOfPoints(); - } - if (source->GetNumberOfCells() > numSourceCells) - { - numSourceCells = source->GetNumberOfCells(); - } - if ( !(sourceNormals = source->GetPointData()->GetNormals()) ) - { - haveNormals = 0; - } - } - } + // Clamp data scale if enabled + if ( this->Clamping ) { + scalex = (scalex < this->Range[0] ? this->Range[0] : + (scalex > this->Range[1] ? this->Range[1] : scalex)); + scalex = (scalex - this->Range[0]) / den; + scaley = (scaley < this->Range[0] ? this->Range[0] : + (scaley > this->Range[1] ? this->Range[1] : scaley)); + scaley = (scaley - this->Range[0]) / den; + scalez = (scalez < this->Range[0] ? this->Range[0] : + (scalez > this->Range[1] ? this->Range[1] : scalez)); + scalez = (scalez - this->Range[0]) / den; } - else - { - source = this->GetSource(0, inputVector[1]); + + // Compute index into table of glyphs + if ( this->IndexMode == VTK_INDEXING_OFF ) { + index = 0; + } else { + if ( this->IndexMode == VTK_INDEXING_BY_SCALAR ) { + value = s; + } else { + value = vMag; + } + + index = (int) ((double)(value - this->Range[0]) * numberOfSources / den); + index = (index < 0 ? 0 : + (index >= numberOfSources ? (numberOfSources-1) : index)); + + source = this->GetSource(index, inputVector[1]); + if ( source != NULL ) { sourcePts = source->GetPoints(); + sourceNormals = source->GetPointData()->GetNormals(); numSourcePts = sourcePts->GetNumberOfPoints(); numSourceCells = source->GetNumberOfCells(); + } + } - sourceNormals = source->GetPointData()->GetNormals(); - if ( sourceNormals ) - { - haveNormals = 1; - } - else - { - haveNormals = 0; - } - - sourceTCoords = source->GetPointData()->GetTCoords(); - if (sourceTCoords) - { - haveTCoords = 1; - } - else - { - haveTCoords = 0; - } + // Make sure we're not indexing into empty glyph + if ( this->GetSource(index, inputVector[1]) == NULL ) { + continue; + } - // Prepare to copy output. - pd = input->GetPointData(); - outputPD->CopyAllocate(pd,numPts*numSourcePts); + // Check ghost points. + // If we are processing a piece, we do not want to duplicate + // glyphs on the borders. The corrct check here is: + // ghostLevel > 0. I am leaving this over glyphing here because + // it make a nice example (sphereGhost.tcl) to show the + // point ghost levels with the glyph filter. I am not certain + // of the usefullness of point ghost levels over 1, but I will have + // to think about it. + if (inGhostLevels && inGhostLevels[inPtId] > requestedGhostLevel) { + continue; } - newPts = vtkPoints::New(); - newPts->Allocate(numPts*numSourcePts); - if ( this->GeneratePointIds ) - { - pointIds = vtkIdTypeArray::New(); - pointIds->SetName(this->PointIdsName); - pointIds->Allocate(numPts*numSourcePts); - outputPD->AddArray(pointIds); - pointIds->Delete(); + if (!this->IsPointVisible(input, inPtId)) { + continue; } - if ( this->ColorMode == VTK_COLOR_BY_SCALAR && inCScalars ) - { - newScalars = inCScalars->NewInstance(); - newScalars->SetNumberOfComponents(inCScalars->GetNumberOfComponents()); - newScalars->Allocate(inCScalars->GetNumberOfComponents()*numPts*numSourcePts); - newScalars->SetName(inCScalars->GetName()); + + // Now begin copying/transforming glyph + trans->Identity(); + + // Copy all topology (transformation independent) + for (cellId=0; cellId < numSourceCells; cellId++) { + cell = this->GetSource(index, inputVector[1])->GetCell(cellId); + cellPts = cell->GetPointIds(); + npts = cellPts->GetNumberOfIds(); + for (pts->Reset(), i=0; i < npts; i++) { + pts->InsertId(i,cellPts->GetId(i) + ptIncr); + } + output->InsertNextCell(cell->GetCellType(),pts); } - else if ( (this->ColorMode == VTK_COLOR_BY_SCALE) && inSScalars) - { - newScalars = vtkFloatArray::New(); - newScalars->Allocate(numPts*numSourcePts); - newScalars->SetName("GlyphScale"); - if (this->ScaleMode == VTK_SCALE_BY_SCALAR) - { - newScalars->SetName(inSScalars->GetName()); + + // translate Source to Input point + input->GetPoint(inPtId, x); + + //projection on the plane orthogonale to the camera + trans->Scale(mOrientation[0],mOrientation[1],mOrientation[2]); + + trans->Translate(x[0], x[1], x[2]); + + if ( haveVectors ) { + // Copy Input vector + for (i=0; i < numSourcePts; i++) { + newVectors->InsertTuple(i+ptIncr, v); + } + if (this->Orient && (vMag > 0.0)) { + // if there is no y or z component + if ( v[1] == 0.0 && v[2] == 0.0 ) { + if (v[0] < 0) { //just flip x if we need to + trans->RotateWXYZ(180.0,0,1,0); + } + } else { + vNew[0] = (v[0]+vMag) / 2.0; + vNew[1] = v[1] / 2.0; + vNew[2] = v[2] / 2.0; + trans->RotateWXYZ((double)180.0,vNew[0],vNew[1],vNew[2]); } + } } - else if ( (this->ColorMode == VTK_COLOR_BY_VECTOR) && haveVectors) - { - newScalars = vtkFloatArray::New(); - newScalars->Allocate(numPts*numSourcePts); - newScalars->SetName("VectorMagnitude"); - } - if ( haveVectors ) - { - newVectors = vtkFloatArray::New(); - newVectors->SetNumberOfComponents(3); - newVectors->Allocate(3*numPts*numSourcePts); - newVectors->SetName("GlyphVector"); - } - if ( haveNormals ) - { - newNormals = vtkFloatArray::New(); - newNormals->SetNumberOfComponents(3); - newNormals->Allocate(3*numPts*numSourcePts); - newNormals->SetName("Normals"); - } - if (haveTCoords) - { - newTCoords = vtkFloatArray::New(); - int numComps = sourceTCoords->GetNumberOfComponents(); - newTCoords->SetNumberOfComponents(numComps); - newTCoords->Allocate(numComps*numPts*numSourcePts); - newTCoords->SetName("TCoords"); + + if (haveTCoords) { + for (i = 0; i < numSourcePts; i++) { + sourceTCoords->GetTuple(i, tc); + newTCoords->InsertTuple(i+ptIncr, tc); + } } - // Setting up for calls to PolyData::InsertNextCell() - if (this->IndexMode != VTK_INDEXING_OFF ) - { - output->Allocate(3*numPts*numSourceCells,numPts*numSourceCells); + // determine scale factor from scalars if appropriate + // Copy scalar value + if (inSScalars && (this->ColorMode == VTK_COLOR_BY_SCALE)) { + for (i=0; i < numSourcePts; i++) { + newScalars->InsertTuple(i+ptIncr, &scalex); // = scaley = scalez + } + } else if (inCScalars && (this->ColorMode == VTK_COLOR_BY_SCALAR)) { + for (i=0; i < numSourcePts; i++) { + outputPD->CopyTuple(inCScalars, newScalars, inPtId, ptIncr+i); + } } - else - { - output->Allocate(this->GetSource(0, inputVector[1]), - 3*numPts*numSourceCells, numPts*numSourceCells); + if (haveVectors && this->ColorMode == VTK_COLOR_BY_VECTOR) { + double color = 1; + for (i=0; i < numSourcePts; i++) { + newScalars->InsertTuple(i+ptIncr, &color); + } } - // Traverse all Input points, transforming Source points and copying - // point attributes. - // - ptIncr=0; - for (inPtId=0; inPtId < numPts; inPtId++) - { - scalex = scaley = scalez = 1.0; - if ( ! (inPtId % 10000) ) - { - this->UpdateProgress ((double)inPtId/numPts); - if (this->GetAbortExecute()) - { - break; - } - } - - // Get the scalar and vector data - if ( inSScalars ) - { - s = inSScalars->GetComponent(inPtId, 0); - if ( this->ScaleMode == VTK_SCALE_BY_SCALAR || - this->ScaleMode == VTK_DATA_SCALING_OFF ) - { - scalex = scaley = scalez = s; - } - } - - if ( haveVectors ) - { - if ( this->VectorMode == VTK_USE_NORMAL ) - { - inNormals->GetTuple(inPtId, v); - } - else - { - inVectors->GetTuple(inPtId, v); - } - - vMag = vtkMath::Norm(v); - if ( this->ScaleMode == VTK_SCALE_BY_VECTORCOMPONENTS ) - { - scalex = v[0]; - scaley = v[1]; - scalez = v[2]; - } - else if ( this->ScaleMode == VTK_SCALE_BY_VECTOR ) - { - scalex = scaley = scalez = vMag; - } - } - - // Clamp data scale if enabled - if ( this->Clamping ) - { - scalex = (scalex < this->Range[0] ? this->Range[0] : - (scalex > this->Range[1] ? this->Range[1] : scalex)); - scalex = (scalex - this->Range[0]) / den; - scaley = (scaley < this->Range[0] ? this->Range[0] : - (scaley > this->Range[1] ? this->Range[1] : scaley)); - scaley = (scaley - this->Range[0]) / den; - scalez = (scalez < this->Range[0] ? this->Range[0] : - (scalez > this->Range[1] ? this->Range[1] : scalez)); - scalez = (scalez - this->Range[0]) / den; - } - - // Compute index into table of glyphs - if ( this->IndexMode == VTK_INDEXING_OFF ) - { - index = 0; - } - else - { - if ( this->IndexMode == VTK_INDEXING_BY_SCALAR ) - { - value = s; - } - else - { - value = vMag; - } - - index = (int) ((double)(value - this->Range[0]) * numberOfSources / den); - index = (index < 0 ? 0 : - (index >= numberOfSources ? (numberOfSources-1) : index)); - - source = this->GetSource(index, inputVector[1]); - if ( source != NULL ) - { - sourcePts = source->GetPoints(); - sourceNormals = source->GetPointData()->GetNormals(); - numSourcePts = sourcePts->GetNumberOfPoints(); - numSourceCells = source->GetNumberOfCells(); - } - } - - // Make sure we're not indexing into empty glyph - if ( this->GetSource(index, inputVector[1]) == NULL ) - { - continue; - } - - // Check ghost points. - // If we are processing a piece, we do not want to duplicate - // glyphs on the borders. The corrct check here is: - // ghostLevel > 0. I am leaving this over glyphing here because - // it make a nice example (sphereGhost.tcl) to show the - // point ghost levels with the glyph filter. I am not certain - // of the usefullness of point ghost levels over 1, but I will have - // to think about it. - if (inGhostLevels && inGhostLevels[inPtId] > requestedGhostLevel) - { - continue; - } - - if (!this->IsPointVisible(input, inPtId)) - { - continue; - } - - // Now begin copying/transforming glyph - trans->Identity(); - - // Copy all topology (transformation independent) - for (cellId=0; cellId < numSourceCells; cellId++) - { - cell = this->GetSource(index, inputVector[1])->GetCell(cellId); - cellPts = cell->GetPointIds(); - npts = cellPts->GetNumberOfIds(); - for (pts->Reset(), i=0; i < npts; i++) - { - pts->InsertId(i,cellPts->GetId(i) + ptIncr); - } - output->InsertNextCell(cell->GetCellType(),pts); - } - - // translate Source to Input point - input->GetPoint(inPtId, x); - - //projection on the plane orthogonale to the camera - trans->Scale(mOrientation[0],mOrientation[1],mOrientation[2]); - - trans->Translate(x[0], x[1], x[2]); - - if ( haveVectors ) - { - // Copy Input vector - for (i=0; i < numSourcePts; i++) - { - newVectors->InsertTuple(i+ptIncr, v); - } - if (this->Orient && (vMag > 0.0)) - { - // if there is no y or z component - if ( v[1] == 0.0 && v[2] == 0.0 ) - { - if (v[0] < 0) //just flip x if we need to - { - trans->RotateWXYZ(180.0,0,1,0); - } - } - else - { - vNew[0] = (v[0]+vMag) / 2.0; - vNew[1] = v[1] / 2.0; - vNew[2] = v[2] / 2.0; - trans->RotateWXYZ((double)180.0,vNew[0],vNew[1],vNew[2]); - } - } - } - - if (haveTCoords) - { - for (i = 0; i < numSourcePts; i++) - { - sourceTCoords->GetTuple(i, tc); - newTCoords->InsertTuple(i+ptIncr, tc); - } - } - - // determine scale factor from scalars if appropriate - // Copy scalar value - if (inSScalars && (this->ColorMode == VTK_COLOR_BY_SCALE)) - { - for (i=0; i < numSourcePts; i++) - { - newScalars->InsertTuple(i+ptIncr, &scalex); // = scaley = scalez - } - } - else if (inCScalars && (this->ColorMode == VTK_COLOR_BY_SCALAR)) - { - for (i=0; i < numSourcePts; i++) - { - outputPD->CopyTuple(inCScalars, newScalars, inPtId, ptIncr+i); - } - } - if (haveVectors && this->ColorMode == VTK_COLOR_BY_VECTOR) - { - double color = 1; - for (i=0; i < numSourcePts; i++) - { - newScalars->InsertTuple(i+ptIncr, &color); - } - } - - // scale data if appropriate - if ( this->Scaling ) - { - if ( this->ScaleMode == VTK_DATA_SCALING_OFF ) - { - scalex = scaley = scalez = this->ScaleFactor; - } - else - { - scalex *= this->ScaleFactor; - scaley *= this->ScaleFactor; - scalez *= this->ScaleFactor; - } - - if ( scalex == 0.0 ) - { - scalex = 1.0e-10; - } - if ( scaley == 0.0 ) - { - scaley = 1.0e-10; - } - if ( scalez == 0.0 ) - { - scalez = 1.0e-10; - } - trans->Scale(scalex,scaley,scalez); - } - // multiply points and normals by resulting matrix - trans->TransformPoints(sourcePts,newPts); - - if ( haveNormals ) - { - trans->TransformNormals(sourceNormals,newNormals); - } + // scale data if appropriate + if ( this->Scaling ) { + if ( this->ScaleMode == VTK_DATA_SCALING_OFF ) { + scalex = scaley = scalez = this->ScaleFactor; + } else { + scalex *= this->ScaleFactor; + scaley *= this->ScaleFactor; + scalez *= this->ScaleFactor; + } + + if ( scalex == 0.0 ) { + scalex = 1.0e-10; + } + if ( scaley == 0.0 ) { + scaley = 1.0e-10; + } + if ( scalez == 0.0 ) { + scalez = 1.0e-10; + } + trans->Scale(scalex,scaley,scalez); + } + // multiply points and normals by resulting matrix + trans->TransformPoints(sourcePts,newPts); - // Copy point data from source (if possible) - if ( pd ) - { - for (i=0; i < numSourcePts; i++) - { - outputPD->CopyData(pd,inPtId,ptIncr+i); - } - } + if ( haveNormals ) { + trans->TransformNormals(sourceNormals,newNormals); + } - // If point ids are to be generated, do it here - if ( this->GeneratePointIds ) - { - for (i=0; i < numSourcePts; i++) - { - pointIds->InsertNextValue(inPtId); - } - } + // Copy point data from source (if possible) + if ( pd ) { + for (i=0; i < numSourcePts; i++) { + outputPD->CopyData(pd,inPtId,ptIncr+i); + } + } - ptIncr += numSourcePts; + // If point ids are to be generated, do it here + if ( this->GeneratePointIds ) { + for (i=0; i < numSourcePts; i++) { + pointIds->InsertNextValue(inPtId); + } } - // Update ourselves and release memory - // - output->SetPoints(newPts); - newPts->Delete(); + ptIncr += numSourcePts; + } - if (newScalars) - { - int idx = outputPD->AddArray(newScalars); - outputPD->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS); - newScalars->Delete(); - } + // Update ourselves and release memory + // + output->SetPoints(newPts); + newPts->Delete(); - if (newVectors) - { - outputPD->SetVectors(newVectors); - newVectors->Delete(); - } + if (newScalars) { + int idx = outputPD->AddArray(newScalars); + outputPD->SetActiveAttribute(idx, vtkDataSetAttributes::SCALARS); + newScalars->Delete(); + } - if (newNormals) - { - outputPD->SetNormals(newNormals); - newNormals->Delete(); - } + if (newVectors) { + outputPD->SetVectors(newVectors); + newVectors->Delete(); + } - if (newTCoords) - { - outputPD->SetTCoords(newTCoords); - newTCoords->Delete(); - } + if (newNormals) { + outputPD->SetNormals(newNormals); + newNormals->Delete(); + } - output->Squeeze(); - trans->Delete(); - pts->Delete(); + if (newTCoords) { + outputPD->SetTCoords(newTCoords); + newTCoords->Delete(); + } - return 1; + output->Squeeze(); + trans->Delete(); + pts->Delete(); + + return 1; } void vvGlyph2D::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os,indent); } void vvGlyph2D::SetOrientation(int x, int y, int z) { - if (x == 0) - mOrientation[0] = 1.0e-10; - else - mOrientation[0] = 1.0; - if (y == 0) - mOrientation[1] = 1.0e-10; - else - mOrientation[1] = 1.0; - if (z == 0) - mOrientation[2] = 1.0e-10; - else - mOrientation[2] = 1.0; + if (x == 0) + mOrientation[0] = 1.0e-10; + else + mOrientation[0] = 1.0; + if (y == 0) + mOrientation[1] = 1.0e-10; + else + mOrientation[1] = 1.0; + if (z == 0) + mOrientation[2] = 1.0e-10; + else + mOrientation[2] = 1.0; } diff --git a/vv/vvGlyphSource.cxx b/vv/vvGlyphSource.cxx index 8801a77..b01866c 100644 --- a/vv/vvGlyphSource.cxx +++ b/vv/vvGlyphSource.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -32,138 +32,135 @@ vtkStandardNewMacro(vvGlyphSource); //---------------------------------------------------------------------------- int vvGlyphSource::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) { - // get the info object - vtkInformation *outInfo = outputVector->GetInformationObject(0); - - // get the ouptut - vtkPolyData *output = vtkPolyData::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - - //Allocate storage - vtkPoints *pts = vtkPoints::New(); - pts->Allocate(6,6); - vtkCellArray *verts = vtkCellArray::New(); - verts->Allocate(verts->EstimateSize(1,1),1); - vtkCellArray *lines = vtkCellArray::New(); - lines->Allocate(lines->EstimateSize(4,2),2); - vtkCellArray *polys = vtkCellArray::New(); - polys->Allocate(polys->EstimateSize(1,4),4); - vtkUnsignedCharArray *colors = vtkUnsignedCharArray::New(); - colors->SetNumberOfComponents(3); - colors->Allocate(2,2); - - this->ConvertColor(); - - //Special options - if ( this->Dash ) - { - int filled = this->Filled; - this->Filled = 0; - this->CreateDash(pts,lines,polys,colors,this->Scale2); - this->Filled = filled; - } - if ( this->Cross ) - { - int filled = this->Filled; - this->Filled = 0; - this->CreateCross(pts,lines,polys,colors,this->Scale2); - this->Filled = filled; - } - - //Call the right function - switch (this->GlyphType) - { - case VTK_NO_GLYPH: - break; - case VTK_VERTEX_GLYPH: - this->CreateVertex(pts,verts,colors); - break; - case VTK_DASH_GLYPH: - this->CreateDash(pts,lines,polys,colors,this->Scale); - break; - case VTK_CROSS_GLYPH: - this->CreateCross(pts,lines,polys,colors,this->Scale); - break; - case VTK_THICKCROSS_GLYPH: - this->CreateThickCross(pts,lines,polys,colors); - break; - case VTK_TRIANGLE_GLYPH: - this->CreateTriangle(pts,lines,polys,colors); - break; - case VTK_SQUARE_GLYPH: - this->CreateSquare(pts,lines,polys,colors); - break; - case VTK_CIRCLE_GLYPH: - this->CreateCircle(pts,lines,polys,colors); - break; - case VTK_DIAMOND_GLYPH: - this->CreateDiamond(pts,lines,polys,colors); - break; - case VTK_ARROW_GLYPH: - this->CreateArrow(pts,lines,polys,colors); - break; - case VTK_THICKARROW_GLYPH: - this->CreateThickArrow(pts,lines,polys,colors); - break; - case VTK_HOOKEDARROW_GLYPH: - this->CreateHookedArrow(pts,lines,polys,colors); - break; - case VTK_EDGEARROW_GLYPH: - this->CreateEdgeArrow(pts,lines,polys,colors); - break; - case VTK_SPECIFICARROW_GLYPH: - this->CreateSpecificArrow(pts,lines,polys,colors); - break; - } - - this->TransformGlyph(pts); - - //Clean up - output->SetPoints(pts); - pts->Delete(); - - output->SetVerts(verts); - verts->Delete(); - - output->SetLines(lines); - lines->Delete(); - - output->SetPolys(polys); - polys->Delete(); - - output->GetCellData()->SetScalars(colors); - colors->Delete(); - - return 1; + // get the info object + vtkInformation *outInfo = outputVector->GetInformationObject(0); + + // get the ouptut + vtkPolyData *output = vtkPolyData::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + //Allocate storage + vtkPoints *pts = vtkPoints::New(); + pts->Allocate(6,6); + vtkCellArray *verts = vtkCellArray::New(); + verts->Allocate(verts->EstimateSize(1,1),1); + vtkCellArray *lines = vtkCellArray::New(); + lines->Allocate(lines->EstimateSize(4,2),2); + vtkCellArray *polys = vtkCellArray::New(); + polys->Allocate(polys->EstimateSize(1,4),4); + vtkUnsignedCharArray *colors = vtkUnsignedCharArray::New(); + colors->SetNumberOfComponents(3); + colors->Allocate(2,2); + + this->ConvertColor(); + + //Special options + if ( this->Dash ) { + int filled = this->Filled; + this->Filled = 0; + this->CreateDash(pts,lines,polys,colors,this->Scale2); + this->Filled = filled; + } + if ( this->Cross ) { + int filled = this->Filled; + this->Filled = 0; + this->CreateCross(pts,lines,polys,colors,this->Scale2); + this->Filled = filled; + } + + //Call the right function + switch (this->GlyphType) { + case VTK_NO_GLYPH: + break; + case VTK_VERTEX_GLYPH: + this->CreateVertex(pts,verts,colors); + break; + case VTK_DASH_GLYPH: + this->CreateDash(pts,lines,polys,colors,this->Scale); + break; + case VTK_CROSS_GLYPH: + this->CreateCross(pts,lines,polys,colors,this->Scale); + break; + case VTK_THICKCROSS_GLYPH: + this->CreateThickCross(pts,lines,polys,colors); + break; + case VTK_TRIANGLE_GLYPH: + this->CreateTriangle(pts,lines,polys,colors); + break; + case VTK_SQUARE_GLYPH: + this->CreateSquare(pts,lines,polys,colors); + break; + case VTK_CIRCLE_GLYPH: + this->CreateCircle(pts,lines,polys,colors); + break; + case VTK_DIAMOND_GLYPH: + this->CreateDiamond(pts,lines,polys,colors); + break; + case VTK_ARROW_GLYPH: + this->CreateArrow(pts,lines,polys,colors); + break; + case VTK_THICKARROW_GLYPH: + this->CreateThickArrow(pts,lines,polys,colors); + break; + case VTK_HOOKEDARROW_GLYPH: + this->CreateHookedArrow(pts,lines,polys,colors); + break; + case VTK_EDGEARROW_GLYPH: + this->CreateEdgeArrow(pts,lines,polys,colors); + break; + case VTK_SPECIFICARROW_GLYPH: + this->CreateSpecificArrow(pts,lines,polys,colors); + break; + } + + this->TransformGlyph(pts); + + //Clean up + output->SetPoints(pts); + pts->Delete(); + + output->SetVerts(verts); + verts->Delete(); + + output->SetLines(lines); + lines->Delete(); + + output->SetPolys(polys); + polys->Delete(); + + output->GetCellData()->SetScalars(colors); + colors->Delete(); + + return 1; } void vvGlyphSource::CreateSpecificArrow(vtkPoints *pts, vtkCellArray *lines, vtkCellArray *polys, vtkUnsignedCharArray *colors) { - //stem - vtkIdType ptIds[3]; - ptIds[0] = pts->InsertNextPoint( 0.0, 0.0, 0.0); - ptIds[1] = pts->InsertNextPoint( 1.0, 0.0, 0.0); - lines->InsertNextCell(2,ptIds); - colors->InsertNextValue(0); - colors->InsertNextValue(0); - colors->InsertNextValue(1); - - //arrow head - ptIds[0] = pts->InsertNextPoint( 0.7, -0.1, 0.0); - ptIds[1] = pts->InsertNextPoint( 1.0, 0.0, 0.0); - ptIds[2] = pts->InsertNextPoint( 0.7, 0.1, 0.0); - lines->InsertNextCell(3,ptIds); - colors->InsertNextValue(0); - colors->InsertNextValue(1); - colors->InsertNextValue(0); + //stem + vtkIdType ptIds[3]; + ptIds[0] = pts->InsertNextPoint( 0.0, 0.0, 0.0); + ptIds[1] = pts->InsertNextPoint( 1.0, 0.0, 0.0); + lines->InsertNextCell(2,ptIds); + colors->InsertNextValue(0); + colors->InsertNextValue(0); + colors->InsertNextValue(1); + + //arrow head + ptIds[0] = pts->InsertNextPoint( 0.7, -0.1, 0.0); + ptIds[1] = pts->InsertNextPoint( 1.0, 0.0, 0.0); + ptIds[2] = pts->InsertNextPoint( 0.7, 0.1, 0.0); + lines->InsertNextCell(3,ptIds); + colors->InsertNextValue(0); + colors->InsertNextValue(1); + colors->InsertNextValue(0); } void vvGlyphSource::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os, indent); + this->Superclass::PrintSelf(os, indent); } diff --git a/vv/vvImageContour.cxx b/vv/vvImageContour.cxx index 0ffff62..56024c8 100644 --- a/vv/vvImageContour.cxx +++ b/vv/vvImageContour.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -28,7 +28,8 @@ #include //------------------------------------------------------------------------------ -vvImageContour::vvImageContour() { +vvImageContour::vvImageContour() +{ mTSlice = -1; mSlice = 0; mHiddenImageIsUsed = false; @@ -38,7 +39,8 @@ vvImageContour::vvImageContour() { //------------------------------------------------------------------------------ -vvImageContour::~vvImageContour() { +vvImageContour::~vvImageContour() +{ for (unsigned int i = 0; i < mSlicer->GetImage()->GetVTKImages().size(); i++) { mSlicer->GetRenderer()->RemoveActor(mSquaresActorList[i]); } @@ -50,8 +52,9 @@ vvImageContour::~vvImageContour() { //------------------------------------------------------------------------------ -void vvImageContour::setSlicer(vvSlicer * slicer) { - mSlicer = slicer; +void vvImageContour::setSlicer(vvSlicer * slicer) +{ + mSlicer = slicer; // Create an actor for each time slice for (unsigned int numImage = 0; numImage < mSlicer->GetImage()->GetVTKImages().size(); numImage++) { vtkImageClip * mClipper = vtkImageClip::New(); @@ -67,7 +70,8 @@ void vvImageContour::setSlicer(vvSlicer * slicer) { //------------------------------------------------------------------------------ -void vvImageContour::setImage(vvImage::Pointer image) { +void vvImageContour::setImage(vvImage::Pointer image) +{ for (unsigned int numImage = 0; numImage < image->GetVTKImages().size(); numImage++) { mClipperList[numImage]->SetInput(image->GetVTKImages()[numImage]); } @@ -78,15 +82,15 @@ void vvImageContour::setImage(vvImage::Pointer image) { //------------------------------------------------------------------------------ -void vvImageContour::setPreserveMemoryModeEnabled(bool b) { +void vvImageContour::setPreserveMemoryModeEnabled(bool b) +{ // FastCache mode work only if threshold is always the same if (mDisplayModeIsPreserveMemory == b) return; mDisplayModeIsPreserveMemory = b; if (!b) { hideActors(); initializeCacheMode(); - } - else { + } else { for(unsigned int d=0; dGetProperty()->SetColor(r,g,b); } @@ -106,7 +111,8 @@ void vvImageContour::setColor(double r, double g, double b) { //------------------------------------------------------------------------------ -void vvImageContour::SetLineWidth(double w) { +void vvImageContour::SetLineWidth(double w) +{ for(unsigned int i=0; iGetProperty()->SetLineWidth(w); } @@ -115,7 +121,8 @@ void vvImageContour::SetLineWidth(double w) { //------------------------------------------------------------------------------ -void vvImageContour::hideActors() { +void vvImageContour::hideActors() +{ if (!mSlicer) return; mSlice = mSlicer->GetSlice(); for(unsigned int i=0; iGetSlice(); mTSlice = mSlicer->GetTSlice(); @@ -137,15 +145,16 @@ void vvImageContour::showActors() { } //------------------------------------------------------------------------------ - + //------------------------------------------------------------------------------ -void vvImageContour::update(double value) { +void vvImageContour::update(double value) +{ // DD(value); if (!mSlicer) return; if (mPreviousValue == value) { if (mPreviousSlice == mSlicer->GetSlice()) { if (mPreviousTSlice == mSlicer->GetTSlice()) { - // DD("vvImageContour::update nothing"); + // DD("vvImageContour::update nothing"); return; // Nothing to do } } @@ -159,8 +168,7 @@ void vvImageContour::update(double value) { // DD(mDisplayModeIsPreserveMemory); if (mDisplayModeIsPreserveMemory) { updateWithPreserveMemoryMode(); - } - else { + } else { updateWithFastCacheMode(); } @@ -176,7 +184,8 @@ void vvImageContour::update(double value) { //------------------------------------------------------------------------------ -void vvImageContour::updateWithPreserveMemoryMode() { +void vvImageContour::updateWithPreserveMemoryMode() +{ // Only change actor visibility if tslice change //DD(mTSlice); //DD(mSlice); @@ -207,7 +216,8 @@ void vvImageContour::updateWithPreserveMemoryMode() { //------------------------------------------------------------------------------ -void vvImageContour::initializeCacheMode() { +void vvImageContour::initializeCacheMode() +{ mPreviousSlice = mPreviousOrientation = 0; int dim = mSlicer->GetImage()->GetNumberOfDimensions(); @@ -225,13 +235,14 @@ void vvImageContour::initializeCacheMode() { //------------------------------------------------------------------------------ -int vvImageContour::computeCurrentOrientation() { +int vvImageContour::computeCurrentOrientation() +{ // Get extent of image in the slicer int* extent = mSlicer->GetImageActor()->GetDisplayExtent(); - + // Compute orientation int orientation; - for (orientation = 0; orientation < 6;orientation = orientation+2) { + for (orientation = 0; orientation < 6; orientation = orientation+2) { if (extent[orientation] == extent[orientation+1]) { break; } @@ -243,7 +254,8 @@ int vvImageContour::computeCurrentOrientation() { //------------------------------------------------------------------------------ -void vvImageContour::updateWithFastCacheMode() { +void vvImageContour::updateWithFastCacheMode() +{ // Compute orientation int orientation = computeCurrentOrientation(); @@ -252,8 +264,7 @@ void vvImageContour::updateWithFastCacheMode() { vtkActor * actor = mListOfCachedContourActors[orientation][mSlice]; if (actor != NULL) { mListOfCachedContourActors[orientation][mSlice]->VisibilityOn(); - } - else { + } else { vtkImageClip * mClipper; vtkMarchingSquares * mSquares; vtkActor * mSquaresActor; @@ -272,18 +283,19 @@ void vvImageContour::updateWithFastCacheMode() { //------------------------------------------------------------------------------ -void vvImageContour::createNewActor(vtkActor ** actor, - vtkMarchingSquares ** squares, - vtkImageClip ** clipper, - int numImage) { +void vvImageContour::createNewActor(vtkActor ** actor, + vtkMarchingSquares ** squares, + vtkImageClip ** clipper, + int numImage) +{ vtkActor * mSquaresActor = (*actor = vtkActor::New()); vtkImageClip * mClipper = (*clipper = vtkImageClip::New()); vtkMarchingSquares * mSquares = (*squares = vtkMarchingSquares::New()); vtkPolyDataMapper * mSquaresMapper = vtkPolyDataMapper::New(); - - if (mHiddenImageIsUsed) + + if (mHiddenImageIsUsed) mClipper->SetInput(mHiddenImage->GetVTKImages()[0]); - else + else mClipper->SetInput(mSlicer->GetImage()->GetVTKImages()[numImage]); mSquares->SetInput(mClipper->GetOutput()); mSquaresMapper->SetInput(mSquares->GetOutput()); @@ -292,17 +304,18 @@ void vvImageContour::createNewActor(vtkActor ** actor, mSquaresActor->GetProperty()->SetColor(1.0,0,0); mSquaresActor->SetPickable(0); mSquaresActor->VisibilityOff(); - mSlicer->GetRenderer()->AddActor(mSquaresActor); + mSlicer->GetRenderer()->AddActor(mSquaresActor); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvImageContour::updateActor(vtkActor * actor, - vtkMarchingSquares * squares, - vtkImageClip * clipper, - double threshold, int orientation, int slice) { - +void vvImageContour::updateActor(vtkActor * actor, + vtkMarchingSquares * squares, + vtkImageClip * clipper, + double threshold, int orientation, int slice) +{ + // Set parameter for the MarchigSquare squares->SetValue(0, threshold); @@ -316,21 +329,19 @@ void vvImageContour::updateActor(vtkActor * actor, int * extent3; extent3 = mHiddenImage->GetFirstVTKImageData()->GetExtent(); for(int i=0; i<6; i++) extent2[i] = extent3[i]; - + double s = (double)extent[orientation*2]*(double)mSlicer->GetImage()->GetSpacing()[orientation]; // in mm s = s+mSlicer->GetImage()->GetOrigin()[orientation]; // from origin s = s-mHiddenImage->GetFirstVTKImageData()->GetOrigin()[orientation]; // from corner second image s = s/mHiddenImage->GetFirstVTKImageData()->GetSpacing()[orientation]; // in voxel - - if (s == floor(s)) { + + if (s == floor(s)) { extent2[orientation*2] = extent2[orientation*2+1] = (int)floor(s); - } - else { + } else { extent2[orientation*2] = (int)floor(s); extent2[orientation*2+1] = extent2[orientation*2]; } - } - else { + } else { extent2 = extent; } clipper->SetOutputWholeExtent(extent2[0],extent2[1],extent2[2], @@ -344,33 +355,30 @@ void vvImageContour::updateActor(vtkActor * actor, //TO SIMPLiFY :!!!!!!!!! == ??????? // actor->SetPosition(-1,-1,-1); - + switch (orientation) { - case 0: + case 0: // DD(mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[0]); if (mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[0] > slice) { actor->SetPosition(1,0,0); - } - else { + } else { actor->SetPosition(-1,0,0); } break; - case 1: + case 1: // DD(mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[1]); if (mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[1] > slice) { actor->SetPosition(0,1,0); - } - else { + } else { actor->SetPosition(0,-1,0); } break; - case 2: + case 2: // DD(mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[2]); if (mSlicer->GetRenderer()->GetActiveCamera()->GetPosition()[2] > slice) { // DD("1"); actor->SetPosition(0,0,1); - } - else { + } else { // DD("-1"); actor->SetPosition(0,0,-1); } diff --git a/vv/vvImageMapToWLColors.cxx b/vv/vvImageMapToWLColors.cxx index 2b51d79..9cc9f82 100644 --- a/vv/vvImageMapToWLColors.cxx +++ b/vv/vvImageMapToWLColors.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -29,13 +29,13 @@ vtkStandardNewMacro(vvImageMapToWLColors); vvImageMapToWLColors::vvImageMapToWLColors() : - wl_mode(false) + wl_mode(false) {} template -void vtkImageMapToWindowLevelClamps ( vtkImageData *data, double w, - double l, T& lower, T& upper, - unsigned char &lower_val, +void vtkImageMapToWindowLevelClamps ( vtkImageData *data, double w, + double l, T& lower, T& upper, + unsigned char &lower_val, unsigned char &upper_val) { double f_lower, f_upper, f_lower_val, f_upper_val; @@ -48,246 +48,199 @@ void vtkImageMapToWindowLevelClamps ( vtkImageData *data, double w, f_upper = f_lower + fabs(w); // Set the correct lower value - if ( f_lower <= range[1]) - { - if (f_lower >= range[0]) - { + if ( f_lower <= range[1]) { + if (f_lower >= range[0]) { lower = static_cast(f_lower); adjustedLower = f_lower; - } - else - { + } else { lower = static_cast(range[0]); adjustedLower = range[0]; - } } - else - { + } else { lower = static_cast(range[1]); adjustedLower = range[1]; - } - + } + // Set the correct upper value - if ( f_upper >= range[0]) - { - if (f_upper <= range[1]) - { + if ( f_upper >= range[0]) { + if (f_upper <= range[1]) { upper = static_cast(f_upper); adjustedUpper = f_upper; - } - else - { + } else { upper = static_cast(range[1]); adjustedUpper = range[1]; - } } - else - { + } else { upper = static_cast(range[0]); adjustedUpper = range [0]; - } - + } + // now compute the lower and upper values - if (w >= 0) - { + if (w >= 0) { f_lower_val = 255.0*(adjustedLower - f_lower)/w; f_upper_val = 255.0*(adjustedUpper - f_lower)/w; - } - else - { + } else { f_lower_val = 255.0 + 255.0*(adjustedLower - f_lower)/w; f_upper_val = 255.0 + 255.0*(adjustedUpper - f_lower)/w; - } - - if (f_upper_val > 255) - { + } + + if (f_upper_val > 255) { upper_val = 255; - } - else if (f_upper_val < 0) - { + } else if (f_upper_val < 0) { upper_val = 0; - } - else - { + } else { upper_val = static_cast(f_upper_val); - } - - if (f_lower_val > 255) - { + } + + if (f_lower_val > 255) { lower_val = 255; - } - else if (f_lower_val < 0) - { + } else if (f_lower_val < 0) { lower_val = 0; - } - else - { + } else { lower_val = static_cast(f_lower_val); - } + } } template void vvImageMapToWindowLevelColorsExecute( - vtkImageMapToWindowLevelColors *self, + vtkImageMapToWindowLevelColors *self, vtkImageData *inData, T *inPtr, - vtkImageData *outData, + vtkImageData *outData, unsigned char *outPtr, int outExt[6], int id, bool wl_mode) { - int idxX, idxY, idxZ; - int extX, extY, extZ; - vtkIdType inIncX, inIncY, inIncZ; - vtkIdType outIncX, outIncY, outIncZ; - unsigned long count = 0; - unsigned long target; - int dataType = inData->GetScalarType(); - int numberOfComponents,numberOfOutputComponents,outputFormat; - int rowLength; - vtkScalarsToColors *lookupTable = self->GetLookupTable(); - unsigned char *outPtr1; - T *inPtr1; - unsigned char *optr; - T *iptr; - double shift = self->GetWindow() / 2.0 - self->GetLevel(); - double scale = 255.0 / self->GetWindow(); + int idxX, idxY, idxZ; + int extX, extY, extZ; + vtkIdType inIncX, inIncY, inIncZ; + vtkIdType outIncX, outIncY, outIncZ; + unsigned long count = 0; + unsigned long target; + int dataType = inData->GetScalarType(); + int numberOfComponents,numberOfOutputComponents,outputFormat; + int rowLength; + vtkScalarsToColors *lookupTable = self->GetLookupTable(); + unsigned char *outPtr1; + T *inPtr1; + unsigned char *optr; + T *iptr; + double shift = self->GetWindow() / 2.0 - self->GetLevel(); + double scale = 255.0 / self->GetWindow(); - T lower, upper; - unsigned char lower_val, upper_val, result_val; - vtkImageMapToWindowLevelClamps( inData, self->GetWindow(), - self->GetLevel(), - lower, upper, lower_val, upper_val ); + T lower, upper; + unsigned char lower_val, upper_val, result_val; + vtkImageMapToWindowLevelClamps( inData, self->GetWindow(), + self->GetLevel(), + lower, upper, lower_val, upper_val ); - // find the region to loop over - extX = outExt[1] - outExt[0] + 1; - extY = outExt[3] - outExt[2] + 1; - extZ = outExt[5] - outExt[4] + 1; + // find the region to loop over + extX = outExt[1] - outExt[0] + 1; + extY = outExt[3] - outExt[2] + 1; + extZ = outExt[5] - outExt[4] + 1; - target = static_cast(extZ*extY/50.0); - target++; + target = static_cast(extZ*extY/50.0); + target++; - // Get increments to march through data - inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); + // Get increments to march through data + inData->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); - outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); - numberOfComponents = inData->GetNumberOfScalarComponents(); - numberOfOutputComponents = outData->GetNumberOfScalarComponents(); - outputFormat = self->GetOutputFormat(); + outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ); + numberOfComponents = inData->GetNumberOfScalarComponents(); + numberOfOutputComponents = outData->GetNumberOfScalarComponents(); + outputFormat = self->GetOutputFormat(); - rowLength = extX*numberOfComponents; + rowLength = extX*numberOfComponents; - // Loop through output pixels - outPtr1 = outPtr; - inPtr1 = inPtr; - for (idxZ = 0; idxZ < extZ; idxZ++) - { - for (idxY = 0; !self->AbortExecute && idxY < extY; idxY++) - { - if (!id) - { - if (!(count%target)) - { - self->UpdateProgress(count/(50.0*target)); - } - count++; - } + // Loop through output pixels + outPtr1 = outPtr; + inPtr1 = inPtr; + for (idxZ = 0; idxZ < extZ; idxZ++) { + for (idxY = 0; !self->AbortExecute && idxY < extY; idxY++) { + if (!id) { + if (!(count%target)) { + self->UpdateProgress(count/(50.0*target)); + } + count++; + } - iptr = inPtr1; - optr = outPtr1; + iptr = inPtr1; + optr = outPtr1; - if ( lookupTable ) - { - lookupTable->MapScalarsThroughTable2( - inPtr1, - static_cast(outPtr1), - dataType,extX,numberOfComponents, - outputFormat); - if (wl_mode) - { - unsigned short ushort_val; - for (idxX = 0; idxX < extX; idxX++) - { - if (*iptr <= lower) - { - ushort_val = lower_val; - } - else if (*iptr >= upper) - { - ushort_val = upper_val; - } - else - { - ushort_val = static_cast((*iptr + shift)*scale); - } - *optr = static_cast((*optr * ushort_val) >> 8); - switch (outputFormat) - { - case VTK_RGBA: - *(optr+1) = static_cast( - (*(optr+1) * ushort_val) >> 8); - *(optr+2) = static_cast( - (*(optr+2) * ushort_val) >> 8); - *(optr+3) = 255; - break; - case VTK_RGB: - *(optr+1) = static_cast( - (*(optr+1) * ushort_val) >> 8); - *(optr+2) = static_cast( - (*(optr+2) * ushort_val) >> 8); - break; - case VTK_LUMINANCE_ALPHA: - *(optr+1) = 255; - break; - } - iptr += numberOfComponents; - optr += numberOfOutputComponents; - } - } + if ( lookupTable ) { + lookupTable->MapScalarsThroughTable2( + inPtr1, + static_cast(outPtr1), + dataType,extX,numberOfComponents, + outputFormat); + if (wl_mode) { + unsigned short ushort_val; + for (idxX = 0; idxX < extX; idxX++) { + if (*iptr <= lower) { + ushort_val = lower_val; + } else if (*iptr >= upper) { + ushort_val = upper_val; + } else { + ushort_val = static_cast((*iptr + shift)*scale); } - else - { - for (idxX = 0; idxX < extX; idxX++) - { - if (*iptr <= lower) - { - result_val = lower_val; - } - else if (*iptr >= upper) - { - result_val = upper_val; - } - else - { - result_val = static_cast((*iptr + shift)*scale); - } - *optr = result_val; - switch (outputFormat) - { - case VTK_RGBA: - *(optr+1) = result_val; - *(optr+2) = result_val; - *(optr+3) = 255; - break; - case VTK_RGB: - *(optr+1) = result_val; - *(optr+2) = result_val; - break; - case VTK_LUMINANCE_ALPHA: - *(optr+1) = 255; - break; - } - iptr += numberOfComponents; - optr += numberOfOutputComponents; - } - } - outPtr1 += outIncY + extX*numberOfOutputComponents; - inPtr1 += inIncY + rowLength; + *optr = static_cast((*optr * ushort_val) >> 8); + switch (outputFormat) { + case VTK_RGBA: + *(optr+1) = static_cast( + (*(optr+1) * ushort_val) >> 8); + *(optr+2) = static_cast( + (*(optr+2) * ushort_val) >> 8); + *(optr+3) = 255; + break; + case VTK_RGB: + *(optr+1) = static_cast( + (*(optr+1) * ushort_val) >> 8); + *(optr+2) = static_cast( + (*(optr+2) * ushort_val) >> 8); + break; + case VTK_LUMINANCE_ALPHA: + *(optr+1) = 255; + break; + } + iptr += numberOfComponents; + optr += numberOfOutputComponents; + } + } + } else { + for (idxX = 0; idxX < extX; idxX++) { + if (*iptr <= lower) { + result_val = lower_val; + } else if (*iptr >= upper) { + result_val = upper_val; + } else { + result_val = static_cast((*iptr + shift)*scale); + } + *optr = result_val; + switch (outputFormat) { + case VTK_RGBA: + *(optr+1) = result_val; + *(optr+2) = result_val; + *(optr+3) = 255; + break; + case VTK_RGB: + *(optr+1) = result_val; + *(optr+2) = result_val; + break; + case VTK_LUMINANCE_ALPHA: + *(optr+1) = 255; + break; + } + iptr += numberOfComponents; + optr += numberOfOutputComponents; } - outPtr1 += outIncZ; - inPtr1 += inIncZ; + } + outPtr1 += outIncY + extX*numberOfOutputComponents; + inPtr1 += inIncY + rowLength; } + outPtr1 += outIncZ; + inPtr1 += inIncZ; + } } - - + + void vvImageMapToWLColors::ThreadedRequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), @@ -296,23 +249,22 @@ void vvImageMapToWLColors::ThreadedRequestData( vtkImageData **outData, int outExt[6], int id) { - void *inPtr = inData[0][0]->GetScalarPointerForExtent(outExt); - void *outPtr = outData[0]->GetScalarPointerForExtent(outExt); + void *inPtr = inData[0][0]->GetScalarPointerForExtent(outExt); + void *outPtr = outData[0]->GetScalarPointerForExtent(outExt); - switch (inData[0][0]->GetScalarType()) - { - vtkTemplateMacro( - vvImageMapToWindowLevelColorsExecute(this, - inData[0][0], - static_cast(inPtr), - outData[0], - static_cast(outPtr), - outExt, - id,wl_mode)); - default: - vtkErrorMacro(<< "Execute: Unknown ScalarType"); - return; - } + switch (inData[0][0]->GetScalarType()) { + vtkTemplateMacro( + vvImageMapToWindowLevelColorsExecute(this, + inData[0][0], + static_cast(inPtr), + outData[0], + static_cast(outPtr), + outExt, + id,wl_mode)); + default: + vtkErrorMacro(<< "Execute: Unknown ScalarType"); + return; + } } diff --git a/vv/vvImageReader.cxx b/vv/vvImageReader.cxx index 5c6eba3..e3e01a3 100644 --- a/vv/vvImageReader.cxx +++ b/vv/vvImageReader.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -53,8 +53,7 @@ void vvImageReader::Update(LoadedImageType type) itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO(mInputFilenames[0].c_str(), itk::ImageIOFactory::ReadMode); if (!reader) { mLastError="Unable to read file."; - } - else { + } else { reader->SetFileName(mInputFilenames[0]); reader->ReadImageInformation(); if (mInputFilenames.size() > 1) @@ -67,17 +66,17 @@ void vvImageReader::Update(LoadedImageType type) //------------------------------------------------------------------------------ -void vvImageReader::Update(int dim,std::string inputPixelType, LoadedImageType type) { +void vvImageReader::Update(int dim,std::string inputPixelType, LoadedImageType type) +{ //CALL_FOR_ALL_DIMS(dim,UpdateWithDim,inputPixelType); mType = type; mDim = dim; mInputPixelType=inputPixelType; this->start(); //Start heavy read operation in a separate thread - while (this->isRunning()) - { - qApp->processEvents(); - this->wait(50); - } + while (this->isRunning()) { + qApp->processEvents(); + this->wait(50); + } } //------------------------------------------------------------------------------ @@ -112,7 +111,8 @@ void vvImageReader::SetInputFilename(const std::string & filename) //------------------------------------------------------------------------------ -void vvImageReader::SetInputFilenames(const std::vector & filenames) { +void vvImageReader::SetInputFilenames(const std::vector & filenames) +{ mInputFilenames = filenames; } //------------------------------------------------------------------------------ @@ -122,35 +122,34 @@ void vvImageReader::SetInputFilenames(const std::vector & filenames //Read transformation in NKI format (Xdr, transposed, cm) void vvImageReader::ReadNkiImageTransform() { - bool bRead=true; - typedef itk::ImageFileReader< itk::Image< double, 2 > > MatrixReaderType; - MatrixReaderType::Pointer readerTransfo = MatrixReaderType::New(); - readerTransfo->SetFileName(mInputFilenames[0]+".MACHINEORIENTATION"); - try - { readerTransfo->Update(); - } - catch( itk::ExceptionObject & err ) - { bRead=false; - } - - if (bRead) - { double mat[16]; - - //Transpose matrix (NKI format) - for(int j=0; j<4; j++) - for(int i=0; i<4; i++) - mat[4*j+i]=readerTransfo->GetOutput()->GetBufferPointer()[4*i+j]; - - //From cm to mm - for(int i=0; i<3; i++) - mat[4*i+3]*=10; - - //Set Transformation - vtkSmartPointer pt = vtkSmartPointer::New(); - pt->SetMatrix( mat ); - pt->Inverse(); - mImage->SetTransform( pt ); - } + bool bRead=true; + typedef itk::ImageFileReader< itk::Image< double, 2 > > MatrixReaderType; + MatrixReaderType::Pointer readerTransfo = MatrixReaderType::New(); + readerTransfo->SetFileName(mInputFilenames[0]+".MACHINEORIENTATION"); + try { + readerTransfo->Update(); + } catch( itk::ExceptionObject & err ) { + bRead=false; + } + + if (bRead) { + double mat[16]; + + //Transpose matrix (NKI format) + for(int j=0; j<4; j++) + for(int i=0; i<4; i++) + mat[4*j+i]=readerTransfo->GetOutput()->GetBufferPointer()[4*i+j]; + + //From cm to mm + for(int i=0; i<3; i++) + mat[4*i+3]*=10; + + //Set Transformation + vtkSmartPointer pt = vtkSmartPointer::New(); + pt->SetMatrix( mat ); + pt->Inverse(); + mImage->SetTransform( pt ); + } } //------------------------------------------------------------------------------ #endif diff --git a/vv/vvImageReader.txx b/vv/vvImageReader.txx index b6539b8..dde83af 100644 --- a/vv/vvImageReader.txx +++ b/vv/vvImageReader.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -32,7 +32,8 @@ //---------------------------------------------------------------------------- template -void vvImageReader::UpdateWithDim(std::string InputPixelType) { +void vvImageReader::UpdateWithDim(std::string InputPixelType) +{ if (mType == VECTORFIELD) UpdateWithDimAndInputPixelType,VImageDimension>(); else if (InputPixelType == "short") @@ -61,118 +62,109 @@ void vvImageReader::UpdateWithDim(std::string InputPixelType) { //---------------------------------------------------------------------------- template -void vvImageReader::UpdateWithDimAndInputPixelType() { +void vvImageReader::UpdateWithDimAndInputPixelType() +{ // DD(mType); if (mType == MERGEDWITHTIME) // In this case we can load the images // one at the time to avoid excessive // memory use - { - typedef itk::Image< InputPixelType, VImageDimension-1 > InputImageType; + { + typedef itk::Image< InputPixelType, VImageDimension-1 > InputImageType; + typedef itk::ImageFileReader ReaderType; + typename ReaderType::Pointer reader = ReaderType::New(); + typedef itk::ImageToVTKImageFilter ConnectorType; + typename ConnectorType::Pointer connector = ConnectorType::New(); + connector->SetInput(reader->GetOutput()); + mImage=vvImage::New(); + for (std::vector::const_iterator i=mInputFilenames.begin(); i!=mInputFilenames.end(); i++) { + std::cout << (*i) << std::endl; + reader->SetFileName(*i); + try { + reader->Update(); + } catch ( itk::ExceptionObject & err ) { + std::cerr << "Error while reading " << mInputFilenames[0].c_str() + << " " << err << std::endl; + std::stringstream error; + error << err; + mLastError = error.str(); + return; + } + try { + connector->Update(); + } catch ( itk::ExceptionObject & err ) { + std::cerr << "Error while setting vvImage from ITK (MERGEDWITHTIME)" + << " " << err << std::endl; + } + vtkImageData *image = vtkImageData::New(); + image->DeepCopy(connector->GetOutput()); + mImage->AddImage(image); + } + } else { + if (mInputFilenames.size() > 1) { + typedef itk::Image< InputPixelType, VImageDimension > InputImageType; + typedef itk::ImageSeriesReader ReaderType; + typename ReaderType::Pointer reader = ReaderType::New(); + for (std::vector::const_iterator i=mInputFilenames.begin(); i!=mInputFilenames.end(); i++) + std::cout << (*i) << std::endl; + reader->SetFileNames(mInputFilenames); + //if (mUseAnObserver) { + //reader->AddObserver(itk::ProgressEvent(), mObserver); + //} + try { + reader->Update(); + } catch ( itk::ExceptionObject & err ) { + std::cerr << "Error while reading image series:" << err << std::endl; + std::stringstream error; + error << err; + mLastError = error.str(); + return; + } + + // DD(reader->GetOutput()->GetImageDimension()); + // DD(reader->GetOutput()->GetNumberOfComponentsPerPixel()); + // for(unsigned int i=0; i GetOutput()->GetImageDimension(); i++) { + // DD(reader->GetOutput()->GetSpacing()[i]); + // } + + if (mType == IMAGEWITHTIME) + mImage=vvImageFromITK(reader->GetOutput(),true); + else + mImage=vvImageFromITK(reader->GetOutput()); + } else { + typedef itk::Image< InputPixelType, VImageDimension > InputImageType; typedef itk::ImageFileReader ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); - typedef itk::ImageToVTKImageFilter ConnectorType; - typename ConnectorType::Pointer connector = ConnectorType::New(); - connector->SetInput(reader->GetOutput()); - mImage=vvImage::New(); - for (std::vector::const_iterator i=mInputFilenames.begin();i!=mInputFilenames.end();i++) - { - std::cout << (*i) << std::endl; - reader->SetFileName(*i); - try { - reader->Update(); - } - catch ( itk::ExceptionObject & err ) { - std::cerr << "Error while reading " << mInputFilenames[0].c_str() - << " " << err << std::endl; - std::stringstream error; - error << err; - mLastError = error.str(); - return; - } - try { - connector->Update(); - } - catch ( itk::ExceptionObject & err ) { - std::cerr << "Error while setting vvImage from ITK (MERGEDWITHTIME)" - << " " << err << std::endl; - } - vtkImageData *image = vtkImageData::New(); - image->DeepCopy(connector->GetOutput()); - mImage->AddImage(image); - } - } - else - { - if (mInputFilenames.size() > 1) - { - typedef itk::Image< InputPixelType, VImageDimension > InputImageType; - typedef itk::ImageSeriesReader ReaderType; - typename ReaderType::Pointer reader = ReaderType::New(); - for (std::vector::const_iterator i=mInputFilenames.begin();i!=mInputFilenames.end();i++) - std::cout << (*i) << std::endl; - reader->SetFileNames(mInputFilenames); - //if (mUseAnObserver) { - //reader->AddObserver(itk::ProgressEvent(), mObserver); - //} - try { - reader->Update(); - } - catch ( itk::ExceptionObject & err ) { - std::cerr << "Error while reading image series:" << err << std::endl; - std::stringstream error; - error << err; - mLastError = error.str(); - return; - } - - // DD(reader->GetOutput()->GetImageDimension()); - // DD(reader->GetOutput()->GetNumberOfComponentsPerPixel()); - // for(unsigned int i=0; i GetOutput()->GetImageDimension(); i++) { - // DD(reader->GetOutput()->GetSpacing()[i]); - // } - - if (mType == IMAGEWITHTIME) - mImage=vvImageFromITK(reader->GetOutput(),true); - else - mImage=vvImageFromITK(reader->GetOutput()); - } + reader->SetFileName(mInputFilenames[0]); + //if (mUseAnObserver) { + //reader->AddObserver(itk::ProgressEvent(), mObserver); + //} + try { + reader->Update(); + } catch ( itk::ExceptionObject & err ) { + std::cerr << "Error while reading " << mInputFilenames[0].c_str() + << " " << err << std::endl; + std::stringstream error; + error << err; + mLastError = error.str(); + return; + } + + // DD(reader->GetOutput()->GetImageDimension()); + // DD(reader->GetOutput()->GetNumberOfComponentsPerPixel()); + // for(unsigned int i=0; i GetOutput()->GetImageDimension(); i++) { + // DD(reader->GetOutput()->GetSpacing()[i]); + // DD(reader->GetOutput()->GetOrigin()[i]); + // } + + + if (mType == IMAGEWITHTIME) + mImage=vvImageFromITK(reader->GetOutput(),true); else - { - typedef itk::Image< InputPixelType, VImageDimension > InputImageType; - typedef itk::ImageFileReader ReaderType; - typename ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(mInputFilenames[0]); - //if (mUseAnObserver) { - //reader->AddObserver(itk::ProgressEvent(), mObserver); - //} - try { - reader->Update(); - } - catch ( itk::ExceptionObject & err ) { - std::cerr << "Error while reading " << mInputFilenames[0].c_str() - << " " << err << std::endl; - std::stringstream error; - error << err; - mLastError = error.str(); - return; - } - - // DD(reader->GetOutput()->GetImageDimension()); - // DD(reader->GetOutput()->GetNumberOfComponentsPerPixel()); - // for(unsigned int i=0; i GetOutput()->GetImageDimension(); i++) { - // DD(reader->GetOutput()->GetSpacing()[i]); - // DD(reader->GetOutput()->GetOrigin()[i]); - // } - - - if (mType == IMAGEWITHTIME) - mImage=vvImageFromITK(reader->GetOutput(),true); - else - mImage=vvImageFromITK(reader->GetOutput()); - } + mImage=vvImageFromITK(reader->GetOutput()); } + } } //---------------------------------------------------------------------------- diff --git a/vv/vvImageWarp.cxx b/vv/vvImageWarp.cxx index caa776b..1fd6778 100644 --- a/vv/vvImageWarp.cxx +++ b/vv/vvImageWarp.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,123 +31,121 @@ //==================================================================== vvImageWarp::vvImageWarp(vvImage::Pointer input,vvImage::Pointer vf,unsigned int ref_image,QWidget* parent): - mRefImage(ref_image), - parent_window(parent), - mInputImage(input), - mVF(vf) + mRefImage(ref_image), + parent_window(parent), + mInputImage(input), + mVF(vf) {} //==================================================================== template -void vvImageWarp::Update_WithDim() { +void vvImageWarp::Update_WithDim() +{ #define TRY_TYPE(TYPE) \ if (clitk::IsSameType(mInputImage->GetScalarTypeAsString())) { this->Update_WithDimAndPixelType(); return; } // TRY_TYPE(signed char); // TRY_TYPE(uchar); - TRY_TYPE(short); + TRY_TYPE(short); // TRY_TYPE(ushort); // TRY_TYPE(int); // no uint ... // TRY_TYPE(float); - //TRY_TYPE(double); + //TRY_TYPE(double); #undef TRY_TYPE - std::string list = clitk::CreateListOfTypes(); - std::cerr << "Error, I don't know the type '" << mInputImage->GetScalarTypeAsString() << "' for the input image. " - << std::endl << "Known types are " << list << std::endl; - exit(0); + std::string list = clitk::CreateListOfTypes(); + std::cerr << "Error, I don't know the type '" << mInputImage->GetScalarTypeAsString() << "' for the input image. " + << std::endl << "Known types are " << list << std::endl; + exit(0); } //==================================================================== template -void vvImageWarp::Update_WithDimAndPixelType() { - QProgressDialog progress(parent_window); - progress.setCancelButton(0); - progress.setLabelText("Computing warped and ventilation images..."); - progress.show(); - typedef itk::Image ImageType; - typedef itk::Image JacobianImageType; - typedef itk::Image,Dim> VectorImageType; - typedef std::vector ImageSeriesType; - ImageSeriesType input = vvImageToITKImageVector(mInputImage); - ImageSeriesType output; +void vvImageWarp::Update_WithDimAndPixelType() +{ + QProgressDialog progress(parent_window); + progress.setCancelButton(0); + progress.setLabelText("Computing warped and ventilation images..."); + progress.show(); + typedef itk::Image ImageType; + typedef itk::Image JacobianImageType; + typedef itk::Image,Dim> VectorImageType; + typedef std::vector ImageSeriesType; + ImageSeriesType input = vvImageToITKImageVector(mInputImage); + ImageSeriesType output; - typename itk::VTKImageToImageFilter::Pointer vf_connector= - itk::VTKImageToImageFilter::New(); + typename itk::VTKImageToImageFilter::Pointer vf_connector= + itk::VTKImageToImageFilter::New(); - //Warp, then join, then convert to vv - typedef itk::WarpImageFilter WarpFilterType; - typedef itk::DisplacementFieldJacobianDeterminantFilter JacobianFilterType; - vvImage::Pointer result=vvImage::New(); - typedef itk::JoinSeriesImageFilter< ImageType,itk::Image > JoinFilterType; - typedef itk::JoinSeriesImageFilter< JacobianImageType,itk::Image > JacobianJoinFilterType; - typename JoinFilterType::Pointer join=JoinFilterType::New(); - typename JoinFilterType::Pointer diff_join=JoinFilterType::New(); - typename JacobianJoinFilterType::Pointer jacobian_join=JacobianJoinFilterType::New(); - join->SetSpacing(1); - join->SetOrigin(0); //Set the temporal origin - diff_join->SetSpacing(1); - diff_join->SetOrigin(0); - jacobian_join->SetSpacing(1); - jacobian_join->SetOrigin(0); - typedef itk::SubtractImageFilter DiffFilter; - std::vector warped_images; + //Warp, then join, then convert to vv + typedef itk::WarpImageFilter WarpFilterType; + typedef itk::DisplacementFieldJacobianDeterminantFilter JacobianFilterType; + vvImage::Pointer result=vvImage::New(); + typedef itk::JoinSeriesImageFilter< ImageType,itk::Image > JoinFilterType; + typedef itk::JoinSeriesImageFilter< JacobianImageType,itk::Image > JacobianJoinFilterType; + typename JoinFilterType::Pointer join=JoinFilterType::New(); + typename JoinFilterType::Pointer diff_join=JoinFilterType::New(); + typename JacobianJoinFilterType::Pointer jacobian_join=JacobianJoinFilterType::New(); + join->SetSpacing(1); + join->SetOrigin(0); //Set the temporal origin + diff_join->SetSpacing(1); + diff_join->SetOrigin(0); + jacobian_join->SetSpacing(1); + jacobian_join->SetOrigin(0); + typedef itk::SubtractImageFilter DiffFilter; + std::vector warped_images; - for (unsigned int num = 0; num < input.size(); num++) - { - typename WarpFilterType::Pointer warp_filter=WarpFilterType::New(); - typename JacobianFilterType::Pointer jacobian_filter=JacobianFilterType::New(); - jacobian_filter->SetUseImageSpacingOn(); - vf_connector->SetInput(mVF->GetVTKImages()[num]); - warp_filter->SetInput(input[num]); - warp_filter->SetDeformationField(vf_connector->GetOutput()); - jacobian_filter->SetInput(vf_connector->GetOutput()); - warp_filter->SetOutputSpacing(input[num]->GetSpacing()); - warp_filter->SetOutputOrigin(input[num]->GetOrigin()); - warp_filter->SetEdgePaddingValue(-1000); - warp_filter->Update(); - jacobian_filter->Update(); - warped_images.push_back(warp_filter->GetOutput()); - jacobian_join->PushBackInput(jacobian_filter->GetOutput()); - join->PushBackInput(warp_filter->GetOutput()); - progress.setValue(progress.value()+1); - } - for (typename std::vector::const_iterator i = warped_images.begin(); i!=warped_images.end();i++) - { - typename DiffFilter::Pointer diff_filter = DiffFilter::New(); - diff_filter->SetInput2(*i); - diff_filter->SetInput1(*(warped_images.begin()+mRefImage)); - diff_filter->Update(); - diff_join->PushBackInput(diff_filter->GetOutput()); - progress.setValue(progress.value()+1); - } - join->Update(); - diff_join->Update(); - jacobian_join->Update(); - mWarpedImage = vvImageFromITK(join->GetOutput()); - mDiffImage = vvImageFromITK(diff_join->GetOutput()); - mJacobianImage = vvImageFromITK(jacobian_join->GetOutput()); - //mJacobianImage = vvImageFromITK(temporal_filter->GetOutput()); + for (unsigned int num = 0; num < input.size(); num++) { + typename WarpFilterType::Pointer warp_filter=WarpFilterType::New(); + typename JacobianFilterType::Pointer jacobian_filter=JacobianFilterType::New(); + jacobian_filter->SetUseImageSpacingOn(); + vf_connector->SetInput(mVF->GetVTKImages()[num]); + warp_filter->SetInput(input[num]); + warp_filter->SetDeformationField(vf_connector->GetOutput()); + jacobian_filter->SetInput(vf_connector->GetOutput()); + warp_filter->SetOutputSpacing(input[num]->GetSpacing()); + warp_filter->SetOutputOrigin(input[num]->GetOrigin()); + warp_filter->SetEdgePaddingValue(-1000); + warp_filter->Update(); + jacobian_filter->Update(); + warped_images.push_back(warp_filter->GetOutput()); + jacobian_join->PushBackInput(jacobian_filter->GetOutput()); + join->PushBackInput(warp_filter->GetOutput()); + progress.setValue(progress.value()+1); + } + for (typename std::vector::const_iterator i = warped_images.begin(); i!=warped_images.end(); i++) { + typename DiffFilter::Pointer diff_filter = DiffFilter::New(); + diff_filter->SetInput2(*i); + diff_filter->SetInput1(*(warped_images.begin()+mRefImage)); + diff_filter->Update(); + diff_join->PushBackInput(diff_filter->GetOutput()); + progress.setValue(progress.value()+1); + } + join->Update(); + diff_join->Update(); + jacobian_join->Update(); + mWarpedImage = vvImageFromITK(join->GetOutput()); + mDiffImage = vvImageFromITK(diff_join->GetOutput()); + mJacobianImage = vvImageFromITK(jacobian_join->GetOutput()); + //mJacobianImage = vvImageFromITK(temporal_filter->GetOutput()); } //==================================================================== // bool vvImageWarp::ComputeWarpedImage() { - for (int i=0;iGetNumberOfDimensions();i++) - { - if (mInputImage->GetSpacing()[i] != mVF->GetSpacing()[i]) - return false; - } - switch (mInputImage->GetNumberOfDimensions()) - { + for (int i=0; iGetNumberOfDimensions(); i++) { + if (mInputImage->GetSpacing()[i] != mVF->GetSpacing()[i]) + return false; + } + switch (mInputImage->GetNumberOfDimensions()) { // case 2: this->Update_WithDim<2>(); break;; // case 3: this->Update_WithDim<3>(); break;; - case 4: - this->Update_WithDim<3>(); - break;; - default: - DD("Error: dimension not handled."); - } - return true; + case 4: + this->Update_WithDim<3>(); + break;; + default: + DD("Error: dimension not handled."); + } + return true; } diff --git a/vv/vvImageWriter.cxx b/vv/vvImageWriter.cxx index e5fc2d6..7c09c35 100644 --- a/vv/vvImageWriter.cxx +++ b/vv/vvImageWriter.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,36 +22,40 @@ #include //==================================================================== -vvImageWriter::vvImageWriter() { - mImage = NULL; - mOutputFilename = ""; - mLastError = ""; - mUseAnObserver = false; +vvImageWriter::vvImageWriter() +{ + mImage = NULL; + mOutputFilename = ""; + mLastError = ""; + mUseAnObserver = false; } //==================================================================== //==================================================================== -vvImageWriter::~vvImageWriter() { +vvImageWriter::~vvImageWriter() +{ } //==================================================================== //==================================================================== -void vvImageWriter::Update(int dim,std::string OutputPixelType) { - //CALL_FOR_ALL_DIMS(dim,UpdateWithDim,inputPixelType); - if (dim == 2) - UpdateWithDim<2>(OutputPixelType); - else if (dim == 3) - UpdateWithDim<3>(OutputPixelType); - else if (dim == 4) - UpdateWithDim<4>(OutputPixelType); - else - std::cerr << "dim not know in Update ! " << std::endl; +void vvImageWriter::Update(int dim,std::string OutputPixelType) +{ + //CALL_FOR_ALL_DIMS(dim,UpdateWithDim,inputPixelType); + if (dim == 2) + UpdateWithDim<2>(OutputPixelType); + else if (dim == 3) + UpdateWithDim<3>(OutputPixelType); + else if (dim == 4) + UpdateWithDim<4>(OutputPixelType); + else + std::cerr << "dim not know in Update ! " << std::endl; } //==================================================================== //==================================================================== -void vvImageWriter::SetOutputFileName(std::string filename) { - mOutputFilename = filename; +void vvImageWriter::SetOutputFileName(std::string filename) +{ + mOutputFilename = filename; } //==================================================================== diff --git a/vv/vvImageWriter.txx b/vv/vvImageWriter.txx index a62578f..dc07874 100644 --- a/vv/vvImageWriter.txx +++ b/vv/vvImageWriter.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -24,42 +24,25 @@ template void vvImageWriter::UpdateWithDim(std::string OutputPixelType) { - if (OutputPixelType == "short") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "unsigned short") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "unsigned_short") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "char") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "unsigned_char") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "int") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "double") - { - UpdateWithDimAndOutputPixelType(); - } - else if (OutputPixelType == "float") - { - UpdateWithDimAndOutputPixelType(); - } - else - { - std::cerr << "Error, output pixel type : \"" << OutputPixelType << "\" unknown !" << std::endl; - } + if (OutputPixelType == "short") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "unsigned short") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "unsigned_short") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "char") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "unsigned_char") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "int") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "double") { + UpdateWithDimAndOutputPixelType(); + } else if (OutputPixelType == "float") { + UpdateWithDimAndOutputPixelType(); + } else { + std::cerr << "Error, output pixel type : \"" << OutputPixelType << "\" unknown !" << std::endl; + } } //==================================================================== @@ -67,26 +50,25 @@ void vvImageWriter::UpdateWithDim(std::string OutputPixelType) template void vvImageWriter::UpdateWithDimAndOutputPixelType() { - //Create the writer - typedef itk::Image< OutputPixelType, VImageDimension > OutputImageType; - typedef itk::ImageFileWriter WriterType; - typename WriterType::Pointer writer = WriterType::New(); - writer->SetFileName(mOutputFilename); - writer->SetInput(vvImageToITK(mImage)); - if (mUseAnObserver) { - writer->AddObserver(itk::ProgressEvent(), mObserver); - } - try { - writer->Update(); - } - catch ( itk::ExceptionObject & err ) { - std::cerr << "Error while reading " << mOutputFilename.c_str() - << " " << err << std::endl; - std::stringstream error; - error << err; - mLastError = error.str(); - return; - } + //Create the writer + typedef itk::Image< OutputPixelType, VImageDimension > OutputImageType; + typedef itk::ImageFileWriter WriterType; + typename WriterType::Pointer writer = WriterType::New(); + writer->SetFileName(mOutputFilename); + writer->SetInput(vvImageToITK(mImage)); + if (mUseAnObserver) { + writer->AddObserver(itk::ProgressEvent(), mObserver); + } + try { + writer->Update(); + } catch ( itk::ExceptionObject & err ) { + std::cerr << "Error while reading " << mOutputFilename.c_str() + << " " << err << std::endl; + std::stringstream error; + error << err; + mLastError = error.str(); + return; + } } //==================================================================== diff --git a/vv/vvInfoPanel.cxx b/vv/vvInfoPanel.cxx index e496b7c..33564b3 100644 --- a/vv/vvInfoPanel.cxx +++ b/vv/vvInfoPanel.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,119 +22,106 @@ void vvInfoPanel::setFileName(QString text) { - if (text.size() > 30) - imageLabel->setText("..." + text.right(27)); - else - imageLabel->setText(text); + if (text.size() > 30) + imageLabel->setText("..." + text.right(27)); + else + imageLabel->setText(text); } void vvInfoPanel::setDimension(QString text) { - dimensionLabel->setText(text); + dimensionLabel->setText(text); } void vvInfoPanel::setSizeMM(QString text) { - sizeMMLabel->setText(text); + sizeMMLabel->setText(text); } void vvInfoPanel::setNPixel(QString text) { - nPixelLabel->setText(text); + nPixelLabel->setText(text); } void vvInfoPanel::setSizePixel(QString text) { - sizePixelLabel->setText(text); + sizePixelLabel->setText(text); } void vvInfoPanel::setOrigin(QString text) { - originLabel->setText(text); + originLabel->setText(text); } void vvInfoPanel::setSpacing(QString text) { - spacingLabel->setText(text); + spacingLabel->setText(text); } void vvInfoPanel::setCurrentInfo(int visibility, double x, double y, double z, double X, double Y, double Z, double value) { - QString world = ""; - QString mouse = ""; - QString val = ""; - if (visibility) - { - world += QString::number(x,'f',1) + " "; - world += QString::number(y,'f',1) + " "; - world += QString::number(z,'f',1) + " "; - - mouse += QString::number(X,'f',1) + " "; - mouse += QString::number(Y,'f',1) + " "; - mouse += QString::number(Z,'f',1) + " "; - - val += QString::number(value); - } - worldPosLabel->setText(world); - pixelPosLabel->setText(mouse); - valueLabel->setText(val); + QString world = ""; + QString mouse = ""; + QString val = ""; + if (visibility) { + world += QString::number(x,'f',1) + " "; + world += QString::number(y,'f',1) + " "; + world += QString::number(z,'f',1) + " "; + + mouse += QString::number(X,'f',1) + " "; + mouse += QString::number(Y,'f',1) + " "; + mouse += QString::number(Z,'f',1) + " "; + + val += QString::number(value); + } + worldPosLabel->setText(world); + pixelPosLabel->setText(mouse); + valueLabel->setText(val); } void vvInfoPanel::setViews(int window, int view, int slice) { - QString viewString; - switch (view) - { - case 0: - { - viewString = "Sagital, "; - break; - } - case 1: - { - viewString = "Coronal, "; - break; - } - case 2: - { - viewString = "Axial, "; - break; - } - } - - QString text = viewString; - if (view != -1) - { - text += "current slice : "; - text += QString::number(slice); - } - else - { - text = "Disable"; - } - - switch (window) - { - case 0: - { - ULLabel->setText(text); - break; - } - case 1: - { - URLabel->setText(text); - break; - } - case 2: - { - DLLabel->setText(text); - break; - } - case 3: - { - DRLabel->setText(text); - break; - } - } + QString viewString; + switch (view) { + case 0: { + viewString = "Sagital, "; + break; + } + case 1: { + viewString = "Coronal, "; + break; + } + case 2: { + viewString = "Axial, "; + break; + } + } + + QString text = viewString; + if (view != -1) { + text += "current slice : "; + text += QString::number(slice); + } else { + text = "Disable"; + } + + switch (window) { + case 0: { + ULLabel->setText(text); + break; + } + case 1: { + URLabel->setText(text); + break; + } + case 2: { + DLLabel->setText(text); + break; + } + case 3: { + DRLabel->setText(text); + break; + } + } } diff --git a/vv/vvInit.cxx b/vv/vvInit.cxx index a71125a..a559bce 100644 --- a/vv/vvInit.cxx +++ b/vv/vvInit.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -29,8 +29,8 @@ void initialize_IO() { - itk::ImageIOFactory::RegisterBuiltInFactories(); - clitk::VoxImageIOFactory::RegisterOneFactory(); - clitk::VfImageIOFactory::RegisterOneFactory(); - nkitk::XDRImageIOFactory::RegisterOneFactory(); + itk::ImageIOFactory::RegisterBuiltInFactories(); + clitk::VoxImageIOFactory::RegisterOneFactory(); + clitk::VfImageIOFactory::RegisterOneFactory(); + nkitk::XDRImageIOFactory::RegisterOneFactory(); } diff --git a/vv/vvIntensityValueSlider.cxx b/vv/vvIntensityValueSlider.cxx index 8f2ee2c..156efe5 100644 --- a/vv/vvIntensityValueSlider.cxx +++ b/vv/vvIntensityValueSlider.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -19,14 +19,14 @@ //------------------------------------------------------------------------------ vvIntensityValueSlider::vvIntensityValueSlider(QWidget * parent, Qt::WindowFlags f) - :QWidget(parent,f), Ui::vvIntensityValueSlider() + :QWidget(parent,f), Ui::vvIntensityValueSlider() { // GUI Initialization - setupUi(this); + setupUi(this); mIsInteger = true; mButtonPlus->setHidden(true); mButtonMinus->setHidden(true); - + // Connect signals & slots connect(mSpinBox, SIGNAL(valueChanged(double)), this, SLOT(valueChangedFromSpinBox(double))); connect(mSlider, SIGNAL(valueChanged(int)), this, SLOT(valueChangedFromSlider(int))); @@ -37,13 +37,15 @@ vvIntensityValueSlider::vvIntensityValueSlider(QWidget * parent, Qt::WindowFlags //------------------------------------------------------------------------------ -vvIntensityValueSlider::~vvIntensityValueSlider() { +vvIntensityValueSlider::~vvIntensityValueSlider() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SingleStepMinusClicked() { +void vvIntensityValueSlider::SingleStepMinusClicked() +{ mSpinBox->setSingleStep(mSpinBox->singleStep()*10); mSpinBox->setDecimals(mSpinBox->decimals()-1); } @@ -51,14 +53,16 @@ void vvIntensityValueSlider::SingleStepMinusClicked() { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SetSingleStep(double step) { +void vvIntensityValueSlider::SetSingleStep(double step) +{ mSpinBox->setSingleStep(step); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SingleStepPlusClicked() { +void vvIntensityValueSlider::SingleStepPlusClicked() +{ mSpinBox->setSingleStep(mSpinBox->singleStep()/10); mSpinBox->setDecimals(mSpinBox->decimals()+1); } @@ -66,15 +70,15 @@ void vvIntensityValueSlider::SingleStepPlusClicked() { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::valueChangedFromSpinBox(double v) { +void vvIntensityValueSlider::valueChangedFromSpinBox(double v) +{ if (v == mValue) return; mSpinBox->setValue(v); v = mSpinBox->value(); // this is needed to 'round' value according to spinBox precision double vv; if (!mIsInteger) { vv = ((v-mMin)/mWidth)/mSliderFactor; - } - else vv = v; + } else vv = v; mSlider->setValue(vv); mValue = v; emit valueChanged(v); @@ -83,12 +87,12 @@ void vvIntensityValueSlider::valueChangedFromSpinBox(double v) { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::valueChangedFromSlider(int vv) { +void vvIntensityValueSlider::valueChangedFromSlider(int vv) +{ double v; if (!mIsInteger) { v = ((double)vv*mSliderFactor)*mWidth+mMin; - } - else v= vv; + } else v= vv; // arrondir ! ? @@ -100,22 +104,25 @@ void vvIntensityValueSlider::valueChangedFromSlider(int vv) { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SetText(QString t) { +void vvIntensityValueSlider::SetText(QString t) +{ mLabel->setText(t); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SetImage(vvImage * im) { - mImage = im; - Update(); +void vvIntensityValueSlider::SetImage(vvImage * im) +{ + mImage = im; + Update(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SetValue(double v) { +void vvIntensityValueSlider::SetValue(double v) +{ mValue = v; mSpinBox->setValue(v); } @@ -123,20 +130,22 @@ void vvIntensityValueSlider::SetValue(double v) { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SetMaximum(double max) { +void vvIntensityValueSlider::SetMaximum(double max) +{ mMax = max; mSpinBox->setMaximum(max); - + // If integer values : update slider max if (mIsInteger == 1) { mSlider->setMaximum(max); - } - else { + } else { double step = mWidth/1000.0; mSpinBox->setSingleStep(step); mWidth = mMax-mMin; } - if (mValue > max) { SetValue(max); } + if (mValue > max) { + SetValue(max); + } QString tip = QString("Min = %1 Max = %2").arg(mSpinBox->minimum()).arg(max); setToolTip(tip); } @@ -144,20 +153,22 @@ void vvIntensityValueSlider::SetMaximum(double max) { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::SetMinimum(double min) { +void vvIntensityValueSlider::SetMinimum(double min) +{ mMin = min; mSpinBox->setMinimum(min); if (mIsInteger == 1) { mSlider->setMinimum(min); - } - else { + } else { double step = mWidth/1000.0; mSpinBox->setSingleStep(step); mWidth = mMax-mMin; } - if (mValue < min) { SetValue(min); } + if (mValue < min) { + SetValue(min); + } QString tip = QString("Min = %1 Max = %2").arg(min).arg(mSpinBox->maximum()); setToolTip(tip); } @@ -165,13 +176,14 @@ void vvIntensityValueSlider::SetMinimum(double min) { //------------------------------------------------------------------------------ -void vvIntensityValueSlider::Update() { +void vvIntensityValueSlider::Update() +{ double range[2]; mImage->GetFirstVTKImageData()->GetScalarRange(range); mMin = range[0]; mMax = range[1]; double step = (mMax-mMin)/1000.0; - + if (mImage->IsScalarTypeInteger()) { mIsInteger = true; mSpinBox->setSingleStep(1.0); @@ -181,8 +193,7 @@ void vvIntensityValueSlider::Update() { mSlider->setSingleStep(1); mSliderFactor = 1.0; mWidth = 1.0; - } - else { + } else { mIsInteger = false; mButtonPlus->setHidden(false); mButtonMinus->setHidden(false); @@ -195,11 +206,11 @@ void vvIntensityValueSlider::Update() { mSliderFactor = 1.0/1000.0; mWidth = mMax-mMin; } - + mSpinBox->setMaximum(mMax); mSpinBox->setMinimum(mMin); mSpinBox->setValue((mMax-mMin)/2.0+mMin); - + QString tip = QString("Min = %1 Max = %2").arg(mMin).arg(mMax); setToolTip(tip); } diff --git a/vv/vvInteractorStyleNavigator.cxx b/vv/vvInteractorStyleNavigator.cxx index 96c45a4..9d6aa10 100644 --- a/vv/vvInteractorStyleNavigator.cxx +++ b/vv/vvInteractorStyleNavigator.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -36,580 +36,539 @@ vtkStandardNewMacro(vvInteractorStyleNavigator); //---------------------------------------------------------------------------- vvInteractorStyleNavigator::vvInteractorStyleNavigator() { - this->WindowLevelStartPosition[0] = 0; - this->WindowLevelStartPosition[1] = 0; + this->WindowLevelStartPosition[0] = 0; + this->WindowLevelStartPosition[1] = 0; - this->WindowLevelCurrentPosition[0] = 0; - this->WindowLevelCurrentPosition[1] = 0; + this->WindowLevelCurrentPosition[0] = 0; + this->WindowLevelCurrentPosition[1] = 0; - this->MotionFactor = 10.0; + this->MotionFactor = 10.0; } //---------------------------------------------------------------------------- vvInteractorStyleNavigator::~vvInteractorStyleNavigator() { - CurrentRenderer=NULL; + CurrentRenderer=NULL; } void vvInteractorStyleNavigator::FindPokedRenderer(int dummy1,int dummy2) { - vtkRenderWindow * renwin=this->GetInteractor()->GetRenderWindow(); - renwin->GetRenderers()->InitTraversal(); - while (true) - { - vtkRenderer* current = renwin->GetRenderers()->GetNextItem(); - if (current==NULL || current->GetDraw()) - { - CurrentRenderer=current; - return; - } - } + vtkRenderWindow * renwin=this->GetInteractor()->GetRenderWindow(); + renwin->GetRenderers()->InitTraversal(); + while (true) { + vtkRenderer* current = renwin->GetRenderers()->GetNextItem(); + if (current==NULL || current->GetDraw()) { + CurrentRenderer=current; + return; + } + } } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::StartWindowLevel() { - if (this->State != VTKIS_NONE) - { - return; - } - this->StartState(VTKIS_WINDOW_LEVEL); - this->InvokeEvent(vtkCommand::StartWindowLevelEvent,this); + if (this->State != VTKIS_NONE) { + return; + } + this->StartState(VTKIS_WINDOW_LEVEL); + this->InvokeEvent(vtkCommand::StartWindowLevelEvent,this); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::EndWindowLevel() { - if (this->State != VTKIS_WINDOW_LEVEL) - { - return; - } - this->InvokeEvent(vtkCommand::EndWindowLevelEvent, this); - this->StopState(); + if (this->State != VTKIS_WINDOW_LEVEL) { + return; + } + this->InvokeEvent(vtkCommand::EndWindowLevelEvent, this); + this->StopState(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::StartPick() { - if (this->State != VTKIS_NONE) - { - return; - } - this->StartState(VTKIS_PICK); - this->InvokeEvent(vtkCommand::StartPickEvent, this); + if (this->State != VTKIS_NONE) { + return; + } + this->StartState(VTKIS_PICK); + this->InvokeEvent(vtkCommand::StartPickEvent, this); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::EndPick() { - if (this->State != VTKIS_PICK) - { - return; - } - this->InvokeEvent(vtkCommand::EndPickEvent, this); - this->StopState(); + if (this->State != VTKIS_PICK) { + return; + } + this->InvokeEvent(vtkCommand::EndPickEvent, this); + this->StopState(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnMouseMove() { - int x = this->Interactor->GetEventPosition()[0]; - int y = this->Interactor->GetEventPosition()[1]; - - switch (this->State) - { - case VTKIS_WINDOW_LEVEL: - this->FindPokedRenderer(x, y); - this->WindowLevel(); - this->InvokeEvent(vtkCommand::InteractionEvent, NULL); - break; - - case VTKIS_PICK: - this->FindPokedRenderer(x, y); - this->Pick(); - this->InvokeEvent(vtkCommand::InteractionEvent, NULL); - break; - - case VTKIS_PAN: - this->FindPokedRenderer(x, y); - this->Pan(); - this->InvokeEvent(vtkCommand::InteractionEvent, NULL); - break; - - case VTKIS_DOLLY: - this->FindPokedRenderer(x, y); - this->Dolly(); - this->InvokeEvent(vtkCommand::InteractionEvent, NULL); - break; - - default: - this->InvokeEvent(vtkCommand::UserEvent, NULL); - break; - } + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + switch (this->State) { + case VTKIS_WINDOW_LEVEL: + this->FindPokedRenderer(x, y); + this->WindowLevel(); + this->InvokeEvent(vtkCommand::InteractionEvent, NULL); + break; - // Call parent to handle all other states and perform additional work + case VTKIS_PICK: + this->FindPokedRenderer(x, y); + this->Pick(); + this->InvokeEvent(vtkCommand::InteractionEvent, NULL); + break; + + case VTKIS_PAN: + this->FindPokedRenderer(x, y); + this->Pan(); + this->InvokeEvent(vtkCommand::InteractionEvent, NULL); + break; + + case VTKIS_DOLLY: + this->FindPokedRenderer(x, y); + this->Dolly(); + this->InvokeEvent(vtkCommand::InteractionEvent, NULL); + break; + + default: + this->InvokeEvent(vtkCommand::UserEvent, NULL); + break; + } + + // Call parent to handle all other states and perform additional work } void vvInteractorStyleNavigator::OnEnter() { - // int x = this->Interactor->GetEventPosition()[0]; - //int y = this->Interactor->GetEventPosition()[1]; + // int x = this->Interactor->GetEventPosition()[0]; + //int y = this->Interactor->GetEventPosition()[1]; - switch (this->State) - { - case VTKIS_WINDOW_LEVEL: - break; + switch (this->State) { + case VTKIS_WINDOW_LEVEL: + break; - case VTKIS_PICK: - break; + case VTKIS_PICK: + break; - case VTKIS_PAN: - break; + case VTKIS_PAN: + break; - default: - this->InvokeEvent(vtkCommand::EnterEvent, NULL); - break; - } + default: + this->InvokeEvent(vtkCommand::EnterEvent, NULL); + break; + } - // Call parent to handle all other states and perform additional work + // Call parent to handle all other states and perform additional work } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnLeave() { - // int x = this->Interactor->GetEventPosition()[0]; - //int y = this->Interactor->GetEventPosition()[1]; + // int x = this->Interactor->GetEventPosition()[0]; + //int y = this->Interactor->GetEventPosition()[1]; - switch (this->State) - { - case VTKIS_WINDOW_LEVEL: - break; + switch (this->State) { + case VTKIS_WINDOW_LEVEL: + break; - case VTKIS_PICK: - break; + case VTKIS_PICK: + break; - case VTKIS_PAN: - break; + case VTKIS_PAN: + break; - default: - this->InvokeEvent(vtkCommand::LeaveEvent, NULL); - break; - } + default: + this->InvokeEvent(vtkCommand::LeaveEvent, NULL); + break; + } - // Call parent to handle all other states and perform additional work + // Call parent to handle all other states and perform additional work } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnRightButtonDown() { - int x = this->Interactor->GetEventPosition()[0]; - int y = this->Interactor->GetEventPosition()[1]; - - this->FindPokedRenderer(x, y); - if (this->CurrentRenderer == NULL) - { - return; - } - - // Redefine this button to handle window/level - this->GrabFocus(this->EventCallbackCommand); - if (!this->Interactor->GetShiftKey() && !this->Interactor->GetControlKey()) - { - this->WindowLevelStartPosition[0] = x; - this->WindowLevelStartPosition[1] = y; - this->StartWindowLevel(); - } - - // The rest of the button + key combinations remain the same - - else - { - this->Superclass::OnRightButtonDown(); - } + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; + + this->FindPokedRenderer(x, y); + if (this->CurrentRenderer == NULL) { + return; + } + + // Redefine this button to handle window/level + this->GrabFocus(this->EventCallbackCommand); + if (!this->Interactor->GetShiftKey() && !this->Interactor->GetControlKey()) { + this->WindowLevelStartPosition[0] = x; + this->WindowLevelStartPosition[1] = y; + this->StartWindowLevel(); + } + + // The rest of the button + key combinations remain the same + + else { + this->Superclass::OnRightButtonDown(); + } } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnRightButtonUp() { - switch (this->State) - { - case VTKIS_WINDOW_LEVEL: - this->EndWindowLevel(); - if ( this->Interactor ) - { - this->ReleaseFocus(); - } - break; + switch (this->State) { + case VTKIS_WINDOW_LEVEL: + this->EndWindowLevel(); + if ( this->Interactor ) { + this->ReleaseFocus(); } + break; + } - // Call parent to handle all other states and perform additional work + // Call parent to handle all other states and perform additional work - this->Superclass::OnRightButtonUp(); + this->Superclass::OnRightButtonUp(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnLeftButtonDown() { - int x = this->Interactor->GetEventPosition()[0]; - int y = this->Interactor->GetEventPosition()[1]; + int x = this->Interactor->GetEventPosition()[0]; + int y = this->Interactor->GetEventPosition()[1]; - this->FindPokedRenderer(x, y); - if (this->CurrentRenderer == NULL) - { - return; - } + this->FindPokedRenderer(x, y); + if (this->CurrentRenderer == NULL) { + return; + } - // Redefine this button to handle pick - this->GrabFocus(this->EventCallbackCommand); - if (!this->Interactor->GetShiftKey() && !this->Interactor->GetControlKey()) - { - this->StartPick(); - } + // Redefine this button to handle pick + this->GrabFocus(this->EventCallbackCommand); + if (!this->Interactor->GetShiftKey() && !this->Interactor->GetControlKey()) { + this->StartPick(); + } - // The rest of the button + key combinations remain the same + // The rest of the button + key combinations remain the same - else - { - this->Superclass::OnLeftButtonDown(); - } + else { + this->Superclass::OnLeftButtonDown(); + } } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnLeftButtonUp() { // DD("OnLeftButtonUp"); - switch (this->State) - { - case VTKIS_PICK: - this->EndPick(); - if ( this->Interactor ) - { - this->ReleaseFocus(); - } - break; + switch (this->State) { + case VTKIS_PICK: + this->EndPick(); + if ( this->Interactor ) { + this->ReleaseFocus(); } + break; + } - // Call parent to handle all other states and perform additional work + // Call parent to handle all other states and perform additional work - this->Superclass::OnLeftButtonUp(); + this->Superclass::OnLeftButtonUp(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnMiddleButtonDown() { - this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], - this->Interactor->GetEventPosition()[1]); - if (this->CurrentRenderer == NULL) - { - return; - } - this->CurrentRenderer->GetRenderWindow()->SetCurrentCursor(8); - this->GrabFocus(this->EventCallbackCommand); - this->StartPan(); + this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], + this->Interactor->GetEventPosition()[1]); + if (this->CurrentRenderer == NULL) { + return; + } + this->CurrentRenderer->GetRenderWindow()->SetCurrentCursor(8); + this->GrabFocus(this->EventCallbackCommand); + this->StartPan(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnMiddleButtonUp() { - switch (this->State) - { - case VTKIS_PAN: - this->EndPan(); - if ( this->Interactor ) - { - this->Interactor->GetRenderWindow()->SetCurrentCursor(0); - this->ReleaseFocus(); - } - break; - } + switch (this->State) { + case VTKIS_PAN: + this->EndPan(); + if ( this->Interactor ) { + this->Interactor->GetRenderWindow()->SetCurrentCursor(0); + this->ReleaseFocus(); + } + break; + } } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnChar() { - vtkRenderWindowInteractor *rwi = this->Interactor; - - switch (rwi->GetKeyCode()) - { - case 'f' : - case 'F' : - { - this->AnimState = VTKIS_ANIM_ON; - this->AnimState = VTKIS_ANIM_OFF; - break; - } - - case 'o' : - case 'O' : - { - this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], - this->Interactor->GetEventPosition()[1]); - if (this->CurrentRenderer == NULL) - { - return; - } - this->GrabFocus(this->EventCallbackCommand); - this->StartDolly(); - double factor = -2; - this->Dolly(pow((double)1.1, factor)); - this->EndDolly(); - this->ReleaseFocus(); - break; - } - case 'i' : - case 'I' : - { - this->FindPokedRenderer(rwi->GetEventPosition()[0], - rwi->GetEventPosition()[1]); - if (this->CurrentRenderer == NULL) - { - return; - } - this->GrabFocus(this->EventCallbackCommand); - this->StartDolly(); - double factor = 2; - this->Dolly(pow((double)1.1, factor)); - this->EndDolly(); - this->ReleaseFocus(); - break; + vtkRenderWindowInteractor *rwi = this->Interactor; + + switch (rwi->GetKeyCode()) { + case 'f' : + case 'F' : { + this->AnimState = VTKIS_ANIM_ON; + this->AnimState = VTKIS_ANIM_OFF; + break; + } + + case 'o' : + case 'O' : { + this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], + this->Interactor->GetEventPosition()[1]); + if (this->CurrentRenderer == NULL) { + return; } - case '3' : - // Disable StereoVision - break; - case 'r' : - case 'R' : - //Do nothing, this is handled in vvSlicerManagerCommand - break; - default: - this->Superclass::OnChar(); - break; + this->GrabFocus(this->EventCallbackCommand); + this->StartDolly(); + double factor = -2; + this->Dolly(pow((double)1.1, factor)); + this->EndDolly(); + this->ReleaseFocus(); + break; + } + case 'i' : + case 'I' : { + this->FindPokedRenderer(rwi->GetEventPosition()[0], + rwi->GetEventPosition()[1]); + if (this->CurrentRenderer == NULL) { + return; } + this->GrabFocus(this->EventCallbackCommand); + this->StartDolly(); + double factor = 2; + this->Dolly(pow((double)1.1, factor)); + this->EndDolly(); + this->ReleaseFocus(); + break; + } + case '3' : + // Disable StereoVision + break; + case 'r' : + case 'R' : + //Do nothing, this is handled in vvSlicerManagerCommand + break; + default: + this->Superclass::OnChar(); + break; + } } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnMouseWheelForward() { - this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], - this->Interactor->GetEventPosition()[1]); - if (this->CurrentRenderer == NULL) - { - return; - } - this->GrabFocus(this->EventCallbackCommand); - if (this->Interactor->GetControlKey()) - { - this->StartDolly(); - double factor = this->MotionFactor * 0.2 * this->MouseWheelMotionFactor; - this->Dolly(pow((double)1.1, factor)); - this->EndDolly(); - } - this->ReleaseFocus(); - this->InvokeEvent(vtkCommand::MouseWheelForwardEvent, this); + this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], + this->Interactor->GetEventPosition()[1]); + if (this->CurrentRenderer == NULL) { + return; + } + this->GrabFocus(this->EventCallbackCommand); + if (this->Interactor->GetControlKey()) { + this->StartDolly(); + double factor = this->MotionFactor * 0.2 * this->MouseWheelMotionFactor; + this->Dolly(pow((double)1.1, factor)); + this->EndDolly(); + } + this->ReleaseFocus(); + this->InvokeEvent(vtkCommand::MouseWheelForwardEvent, this); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::OnMouseWheelBackward() { - this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], - this->Interactor->GetEventPosition()[1]); - if (this->CurrentRenderer == NULL) - { - return; - } - - this->GrabFocus(this->EventCallbackCommand); - if (this->Interactor->GetControlKey()) - { - this->StartDolly(); - double factor = this->MotionFactor * -0.2 * this->MouseWheelMotionFactor; - this->Dolly(pow((double)1.1, factor)); - this->EndDolly(); - } - this->ReleaseFocus(); - this->InvokeEvent(vtkCommand::MouseWheelBackwardEvent, this); + this->FindPokedRenderer(this->Interactor->GetEventPosition()[0], + this->Interactor->GetEventPosition()[1]); + if (this->CurrentRenderer == NULL) { + return; + } + + this->GrabFocus(this->EventCallbackCommand); + if (this->Interactor->GetControlKey()) { + this->StartDolly(); + double factor = this->MotionFactor * -0.2 * this->MouseWheelMotionFactor; + this->Dolly(pow((double)1.1, factor)); + this->EndDolly(); + } + this->ReleaseFocus(); + this->InvokeEvent(vtkCommand::MouseWheelBackwardEvent, this); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::WindowLevel() { - vtkRenderWindowInteractor *rwi = this->Interactor; + vtkRenderWindowInteractor *rwi = this->Interactor; - this->WindowLevelCurrentPosition[0] = rwi->GetEventPosition()[0]; - this->WindowLevelCurrentPosition[1] = rwi->GetEventPosition()[1]; + this->WindowLevelCurrentPosition[0] = rwi->GetEventPosition()[0]; + this->WindowLevelCurrentPosition[1] = rwi->GetEventPosition()[1]; - this->InvokeEvent(vtkCommand::WindowLevelEvent, this); + this->InvokeEvent(vtkCommand::WindowLevelEvent, this); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::Pick() { - this->InvokeEvent(vtkCommand::PickEvent, this); + this->InvokeEvent(vtkCommand::PickEvent, this); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::Pan() { - if (this->CurrentRenderer == NULL) - { - return; - } + if (this->CurrentRenderer == NULL) { + return; + } - vtkRenderWindowInteractor *rwi = this->Interactor; + vtkRenderWindowInteractor *rwi = this->Interactor; - double viewFocus[4], focalDepth, viewPoint[3]; - double newPickPoint[4], oldPickPoint[4], motionVector[3]; + double viewFocus[4], focalDepth, viewPoint[3]; + double newPickPoint[4], oldPickPoint[4], motionVector[3]; - // Calculate the focal depth since we'll be using it a lot + // Calculate the focal depth since we'll be using it a lot - vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); - camera->GetFocalPoint(viewFocus); - this->ComputeWorldToDisplay(viewFocus[0], viewFocus[1], viewFocus[2], - viewFocus); - focalDepth = viewFocus[2]; + vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); + camera->GetFocalPoint(viewFocus); + this->ComputeWorldToDisplay(viewFocus[0], viewFocus[1], viewFocus[2], + viewFocus); + focalDepth = viewFocus[2]; - this->ComputeDisplayToWorld((double)rwi->GetEventPosition()[0], - (double)rwi->GetEventPosition()[1], - focalDepth, - newPickPoint); + this->ComputeDisplayToWorld((double)rwi->GetEventPosition()[0], + (double)rwi->GetEventPosition()[1], + focalDepth, + newPickPoint); - // Has to recalc old mouse point since the viewport has moved, - // so can't move it outside the loop + // Has to recalc old mouse point since the viewport has moved, + // so can't move it outside the loop - this->ComputeDisplayToWorld((double)rwi->GetLastEventPosition()[0], - (double)rwi->GetLastEventPosition()[1], - focalDepth, - oldPickPoint); + this->ComputeDisplayToWorld((double)rwi->GetLastEventPosition()[0], + (double)rwi->GetLastEventPosition()[1], + focalDepth, + oldPickPoint); - // Camera motion is reversed + // Camera motion is reversed - motionVector[0] = oldPickPoint[0] - newPickPoint[0]; - motionVector[1] = oldPickPoint[1] - newPickPoint[1]; - motionVector[2] = oldPickPoint[2] - newPickPoint[2]; + motionVector[0] = oldPickPoint[0] - newPickPoint[0]; + motionVector[1] = oldPickPoint[1] - newPickPoint[1]; + motionVector[2] = oldPickPoint[2] - newPickPoint[2]; - camera->GetFocalPoint(viewFocus); - camera->GetPosition(viewPoint); - camera->SetFocalPoint(motionVector[0] + viewFocus[0], - motionVector[1] + viewFocus[1], - motionVector[2] + viewFocus[2]); + camera->GetFocalPoint(viewFocus); + camera->GetPosition(viewPoint); + camera->SetFocalPoint(motionVector[0] + viewFocus[0], + motionVector[1] + viewFocus[1], + motionVector[2] + viewFocus[2]); - camera->SetPosition(motionVector[0] + viewPoint[0], - motionVector[1] + viewPoint[1], - motionVector[2] + viewPoint[2]); + camera->SetPosition(motionVector[0] + viewPoint[0], + motionVector[1] + viewPoint[1], + motionVector[2] + viewPoint[2]); - if (rwi->GetLightFollowCamera()) - { - this->CurrentRenderer->UpdateLightsGeometryToFollowCamera(); - } + if (rwi->GetLightFollowCamera()) { + this->CurrentRenderer->UpdateLightsGeometryToFollowCamera(); + } - rwi->Render(); + rwi->Render(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::Dolly() { - if (this->CurrentRenderer == NULL) - { - return; - } - - vtkRenderWindowInteractor *rwi = this->Interactor; - double *center = this->CurrentRenderer->GetCenter(); - int dy = rwi->GetEventPosition()[1] - rwi->GetLastEventPosition()[1]; - double dyf = this->MotionFactor * (double)(dy) / (double)(center[1]); - this->Dolly(pow((double)1.1, dyf)); + if (this->CurrentRenderer == NULL) { + return; + } + + vtkRenderWindowInteractor *rwi = this->Interactor; + double *center = this->CurrentRenderer->GetCenter(); + int dy = rwi->GetEventPosition()[1] - rwi->GetLastEventPosition()[1]; + double dyf = this->MotionFactor * (double)(dy) / (double)(center[1]); + this->Dolly(pow((double)1.1, dyf)); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::Dolly(double factor) { - if (this->CurrentRenderer == NULL) - { - return; - } - - double viewFocus[4],viewPoint[4],motionVector[3], focalDepth; - double oldPos[3], newPos[3], distance[2]; - vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); - camera->GetFocalPoint(viewFocus); - this->ComputeWorldToDisplay(viewFocus[0], viewFocus[1], viewFocus[2], - viewFocus); - focalDepth = viewFocus[2]; - - oldPos[0] = this->CurrentRenderer->GetCenter()[0]; - oldPos[1] = this->CurrentRenderer->GetCenter()[1]; - oldPos[2] = focalDepth; - - distance[0] = 1/factor* - (this->Interactor->GetEventPosition()[0]-this->CurrentRenderer->GetCenter()[0]); - distance[1] = 1/factor* - (this->Interactor->GetEventPosition()[1]-this->CurrentRenderer->GetCenter()[1]); - - newPos[0] = this->Interactor->GetEventPosition()[0] - distance[0]; - newPos[1] = this->Interactor->GetEventPosition()[1] - distance[1]; - newPos[2] = focalDepth; - - this->CurrentRenderer->DisplayToNormalizedDisplay(oldPos[0],oldPos[1]); - this->CurrentRenderer->NormalizedDisplayToViewport(oldPos[0],oldPos[1]); - this->CurrentRenderer->ViewportToNormalizedViewport(oldPos[0],oldPos[1]); - this->CurrentRenderer->NormalizedViewportToView(oldPos[0],oldPos[1],oldPos[2]); - this->CurrentRenderer->ViewToWorld(oldPos[0],oldPos[1],oldPos[2]); - - this->CurrentRenderer->DisplayToNormalizedDisplay(newPos[0],newPos[1]); - this->CurrentRenderer->NormalizedDisplayToViewport(newPos[0],newPos[1]); - this->CurrentRenderer->ViewportToNormalizedViewport(newPos[0],newPos[1]); - this->CurrentRenderer->NormalizedViewportToView(newPos[0],newPos[1],newPos[2]); - this->CurrentRenderer->ViewToWorld(newPos[0],newPos[1],newPos[2]); - - motionVector[0] = newPos[0] - oldPos[0]; - motionVector[1] = newPos[1] - oldPos[1]; - motionVector[2] = newPos[2] - oldPos[2]; - - camera->GetFocalPoint(viewFocus); - camera->GetPosition(viewPoint); - camera->SetFocalPoint(motionVector[0] + viewFocus[0], - motionVector[1] + viewFocus[1], - motionVector[2] + viewFocus[2]); - - camera->SetPosition(motionVector[0] + viewPoint[0], - motionVector[1] + viewPoint[1], - motionVector[2] + viewPoint[2]); - - if (camera->GetParallelProjection()) - { - camera->SetParallelScale(camera->GetParallelScale() / factor); - } - else - { - camera->Dolly(factor); - if (this->AutoAdjustCameraClippingRange) - { - this->CurrentRenderer->ResetCameraClippingRange(); - } - } - - if (this->Interactor->GetLightFollowCamera()) - { - this->CurrentRenderer->UpdateLightsGeometryToFollowCamera(); - } - this->CurrentRenderer->ResetCameraClippingRange(); - //this->Interactor->Render(); + if (this->CurrentRenderer == NULL) { + return; + } + + double viewFocus[4],viewPoint[4],motionVector[3], focalDepth; + double oldPos[3], newPos[3], distance[2]; + vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); + camera->GetFocalPoint(viewFocus); + this->ComputeWorldToDisplay(viewFocus[0], viewFocus[1], viewFocus[2], + viewFocus); + focalDepth = viewFocus[2]; + + oldPos[0] = this->CurrentRenderer->GetCenter()[0]; + oldPos[1] = this->CurrentRenderer->GetCenter()[1]; + oldPos[2] = focalDepth; + + distance[0] = 1/factor* + (this->Interactor->GetEventPosition()[0]-this->CurrentRenderer->GetCenter()[0]); + distance[1] = 1/factor* + (this->Interactor->GetEventPosition()[1]-this->CurrentRenderer->GetCenter()[1]); + + newPos[0] = this->Interactor->GetEventPosition()[0] - distance[0]; + newPos[1] = this->Interactor->GetEventPosition()[1] - distance[1]; + newPos[2] = focalDepth; + + this->CurrentRenderer->DisplayToNormalizedDisplay(oldPos[0],oldPos[1]); + this->CurrentRenderer->NormalizedDisplayToViewport(oldPos[0],oldPos[1]); + this->CurrentRenderer->ViewportToNormalizedViewport(oldPos[0],oldPos[1]); + this->CurrentRenderer->NormalizedViewportToView(oldPos[0],oldPos[1],oldPos[2]); + this->CurrentRenderer->ViewToWorld(oldPos[0],oldPos[1],oldPos[2]); + + this->CurrentRenderer->DisplayToNormalizedDisplay(newPos[0],newPos[1]); + this->CurrentRenderer->NormalizedDisplayToViewport(newPos[0],newPos[1]); + this->CurrentRenderer->ViewportToNormalizedViewport(newPos[0],newPos[1]); + this->CurrentRenderer->NormalizedViewportToView(newPos[0],newPos[1],newPos[2]); + this->CurrentRenderer->ViewToWorld(newPos[0],newPos[1],newPos[2]); + + motionVector[0] = newPos[0] - oldPos[0]; + motionVector[1] = newPos[1] - oldPos[1]; + motionVector[2] = newPos[2] - oldPos[2]; + + camera->GetFocalPoint(viewFocus); + camera->GetPosition(viewPoint); + camera->SetFocalPoint(motionVector[0] + viewFocus[0], + motionVector[1] + viewFocus[1], + motionVector[2] + viewFocus[2]); + + camera->SetPosition(motionVector[0] + viewPoint[0], + motionVector[1] + viewPoint[1], + motionVector[2] + viewPoint[2]); + + if (camera->GetParallelProjection()) { + camera->SetParallelScale(camera->GetParallelScale() / factor); + } else { + camera->Dolly(factor); + if (this->AutoAdjustCameraClippingRange) { + this->CurrentRenderer->ResetCameraClippingRange(); + } + } + + if (this->Interactor->GetLightFollowCamera()) { + this->CurrentRenderer->UpdateLightsGeometryToFollowCamera(); + } + this->CurrentRenderer->ResetCameraClippingRange(); + //this->Interactor->Render(); } //---------------------------------------------------------------------------- void vvInteractorStyleNavigator::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os, indent); + this->Superclass::PrintSelf(os, indent); - os << indent << "Window Level Current Position: (" - << this->WindowLevelCurrentPosition[0] << ", " - << this->WindowLevelCurrentPosition[1] << ")" << endl; + os << indent << "Window Level Current Position: (" + << this->WindowLevelCurrentPosition[0] << ", " + << this->WindowLevelCurrentPosition[1] << ")" << endl; - os << indent << "Window Level Start Position: (" - << this->WindowLevelStartPosition[0] << ", " - << this->WindowLevelStartPosition[1] << ")" << endl; + os << indent << "Window Level Start Position: (" + << this->WindowLevelStartPosition[0] << ", " + << this->WindowLevelStartPosition[1] << ")" << endl; } diff --git a/vv/vvLandmarks.cxx b/vv/vvLandmarks.cxx index bf9207f..b0e228c 100644 --- a/vv/vvLandmarks.cxx +++ b/vv/vvLandmarks.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,246 +31,226 @@ vvLandmarks::vvLandmarks(int size) { - mLandmarks.resize(0); - mFilename = ""; + mLandmarks.resize(0); + mFilename = ""; - for (int i = 0; i < size; i++) - { - vtkPoints *points = vtkPoints::New(); - mPoints.push_back(points); - } - mPolyData = vtkPolyData::New(); - mIds = vtkFloatArray::New(); + for (int i = 0; i < size; i++) { + vtkPoints *points = vtkPoints::New(); + mPoints.push_back(points); + } + mPolyData = vtkPolyData::New(); + mIds = vtkFloatArray::New(); } vvLandmarks::~vvLandmarks() { - for (unsigned int i = 0; i < mPoints.size(); i++) { - mPoints[i]->Delete(); - } - /*for(unsigned int i = 0; i < mText.size(); i++) { - mText[i]->Delete(); - }*/ - if (mIds) - mIds->Delete(); - if (mPolyData) - mPolyData->Delete(); + for (unsigned int i = 0; i < mPoints.size(); i++) { + mPoints[i]->Delete(); + } + /*for(unsigned int i = 0; i < mText.size(); i++) { + mText[i]->Delete(); + }*/ + if (mIds) + mIds->Delete(); + if (mPolyData) + mPolyData->Delete(); } void vvLandmarks::AddLandmark(float x,float y,float z,float t,double value) { - vvLandmark point; - point.coordinates[0] = x; - point.coordinates[1] = y; - point.coordinates[2] = z; - point.coordinates[3] = t; - point.pixel_value=value; - mLandmarks.push_back(point); - mPoints[int(t)]->InsertNextPoint(x,y,z); + vvLandmark point; + point.coordinates[0] = x; + point.coordinates[1] = y; + point.coordinates[2] = z; + point.coordinates[3] = t; + point.pixel_value=value; + mLandmarks.push_back(point); + mPoints[int(t)]->InsertNextPoint(x,y,z); - /*std::stringstream numberVal; - numberVal << (mLandmarks.size()-1); - vvLandmarksGlyph *number = vvLandmarksGlyph::New(); - number->SetText(numberVal.str().c_str()); - number->BackingOff(); - mText.push_back(number);*/ - mIds->InsertNextTuple1(0.55); - //mIds->InsertTuple1(mLandmarks.size(),mLandmarks.size()); - SetTime(int(t)); + /*std::stringstream numberVal; + numberVal << (mLandmarks.size()-1); + vvLandmarksGlyph *number = vvLandmarksGlyph::New(); + number->SetText(numberVal.str().c_str()); + number->BackingOff(); + mText.push_back(number);*/ + mIds->InsertNextTuple1(0.55); + //mIds->InsertTuple1(mLandmarks.size(),mLandmarks.size()); + SetTime(int(t)); } void vvLandmarks::RemoveLastLandmark() { - mPoints[mLandmarks.back().coordinates[3]]->SetNumberOfPoints( - mPoints[mLandmarks.back().coordinates[3]]->GetNumberOfPoints()-1); - mPolyData->Modified(); - //mText.pop_back(); - mLandmarks.pop_back(); - mIds->RemoveLastTuple(); + mPoints[mLandmarks.back().coordinates[3]]->SetNumberOfPoints( + mPoints[mLandmarks.back().coordinates[3]]->GetNumberOfPoints()-1); + mPolyData->Modified(); + //mText.pop_back(); + mLandmarks.pop_back(); + mIds->RemoveLastTuple(); } void vvLandmarks::ChangeComments(int index, std::string comments) { - mLandmarks[index].comments = comments; + mLandmarks[index].comments = comments; } double vvLandmarks::GetPixelValue(int index) { - return mLandmarks[index].pixel_value; + return mLandmarks[index].pixel_value; } float* vvLandmarks::GetCoordinates(int index) { - return mLandmarks[index].coordinates; + return mLandmarks[index].coordinates; } std::string vvLandmarks::GetComments(int index) { - return mLandmarks[index].comments; + return mLandmarks[index].comments; } void vvLandmarks::LoadFile(std::string filename) { - std::ifstream fp(filename.c_str(), std::ios::in|std::ios::binary); - if (!fp.is_open()) - { - std::cerr <<"Unable to open file " << filename << std::endl; - return; + std::ifstream fp(filename.c_str(), std::ios::in|std::ios::binary); + if (!fp.is_open()) { + std::cerr <<"Unable to open file " << filename << std::endl; + return; + } + mFilename = filename; + mLandmarks.clear(); + char line[255]; + for (unsigned int i = 0; i < mPoints.size(); i++) + mPoints[i]->SetNumberOfPoints(0); + bool first_line=true; + while (fp.getline(line,255)) { + std::string stringline = line; + if (first_line) { + first_line=false; + ///New landmark format: first line is "LANDMARKSXX", where XX is the version number + if (stringline.size() >= 10 && stringline.compare(0,9,"LANDMARKS")==0) { + std::istringstream ss(stringline.c_str()+9); + ss >> mFormatVersion; + continue; //skip first line + } else + mFormatVersion=0; } - mFilename = filename; - mLandmarks.clear(); - char line[255]; - for (unsigned int i = 0; i < mPoints.size();i++) - mPoints[i]->SetNumberOfPoints(0); - bool first_line=true; - while (fp.getline(line,255)) - { - std::string stringline = line; - if (first_line) - { - first_line=false; - ///New landmark format: first line is "LANDMARKSXX", where XX is the version number - if (stringline.size() >= 10 && stringline.compare(0,9,"LANDMARKS")==0) - { - std::istringstream ss(stringline.c_str()+9); - ss >> mFormatVersion; - continue; //skip first line - } - else - mFormatVersion=0; + DD(mFormatVersion); + if (stringline.size() > 1) { + vvLandmark point; + int previousSpace = 0; + int space=0; + if (mFormatVersion>0) { + space = stringline.find(" ", previousSpace+1); + if (space < -1 || space > (int)stringline.size()) { + ErrorMsg(mLandmarks.size(),"index"); + continue; + } + //int index = atoi(stringline.substr(previousSpace,space - previousSpace).c_str()); + previousSpace = space; + } + space = stringline.find(" ", previousSpace+1); + if (space < -1 || space > (int)stringline.size()) { + ErrorMsg(mLandmarks.size(),"x position"); + continue; + } + point.coordinates[0] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); + previousSpace = space; + space = stringline.find(" ", previousSpace+1); + if (space < -1 || space > (int)stringline.size()) { + ErrorMsg(mLandmarks.size(),"y position"); + continue; + } + point.coordinates[1] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); + previousSpace = space; + space = stringline.find(" ", previousSpace+1); + if (space < -1 || space > (int)stringline.size()) { + ErrorMsg(mLandmarks.size(),"z position"); + continue; + } + point.coordinates[2] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); + previousSpace = space; + if (mFormatVersion>0) { + space = stringline.find(" ", previousSpace+1); + if (space < -1 || space > (int)stringline.size()) { + ErrorMsg(mLandmarks.size(),"t position"); + continue; } - DD(mFormatVersion); - if (stringline.size() > 1) - { - vvLandmark point; - int previousSpace = 0; - int space=0; - if (mFormatVersion>0) - { - space = stringline.find(" ", previousSpace+1); - if (space < -1 || space > (int)stringline.size()) - { - ErrorMsg(mLandmarks.size(),"index"); - continue; - } - //int index = atoi(stringline.substr(previousSpace,space - previousSpace).c_str()); - previousSpace = space; - } - space = stringline.find(" ", previousSpace+1); - if (space < -1 || space > (int)stringline.size()) - { - ErrorMsg(mLandmarks.size(),"x position"); - continue; - } - point.coordinates[0] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); - previousSpace = space; - space = stringline.find(" ", previousSpace+1); - if (space < -1 || space > (int)stringline.size()) - { - ErrorMsg(mLandmarks.size(),"y position"); - continue; - } - point.coordinates[1] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); - previousSpace = space; - space = stringline.find(" ", previousSpace+1); - if (space < -1 || space > (int)stringline.size()) - { - ErrorMsg(mLandmarks.size(),"z position"); - continue; - } - point.coordinates[2] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); - previousSpace = space; - if (mFormatVersion>0) - { - space = stringline.find(" ", previousSpace+1); - if (space < -1 || space > (int)stringline.size()) - { - ErrorMsg(mLandmarks.size(),"t position"); - continue; - } - point.coordinates[3] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); - previousSpace = space; - space = stringline.find(" ", previousSpace+1); - if (space < -1 || space > (int)stringline.size()) - { - ErrorMsg(mLandmarks.size(),"pixel value"); - continue; - } - point.pixel_value = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); - } - else - { - point.pixel_value=0.; //Not in file - point.coordinates[3]=0.; - } - previousSpace = space; - //this is the maximum size of comments - space = (stringline.find("\n", previousSpace+1) < 254 ? stringline.find("\n", previousSpace+1) : 254); - point.comments = stringline.substr(previousSpace,space - (previousSpace)).c_str(); - mLandmarks.push_back(point); - mIds->InsertNextTuple1(0.55); - mPoints[int(point.coordinates[3])]->InsertNextPoint( - point.coordinates[0],point.coordinates[1],point.coordinates[2]); + point.coordinates[3] = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); + previousSpace = space; + space = stringline.find(" ", previousSpace+1); + if (space < -1 || space > (int)stringline.size()) { + ErrorMsg(mLandmarks.size(),"pixel value"); + continue; } + point.pixel_value = atof(replace_dots(stringline.substr(previousSpace,space - previousSpace)).c_str()); + } else { + point.pixel_value=0.; //Not in file + point.coordinates[3]=0.; + } + previousSpace = space; + //this is the maximum size of comments + space = (stringline.find("\n", previousSpace+1) < 254 ? stringline.find("\n", previousSpace+1) : 254); + point.comments = stringline.substr(previousSpace,space - (previousSpace)).c_str(); + mLandmarks.push_back(point); + mIds->InsertNextTuple1(0.55); + mPoints[int(point.coordinates[3])]->InsertNextPoint( + point.coordinates[0],point.coordinates[1],point.coordinates[2]); } - SetTime(0); + } + SetTime(0); } bool vvLandmarks::ErrorMsg(int num,const char * text) { - std::cerr << "error when loading point " << num << " at " << text << std::endl; - return false; + std::cerr << "error when loading point " << num << " at " << text << std::endl; + return false; } void vvLandmarks::SaveFile(std::string filename) { - std::string fileContent = "LANDMARKS1\n"; //File format version identification - for (unsigned int i = 0; i < mLandmarks.size(); i++) { - std::stringstream out; - out.imbue(std::locale("C")); //This is to specify that the dot is to be used as the decimal separator - out << i << " " - << mLandmarks[i].coordinates[0] << " " - << mLandmarks[i].coordinates[1] << " " - << mLandmarks[i].coordinates[2] << " " - << mLandmarks[i].coordinates[3] << " " - << mLandmarks[i].pixel_value << " "; - fileContent += out.str(); - if (mLandmarks[i].comments.size() == 0) - fileContent += " "; - else - fileContent += mLandmarks[i].comments; - fileContent += "\n"; - } - std::ofstream fp(filename.c_str(), std::ios::trunc); - if ( !fp ) - { - std::cerr << "Unable to open file" << std::endl; - return; - } - fp << fileContent.c_str()<< std::endl; - fp.close(); + std::string fileContent = "LANDMARKS1\n"; //File format version identification + for (unsigned int i = 0; i < mLandmarks.size(); i++) { + std::stringstream out; + out.imbue(std::locale("C")); //This is to specify that the dot is to be used as the decimal separator + out << i << " " + << mLandmarks[i].coordinates[0] << " " + << mLandmarks[i].coordinates[1] << " " + << mLandmarks[i].coordinates[2] << " " + << mLandmarks[i].coordinates[3] << " " + << mLandmarks[i].pixel_value << " "; + fileContent += out.str(); + if (mLandmarks[i].comments.size() == 0) + fileContent += " "; + else + fileContent += mLandmarks[i].comments; + fileContent += "\n"; + } + std::ofstream fp(filename.c_str(), std::ios::trunc); + if ( !fp ) { + std::cerr << "Unable to open file" << std::endl; + return; + } + fp << fileContent.c_str()<< std::endl; + fp.close(); } void vvLandmarks::SetTime(int time) { - if (time >= 0 && time <= ((int)mPoints.size() -1)) - { - mPolyData->SetPoints(mPoints[time]); - mPolyData->GetPointData()->SetScalars(mIds); - mPolyData->Modified(); - mPolyData->Update(); - } + if (time >= 0 && time <= ((int)mPoints.size() -1)) { + mPolyData->SetPoints(mPoints[time]); + mPolyData->GetPointData()->SetScalars(mIds); + mPolyData->Modified(); + mPolyData->Update(); + } } std::string vvLandmarks::replace_dots(std::string input) { - ///Replaces the dots used in the file with the decimal separator in use on the platform - lconv * conv=localeconv(); - unsigned int position = input.find( "." ); - while ( position < input.size() ) - { - input.replace(position, 1, conv->decimal_point); - position = input.find( ".", position + 1 ); - } - return input; + ///Replaces the dots used in the file with the decimal separator in use on the platform + lconv * conv=localeconv(); + unsigned int position = input.find( "." ); + while ( position < input.size() ) { + input.replace(position, 1, conv->decimal_point); + position = input.find( ".", position + 1 ); + } + return input; } diff --git a/vv/vvLandmarksGlyph.cxx b/vv/vvLandmarksGlyph.cxx index 626515d..99bed09 100644 --- a/vv/vvLandmarksGlyph.cxx +++ b/vv/vvLandmarksGlyph.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -36,536 +36,517 @@ vtkStandardNewMacro(vvLandmarksGlyph); #define vtkfont_height 15 //#define vtkfont_height 20 static unsigned char vtkfont_bits[] = { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0xe0,0x00,0x10,0x90,0x00,0x00,0x40,0x88,0x03,0x1c,0x10,0x08,0x00, - 0x00,0x00,0x00,0x00,0x00,0x20,0x1c,0x10,0xf8,0xf8,0x03,0xe2,0x0f,0x8f,0x3f, - 0x3e,0x7c,0x00,0x00,0x00,0x02,0x80,0x00,0x1f,0x3e,0x10,0xfc,0xf0,0xf1,0xe3, - 0xcf,0x1f,0x1f,0x41,0x7c,0xe0,0x09,0x12,0x20,0x48,0x10,0x1f,0x3f,0x7c,0xfc, - 0xf0,0xf1,0x27,0x48,0x90,0x20,0x41,0x82,0xfc,0xe1,0x11,0xc0,0x03,0x02,0x00, - 0x0e,0x00,0x04,0x00,0x00,0x04,0x00,0x0e,0x00,0x01,0x00,0x00,0x08,0xc0,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x80,0x83,0xe0,0x80,0x11,0xe0,0x00,0x10,0x90,0x90,0x80,0xa0,0x44,0x04,0x0c, - 0x08,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x22,0x18,0x04,0x01,0x02,0x23, - 0x80,0x00,0x20,0x41,0x82,0x00,0x00,0x00,0x01,0x00,0x81,0x20,0x41,0x28,0x08, - 0x09,0x22,0x44,0x80,0x80,0x20,0x41,0x10,0x80,0x08,0x11,0x20,0x48,0x90,0x20, - 0x41,0x82,0x04,0x09,0x82,0x20,0x48,0x90,0x20,0x41,0x82,0x00,0x21,0x20,0x00, - 0x02,0x05,0x00,0x0c,0x00,0x04,0x00,0x00,0x04,0x00,0x11,0x00,0x01,0x10,0x80, - 0x08,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x40,0x80,0x00,0x41,0x12,0xe0,0x00,0x10,0x90,0x90,0xe0,0xa3, - 0x44,0x04,0x02,0x08,0x10,0x00,0x40,0x00,0x00,0x00,0x00,0x10,0x41,0x14,0x04, - 0x01,0x81,0x22,0x40,0x00,0x20,0x41,0x82,0x00,0x00,0x80,0x00,0x00,0x82,0x20, - 0x41,0x44,0x08,0x09,0x20,0x44,0x80,0x80,0x00,0x41,0x10,0x80,0x88,0x10,0x60, - 0xcc,0x90,0x20,0x41,0x82,0x04,0x09,0x80,0x20,0x48,0x90,0x20,0x22,0x44,0x80, - 0x20,0x20,0x00,0x82,0x08,0x00,0x10,0x00,0x04,0x00,0x00,0x04,0x00,0x11,0x00, - 0x01,0x00,0x00,0x08,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x80,0x00,0x41,0x0c,0xe0,0x00,0x10,0x00, - 0xf8,0x91,0x40,0x42,0x04,0x00,0x04,0x20,0x88,0x40,0x00,0x00,0x00,0x00,0x08, - 0x41,0x10,0x00,0x81,0x40,0xa2,0x47,0x00,0x10,0x41,0x82,0x20,0x40,0x40,0x00, - 0x00,0x04,0x20,0x79,0x82,0x08,0x09,0x20,0x44,0x80,0x80,0x00,0x41,0x10,0x80, - 0x48,0x10,0xa0,0x4a,0x91,0x20,0x41,0x82,0x04,0x09,0x80,0x20,0x88,0x88,0x20, - 0x14,0x28,0x40,0x20,0x40,0x00,0x42,0x10,0x00,0x00,0x7c,0xf4,0xf0,0xe1,0xc5, - 0x07,0x01,0x2f,0x3d,0x18,0xe0,0x08,0x82,0xe0,0x46,0x0f,0x1f,0x3d,0xbc,0xe4, - 0xf0,0xf1,0x23,0x44,0x90,0x20,0x41,0x42,0xfc,0x81,0x80,0x80,0x00,0x00,0xe0, - 0x00,0x10,0x00,0x90,0x90,0x00,0x81,0x03,0x00,0x04,0x20,0x50,0x40,0x00,0x00, - 0x00,0x00,0x04,0x41,0x10,0x80,0xc0,0x21,0x62,0x48,0x0f,0x08,0x3e,0xc2,0x70, - 0xe0,0x20,0xe0,0x0f,0x08,0x10,0x45,0x82,0xf8,0x08,0x20,0xc4,0x83,0x87,0x00, - 0x7f,0x10,0x80,0x38,0x10,0xa0,0x4a,0x92,0x20,0x3f,0x82,0xfc,0xf0,0x81,0x20, - 0x88,0x88,0x24,0x08,0x10,0x20,0x20,0x80,0x00,0x02,0x00,0x00,0x00,0x80,0x0c, - 0x09,0x12,0x26,0x08,0x81,0x10,0x43,0x10,0x80,0x88,0x81,0x20,0xc9,0x90,0x20, - 0x43,0xc2,0x18,0x09,0x42,0x20,0x44,0x90,0x20,0x22,0x42,0x80,0x60,0x80,0x00, - 0x03,0x00,0xe0,0x00,0x10,0x00,0x90,0xe0,0x03,0x41,0x04,0x00,0x04,0x20,0xfc, - 0xf9,0x03,0xe0,0x0f,0x00,0x04,0x41,0x10,0x40,0x00,0x12,0x02,0xc8,0x10,0x04, - 0x41,0xbc,0x20,0x40,0x20,0x00,0x00,0x08,0x08,0x65,0x82,0x08,0x09,0x20,0x44, - 0x80,0x80,0x38,0x41,0x10,0x80,0x28,0x10,0x20,0x49,0x94,0x20,0x01,0x82,0x24, - 0x00,0x82,0x20,0x88,0x88,0x24,0x08,0x10,0x10,0x20,0x80,0x00,0x02,0x00,0x00, - 0x00,0x80,0x04,0x09,0x10,0x24,0xc8,0x87,0x10,0x41,0x10,0x80,0x68,0x80,0x20, - 0x49,0x90,0x20,0x41,0x82,0x08,0x09,0x40,0x20,0x84,0x88,0x24,0x14,0x42,0x40, - 0x60,0x80,0x00,0x03,0x00,0xe0,0x00,0x10,0x00,0xf8,0x81,0x84,0x44,0x14,0x00, - 0x04,0x20,0x50,0x40,0x00,0x00,0x00,0x00,0x02,0x41,0x10,0x30,0x00,0xf2,0x07, - 0x48,0x10,0x02,0x41,0x80,0x00,0x00,0x40,0x00,0x00,0x04,0x04,0x59,0xfe,0x08, - 0x09,0x20,0x44,0x80,0x80,0x20,0x41,0x10,0x80,0x48,0x10,0x20,0x49,0x98,0x20, - 0x01,0x82,0x44,0x00,0x82,0x20,0x08,0x85,0x24,0x14,0x10,0x08,0x20,0x00,0x01, - 0x02,0x00,0x00,0x00,0xfc,0x04,0x09,0x10,0xe4,0x0f,0x81,0x10,0x41,0x10,0x80, - 0x18,0x80,0x20,0x49,0x90,0x20,0x41,0x82,0x08,0xf0,0x41,0x20,0x84,0x88,0x24, - 0x08,0x42,0x20,0x80,0x80,0x80,0x00,0x00,0xe0,0x00,0x10,0x00,0x90,0x80,0x44, - 0x4a,0x08,0x00,0x08,0x10,0x88,0x40,0x00,0x00,0x00,0x00,0x01,0x41,0x10,0x08, - 0x00,0x02,0x02,0x48,0x10,0x02,0x41,0x80,0x00,0x00,0x80,0xe0,0x0f,0x02,0x04, - 0x01,0x82,0x08,0x09,0x20,0x44,0x80,0x80,0x20,0x41,0x10,0x80,0x88,0x10,0x20, - 0x48,0x90,0x20,0x01,0x92,0x84,0x00,0x82,0x20,0x08,0x85,0x24,0x22,0x10,0x04, - 0x20,0x00,0x02,0x02,0x00,0x00,0x00,0x82,0x04,0x09,0x10,0x24,0x00,0x01,0x0f, - 0x41,0x10,0x80,0x68,0x80,0x20,0x49,0x90,0x20,0x41,0x82,0x08,0x00,0x42,0x20, - 0x04,0x85,0x24,0x14,0x42,0x10,0x40,0x80,0x00,0x01,0x00,0xe0,0x00,0x00,0x00, - 0x90,0xe0,0x43,0x4a,0x0c,0x00,0x08,0x10,0x00,0x40,0xc0,0x01,0x00,0x02,0x01, - 0x22,0x10,0x04,0x08,0x02,0x22,0x48,0x10,0x01,0x41,0x40,0x20,0xe0,0x00,0x01, - 0x00,0x01,0x00,0x01,0x82,0x08,0x09,0x22,0x44,0x80,0x80,0x20,0x41,0x10,0x84, - 0x08,0x11,0x20,0x48,0x90,0x20,0x01,0xa2,0x04,0x09,0x82,0x20,0x08,0x85,0x2a, - 0x41,0x10,0x04,0x20,0x00,0x02,0x02,0x00,0x00,0x00,0xc2,0x0c,0x09,0x12,0x26, - 0x00,0x81,0x00,0x41,0x10,0x80,0x88,0x81,0x20,0x49,0x90,0x20,0x43,0xc2,0x08, - 0x08,0x42,0x24,0x04,0x85,0x2a,0x22,0x62,0x08,0x40,0x80,0x00,0x01,0x00,0xe0, - 0x00,0x10,0x00,0x00,0x80,0x20,0x84,0x13,0x00,0x10,0x08,0x00,0x00,0xc0,0x00, - 0x00,0x87,0x00,0x1c,0x7c,0xfc,0xf1,0x01,0xc2,0x87,0x0f,0x01,0x3e,0x3c,0x70, - 0x60,0x00,0x02,0x80,0x00,0x04,0x3e,0x82,0xfc,0xf0,0xf1,0xe3,0x8f,0x00,0x1f, - 0x41,0x7c,0x78,0x08,0xf2,0x27,0x48,0x10,0x1f,0x01,0x7c,0x04,0xf1,0x81,0xc0, - 0x07,0x02,0x11,0x41,0x10,0xfc,0xe1,0x01,0xc4,0x03,0x00,0x00,0x00,0xbc,0xf4, - 0xf0,0xe1,0xc5,0x07,0x01,0x1f,0x41,0x7c,0x84,0x08,0xe2,0x23,0x48,0x10,0x1f, - 0x3d,0xbc,0x08,0xf0,0x81,0xc3,0x0b,0x02,0x11,0x41,0x5c,0xfc,0x81,0x83,0xe0, - 0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x20,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x20,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x3f, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x20,0x00,0x00,0x84,0x00,0x00,0x00, - 0x00,0x00,0x00,0x01,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00, - 0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x20,0x00,0x00,0x84, - 0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x42,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f, - 0x00,0x00,0x78,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x80,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x3c,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xe0 + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0xe0,0x00,0x10,0x90,0x00,0x00,0x40,0x88,0x03,0x1c,0x10,0x08,0x00, + 0x00,0x00,0x00,0x00,0x00,0x20,0x1c,0x10,0xf8,0xf8,0x03,0xe2,0x0f,0x8f,0x3f, + 0x3e,0x7c,0x00,0x00,0x00,0x02,0x80,0x00,0x1f,0x3e,0x10,0xfc,0xf0,0xf1,0xe3, + 0xcf,0x1f,0x1f,0x41,0x7c,0xe0,0x09,0x12,0x20,0x48,0x10,0x1f,0x3f,0x7c,0xfc, + 0xf0,0xf1,0x27,0x48,0x90,0x20,0x41,0x82,0xfc,0xe1,0x11,0xc0,0x03,0x02,0x00, + 0x0e,0x00,0x04,0x00,0x00,0x04,0x00,0x0e,0x00,0x01,0x00,0x00,0x08,0xc0,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x80,0x83,0xe0,0x80,0x11,0xe0,0x00,0x10,0x90,0x90,0x80,0xa0,0x44,0x04,0x0c, + 0x08,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x22,0x18,0x04,0x01,0x02,0x23, + 0x80,0x00,0x20,0x41,0x82,0x00,0x00,0x00,0x01,0x00,0x81,0x20,0x41,0x28,0x08, + 0x09,0x22,0x44,0x80,0x80,0x20,0x41,0x10,0x80,0x08,0x11,0x20,0x48,0x90,0x20, + 0x41,0x82,0x04,0x09,0x82,0x20,0x48,0x90,0x20,0x41,0x82,0x00,0x21,0x20,0x00, + 0x02,0x05,0x00,0x0c,0x00,0x04,0x00,0x00,0x04,0x00,0x11,0x00,0x01,0x10,0x80, + 0x08,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x40,0x80,0x00,0x41,0x12,0xe0,0x00,0x10,0x90,0x90,0xe0,0xa3, + 0x44,0x04,0x02,0x08,0x10,0x00,0x40,0x00,0x00,0x00,0x00,0x10,0x41,0x14,0x04, + 0x01,0x81,0x22,0x40,0x00,0x20,0x41,0x82,0x00,0x00,0x80,0x00,0x00,0x82,0x20, + 0x41,0x44,0x08,0x09,0x20,0x44,0x80,0x80,0x00,0x41,0x10,0x80,0x88,0x10,0x60, + 0xcc,0x90,0x20,0x41,0x82,0x04,0x09,0x80,0x20,0x48,0x90,0x20,0x22,0x44,0x80, + 0x20,0x20,0x00,0x82,0x08,0x00,0x10,0x00,0x04,0x00,0x00,0x04,0x00,0x11,0x00, + 0x01,0x00,0x00,0x08,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x80,0x00,0x41,0x0c,0xe0,0x00,0x10,0x00, + 0xf8,0x91,0x40,0x42,0x04,0x00,0x04,0x20,0x88,0x40,0x00,0x00,0x00,0x00,0x08, + 0x41,0x10,0x00,0x81,0x40,0xa2,0x47,0x00,0x10,0x41,0x82,0x20,0x40,0x40,0x00, + 0x00,0x04,0x20,0x79,0x82,0x08,0x09,0x20,0x44,0x80,0x80,0x00,0x41,0x10,0x80, + 0x48,0x10,0xa0,0x4a,0x91,0x20,0x41,0x82,0x04,0x09,0x80,0x20,0x88,0x88,0x20, + 0x14,0x28,0x40,0x20,0x40,0x00,0x42,0x10,0x00,0x00,0x7c,0xf4,0xf0,0xe1,0xc5, + 0x07,0x01,0x2f,0x3d,0x18,0xe0,0x08,0x82,0xe0,0x46,0x0f,0x1f,0x3d,0xbc,0xe4, + 0xf0,0xf1,0x23,0x44,0x90,0x20,0x41,0x42,0xfc,0x81,0x80,0x80,0x00,0x00,0xe0, + 0x00,0x10,0x00,0x90,0x90,0x00,0x81,0x03,0x00,0x04,0x20,0x50,0x40,0x00,0x00, + 0x00,0x00,0x04,0x41,0x10,0x80,0xc0,0x21,0x62,0x48,0x0f,0x08,0x3e,0xc2,0x70, + 0xe0,0x20,0xe0,0x0f,0x08,0x10,0x45,0x82,0xf8,0x08,0x20,0xc4,0x83,0x87,0x00, + 0x7f,0x10,0x80,0x38,0x10,0xa0,0x4a,0x92,0x20,0x3f,0x82,0xfc,0xf0,0x81,0x20, + 0x88,0x88,0x24,0x08,0x10,0x20,0x20,0x80,0x00,0x02,0x00,0x00,0x00,0x80,0x0c, + 0x09,0x12,0x26,0x08,0x81,0x10,0x43,0x10,0x80,0x88,0x81,0x20,0xc9,0x90,0x20, + 0x43,0xc2,0x18,0x09,0x42,0x20,0x44,0x90,0x20,0x22,0x42,0x80,0x60,0x80,0x00, + 0x03,0x00,0xe0,0x00,0x10,0x00,0x90,0xe0,0x03,0x41,0x04,0x00,0x04,0x20,0xfc, + 0xf9,0x03,0xe0,0x0f,0x00,0x04,0x41,0x10,0x40,0x00,0x12,0x02,0xc8,0x10,0x04, + 0x41,0xbc,0x20,0x40,0x20,0x00,0x00,0x08,0x08,0x65,0x82,0x08,0x09,0x20,0x44, + 0x80,0x80,0x38,0x41,0x10,0x80,0x28,0x10,0x20,0x49,0x94,0x20,0x01,0x82,0x24, + 0x00,0x82,0x20,0x88,0x88,0x24,0x08,0x10,0x10,0x20,0x80,0x00,0x02,0x00,0x00, + 0x00,0x80,0x04,0x09,0x10,0x24,0xc8,0x87,0x10,0x41,0x10,0x80,0x68,0x80,0x20, + 0x49,0x90,0x20,0x41,0x82,0x08,0x09,0x40,0x20,0x84,0x88,0x24,0x14,0x42,0x40, + 0x60,0x80,0x00,0x03,0x00,0xe0,0x00,0x10,0x00,0xf8,0x81,0x84,0x44,0x14,0x00, + 0x04,0x20,0x50,0x40,0x00,0x00,0x00,0x00,0x02,0x41,0x10,0x30,0x00,0xf2,0x07, + 0x48,0x10,0x02,0x41,0x80,0x00,0x00,0x40,0x00,0x00,0x04,0x04,0x59,0xfe,0x08, + 0x09,0x20,0x44,0x80,0x80,0x20,0x41,0x10,0x80,0x48,0x10,0x20,0x49,0x98,0x20, + 0x01,0x82,0x44,0x00,0x82,0x20,0x08,0x85,0x24,0x14,0x10,0x08,0x20,0x00,0x01, + 0x02,0x00,0x00,0x00,0xfc,0x04,0x09,0x10,0xe4,0x0f,0x81,0x10,0x41,0x10,0x80, + 0x18,0x80,0x20,0x49,0x90,0x20,0x41,0x82,0x08,0xf0,0x41,0x20,0x84,0x88,0x24, + 0x08,0x42,0x20,0x80,0x80,0x80,0x00,0x00,0xe0,0x00,0x10,0x00,0x90,0x80,0x44, + 0x4a,0x08,0x00,0x08,0x10,0x88,0x40,0x00,0x00,0x00,0x00,0x01,0x41,0x10,0x08, + 0x00,0x02,0x02,0x48,0x10,0x02,0x41,0x80,0x00,0x00,0x80,0xe0,0x0f,0x02,0x04, + 0x01,0x82,0x08,0x09,0x20,0x44,0x80,0x80,0x20,0x41,0x10,0x80,0x88,0x10,0x20, + 0x48,0x90,0x20,0x01,0x92,0x84,0x00,0x82,0x20,0x08,0x85,0x24,0x22,0x10,0x04, + 0x20,0x00,0x02,0x02,0x00,0x00,0x00,0x82,0x04,0x09,0x10,0x24,0x00,0x01,0x0f, + 0x41,0x10,0x80,0x68,0x80,0x20,0x49,0x90,0x20,0x41,0x82,0x08,0x00,0x42,0x20, + 0x04,0x85,0x24,0x14,0x42,0x10,0x40,0x80,0x00,0x01,0x00,0xe0,0x00,0x00,0x00, + 0x90,0xe0,0x43,0x4a,0x0c,0x00,0x08,0x10,0x00,0x40,0xc0,0x01,0x00,0x02,0x01, + 0x22,0x10,0x04,0x08,0x02,0x22,0x48,0x10,0x01,0x41,0x40,0x20,0xe0,0x00,0x01, + 0x00,0x01,0x00,0x01,0x82,0x08,0x09,0x22,0x44,0x80,0x80,0x20,0x41,0x10,0x84, + 0x08,0x11,0x20,0x48,0x90,0x20,0x01,0xa2,0x04,0x09,0x82,0x20,0x08,0x85,0x2a, + 0x41,0x10,0x04,0x20,0x00,0x02,0x02,0x00,0x00,0x00,0xc2,0x0c,0x09,0x12,0x26, + 0x00,0x81,0x00,0x41,0x10,0x80,0x88,0x81,0x20,0x49,0x90,0x20,0x43,0xc2,0x08, + 0x08,0x42,0x24,0x04,0x85,0x2a,0x22,0x62,0x08,0x40,0x80,0x00,0x01,0x00,0xe0, + 0x00,0x10,0x00,0x00,0x80,0x20,0x84,0x13,0x00,0x10,0x08,0x00,0x00,0xc0,0x00, + 0x00,0x87,0x00,0x1c,0x7c,0xfc,0xf1,0x01,0xc2,0x87,0x0f,0x01,0x3e,0x3c,0x70, + 0x60,0x00,0x02,0x80,0x00,0x04,0x3e,0x82,0xfc,0xf0,0xf1,0xe3,0x8f,0x00,0x1f, + 0x41,0x7c,0x78,0x08,0xf2,0x27,0x48,0x10,0x1f,0x01,0x7c,0x04,0xf1,0x81,0xc0, + 0x07,0x02,0x11,0x41,0x10,0xfc,0xe1,0x01,0xc4,0x03,0x00,0x00,0x00,0xbc,0xf4, + 0xf0,0xe1,0xc5,0x07,0x01,0x1f,0x41,0x7c,0x84,0x08,0xe2,0x23,0x48,0x10,0x1f, + 0x3d,0xbc,0x08,0xf0,0x81,0xc3,0x0b,0x02,0x11,0x41,0x5c,0xfc,0x81,0x83,0xe0, + 0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x20,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x20,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x3f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x20,0x00,0x00,0x84,0x00,0x00,0x00, + 0x00,0x00,0x00,0x01,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00, + 0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x20,0x00,0x00,0x84, + 0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x42,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1f, + 0x00,0x00,0x78,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x80,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x3c,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xe0 }; // Construct object with no string set and backing enabled. vvLandmarksGlyph::vvLandmarksGlyph() { - this->Text = NULL; - this->Backing = 1; - this->ForegroundColor[0] = 1.0; - this->ForegroundColor[1] = 1.0; - this->ForegroundColor[2] = 1.0; - this->ForegroundColor[3] = 1.0; - this->BackgroundColor[0] = 0.0; - this->BackgroundColor[1] = 0.0; - this->BackgroundColor[2] = 0.0; - this->BackgroundColor[3] = 1.0; - - this->SetNumberOfInputPorts(0); + this->Text = NULL; + this->Backing = 1; + this->ForegroundColor[0] = 1.0; + this->ForegroundColor[1] = 1.0; + this->ForegroundColor[2] = 1.0; + this->ForegroundColor[3] = 1.0; + this->BackgroundColor[0] = 0.0; + this->BackgroundColor[1] = 0.0; + this->BackgroundColor[2] = 0.0; + this->BackgroundColor[3] = 1.0; + + this->SetNumberOfInputPorts(0); } vvLandmarksGlyph::~vvLandmarksGlyph() { - if (this->Text) - { - delete [] this->Text; - } + if (this->Text) { + delete [] this->Text; + } } int vvLandmarksGlyph::RequestData( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) { - // get the info object - vtkInformation *outInfo = outputVector->GetInformationObject(0); + // get the info object + vtkInformation *outInfo = outputVector->GetInformationObject(0); - // get the ouptut - vtkPolyData *output = vtkPolyData::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); + // get the ouptut + vtkPolyData *output = vtkPolyData::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkPoints *newPoints; - vtkCellArray *newPolys; - vtkCellArray *newLines; - vtkUnsignedCharArray *newScalars; + vtkPoints *newPoints; + vtkCellArray *newPolys; + vtkCellArray *newLines; + vtkUnsignedCharArray *newScalars; - newPoints = vtkPoints::New(); - newPolys = vtkCellArray::New(); - newScalars = vtkUnsignedCharArray::New(); - newScalars->SetNumberOfComponents(4); - newLines = vtkCellArray::New(); - newLines->Allocate(newLines->EstimateSize(3,2)); + newPoints = vtkPoints::New(); + newPolys = vtkCellArray::New(); + newScalars = vtkUnsignedCharArray::New(); + newScalars->SetNumberOfComponents(4); + newLines = vtkCellArray::New(); + newLines->Allocate(newLines->EstimateSize(3,2)); - AddTextGlyph(newPoints,newScalars,newPolys,0); - AddTextGlyph(newPoints,newScalars,newPolys,1); - AddTextGlyph(newPoints,newScalars,newPolys,2); + AddTextGlyph(newPoints,newScalars,newPolys,0); + AddTextGlyph(newPoints,newScalars,newPolys,1); + AddTextGlyph(newPoints,newScalars,newPolys,2); - AddCrossGlyph(newPoints, newLines); + AddCrossGlyph(newPoints, newLines); - output->SetPoints(newPoints); - newPoints->Delete(); + output->SetPoints(newPoints); + newPoints->Delete(); - output->SetLines(newLines); - newLines->Delete(); + output->SetLines(newLines); + newLines->Delete(); - output->GetPointData()->SetScalars(newScalars); - newScalars->Delete(); + output->GetPointData()->SetScalars(newScalars); + newScalars->Delete(); - output->SetPolys(newPolys); - newPolys->Delete(); + output->SetPolys(newPolys); + newPolys->Delete(); - return 1; + return 1; } void vvLandmarksGlyph::AddTextGlyph(vtkPoints* newPoints,vtkUnsignedCharArray* newScalars, vtkCellArray *newPolys, int orientation) { - int row, col; - int pos = 0; - int pixelPos; - vtkIdType pts[5]; - vtkIdType numPolys = 0; - double x[3]; - int acol; - int drawingWhite = 0; - int drawingBlack = 0; - unsigned char white[4]; - unsigned char black[4]; - std::cout << "AddTextGlyph(output," << orientation << ")" << std::endl; - - if (this->Text == NULL) - { - vtkErrorMacro (<< "Text is not set!"); - return; - } - - // convert colors to unsigned char - for (int i = 0; i < 4; i++) - { - white[i] = (unsigned char) (this->ForegroundColor[i] * 255.0); - black[i] = (unsigned char) (this->BackgroundColor[i] * 255.0); - } - - std::cout << "Create Text" << std::endl; - // Create Text - while (this->Text[pos]) - { - if (this->Text[pos] != 32) - { - for (col = 0; col < vtkfont_width; col++) - { - acol = (this->Text[pos] - 32)*vtkfont_width + col - 1; - for (row = 0; row < vtkfont_height; row++) - { - pixelPos = acol + row*vtkfont_row_width; - if (vtkfont_bits[pixelPos/8] & (0x01 << pixelPos%8)) - { - if (drawingBlack) - { - x[0] = pos*vtkfont_width + col + 1; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - x[0] = pos*vtkfont_width + col; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - pts[0] = numPolys*4; - pts[1] = numPolys*4 + 1; - pts[2] = numPolys*4 + 2; - pts[3] = numPolys*4 + 3; - newPolys->InsertNextCell(4,pts); - numPolys++; - drawingBlack = 0; - } - if (!drawingWhite) - { - x[0] = pos*vtkfont_width + col; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(white[0]); - newScalars->InsertNextValue(white[1]); - newScalars->InsertNextValue(white[2]); - newScalars->InsertNextValue(white[3]); - - x[0] = pos*vtkfont_width + col + 1; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(white[0]); - newScalars->InsertNextValue(white[1]); - newScalars->InsertNextValue(white[2]); - newScalars->InsertNextValue(white[3]); - drawingWhite = 1; - } - } - // if the pixel is not set the close up the rectangle - else - { - if (drawingWhite) - { - x[0] = pos*vtkfont_width + col + 1; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(white[0]); - newScalars->InsertNextValue(white[1]); - newScalars->InsertNextValue(white[2]); - newScalars->InsertNextValue(white[3]); - - x[0] = pos*vtkfont_width + col; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(white[0]); - newScalars->InsertNextValue(white[1]); - newScalars->InsertNextValue(white[2]); - newScalars->InsertNextValue(white[3]); - - pts[0] = numPolys*4; - pts[1] = numPolys*4 + 1; - pts[2] = numPolys*4 + 2; - pts[3] = numPolys*4 + 3; - newPolys->InsertNextCell(4,pts); - numPolys++; - drawingWhite = 0; - } - if (!drawingBlack && this->Backing) - { - x[0] = pos*vtkfont_width + col; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - x[0] = pos*vtkfont_width + col + 1; - x[1] = vtkfont_height - row; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - drawingBlack = 1; - } - } - } - // if we finished up a row but are still drawing close it up - if (drawingWhite) - { - x[0] = pos*vtkfont_width + col + 1; - x[1] = 0; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(white[0]); - newScalars->InsertNextValue(white[1]); - newScalars->InsertNextValue(white[2]); - newScalars->InsertNextValue(white[3]); - - x[0] = pos*vtkfont_width + col; - x[1] = 0; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(white[0]); - newScalars->InsertNextValue(white[1]); - newScalars->InsertNextValue(white[2]); - newScalars->InsertNextValue(white[3]); - - pts[0] = numPolys*4; - pts[1] = numPolys*4 + 1; - pts[2] = numPolys*4 + 2; - pts[3] = numPolys*4 + 3; - newPolys->InsertNextCell(4,pts); - numPolys++; - drawingWhite = 0; - } - if (drawingBlack) - { - x[0] = pos*vtkfont_width + col + 1; - x[1] = 0; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - x[0] = pos*vtkfont_width + col; - x[1] = 0; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - pts[0] = numPolys*4; - pts[1] = numPolys*4 + 1; - pts[2] = numPolys*4 + 2; - pts[3] = numPolys*4 + 3; - newPolys->InsertNextCell(4,pts); - numPolys++; - drawingBlack = 0; - } + int row, col; + int pos = 0; + int pixelPos; + vtkIdType pts[5]; + vtkIdType numPolys = 0; + double x[3]; + int acol; + int drawingWhite = 0; + int drawingBlack = 0; + unsigned char white[4]; + unsigned char black[4]; + std::cout << "AddTextGlyph(output," << orientation << ")" << std::endl; + + if (this->Text == NULL) { + vtkErrorMacro (<< "Text is not set!"); + return; + } + + // convert colors to unsigned char + for (int i = 0; i < 4; i++) { + white[i] = (unsigned char) (this->ForegroundColor[i] * 255.0); + black[i] = (unsigned char) (this->BackgroundColor[i] * 255.0); + } + + std::cout << "Create Text" << std::endl; + // Create Text + while (this->Text[pos]) { + if (this->Text[pos] != 32) { + for (col = 0; col < vtkfont_width; col++) { + acol = (this->Text[pos] - 32)*vtkfont_width + col - 1; + for (row = 0; row < vtkfont_height; row++) { + pixelPos = acol + row*vtkfont_row_width; + if (vtkfont_bits[pixelPos/8] & (0x01 << pixelPos%8)) { + if (drawingBlack) { + x[0] = pos*vtkfont_width + col + 1; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + x[0] = pos*vtkfont_width + col; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + pts[0] = numPolys*4; + pts[1] = numPolys*4 + 1; + pts[2] = numPolys*4 + 2; + pts[3] = numPolys*4 + 3; + newPolys->InsertNextCell(4,pts); + numPolys++; + drawingBlack = 0; } - } - else - { - // draw a black square for a space - if (this->Backing) - { - x[0] = pos*vtkfont_width; - x[1] = vtkfont_height; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - x[0] = pos*vtkfont_width + vtkfont_width; - x[1] = vtkfont_height; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - x[0] = pos*vtkfont_width + vtkfont_width; - x[1] = 0; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - x[0] = pos*vtkfont_width; - x[1] = 0; - x[2] = 0; - ChangeOrientation(x,orientation); - newPoints->InsertNextPoint(x); - newScalars->InsertNextValue(black[0]); - newScalars->InsertNextValue(black[1]); - newScalars->InsertNextValue(black[2]); - newScalars->InsertNextValue(black[3]); - - pts[0] = numPolys*4; - pts[1] = numPolys*4 + 1; - pts[2] = numPolys*4 + 2; - pts[3] = numPolys*4 + 3; - newPolys->InsertNextCell(4,pts); - numPolys++; + if (!drawingWhite) { + x[0] = pos*vtkfont_width + col; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(white[0]); + newScalars->InsertNextValue(white[1]); + newScalars->InsertNextValue(white[2]); + newScalars->InsertNextValue(white[3]); + + x[0] = pos*vtkfont_width + col + 1; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(white[0]); + newScalars->InsertNextValue(white[1]); + newScalars->InsertNextValue(white[2]); + newScalars->InsertNextValue(white[3]); + drawingWhite = 1; } + } + // if the pixel is not set the close up the rectangle + else { + if (drawingWhite) { + x[0] = pos*vtkfont_width + col + 1; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(white[0]); + newScalars->InsertNextValue(white[1]); + newScalars->InsertNextValue(white[2]); + newScalars->InsertNextValue(white[3]); + + x[0] = pos*vtkfont_width + col; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(white[0]); + newScalars->InsertNextValue(white[1]); + newScalars->InsertNextValue(white[2]); + newScalars->InsertNextValue(white[3]); + + pts[0] = numPolys*4; + pts[1] = numPolys*4 + 1; + pts[2] = numPolys*4 + 2; + pts[3] = numPolys*4 + 3; + newPolys->InsertNextCell(4,pts); + numPolys++; + drawingWhite = 0; + } + if (!drawingBlack && this->Backing) { + x[0] = pos*vtkfont_width + col; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + x[0] = pos*vtkfont_width + col + 1; + x[1] = vtkfont_height - row; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + drawingBlack = 1; + } + } + } + // if we finished up a row but are still drawing close it up + if (drawingWhite) { + x[0] = pos*vtkfont_width + col + 1; + x[1] = 0; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(white[0]); + newScalars->InsertNextValue(white[1]); + newScalars->InsertNextValue(white[2]); + newScalars->InsertNextValue(white[3]); + + x[0] = pos*vtkfont_width + col; + x[1] = 0; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(white[0]); + newScalars->InsertNextValue(white[1]); + newScalars->InsertNextValue(white[2]); + newScalars->InsertNextValue(white[3]); + + pts[0] = numPolys*4; + pts[1] = numPolys*4 + 1; + pts[2] = numPolys*4 + 2; + pts[3] = numPolys*4 + 3; + newPolys->InsertNextCell(4,pts); + numPolys++; + drawingWhite = 0; } - pos++; + if (drawingBlack) { + x[0] = pos*vtkfont_width + col + 1; + x[1] = 0; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + x[0] = pos*vtkfont_width + col; + x[1] = 0; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + pts[0] = numPolys*4; + pts[1] = numPolys*4 + 1; + pts[2] = numPolys*4 + 2; + pts[3] = numPolys*4 + 3; + newPolys->InsertNextCell(4,pts); + numPolys++; + drawingBlack = 0; + } + } + } else { + // draw a black square for a space + if (this->Backing) { + x[0] = pos*vtkfont_width; + x[1] = vtkfont_height; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + x[0] = pos*vtkfont_width + vtkfont_width; + x[1] = vtkfont_height; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + x[0] = pos*vtkfont_width + vtkfont_width; + x[1] = 0; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + x[0] = pos*vtkfont_width; + x[1] = 0; + x[2] = 0; + ChangeOrientation(x,orientation); + newPoints->InsertNextPoint(x); + newScalars->InsertNextValue(black[0]); + newScalars->InsertNextValue(black[1]); + newScalars->InsertNextValue(black[2]); + newScalars->InsertNextValue(black[3]); + + pts[0] = numPolys*4; + pts[1] = numPolys*4 + 1; + pts[2] = numPolys*4 + 2; + pts[3] = numPolys*4 + 3; + newPolys->InsertNextCell(4,pts); + numPolys++; + } } + pos++; + } } void vvLandmarksGlyph::AddCrossGlyph(vtkPoints* newPts,vtkCellArray* newLines) { - vtkIdType ptIds[2]; - double x[3]; - std::cout << "AddCross" << std::endl; - x[0] = -10; - x[1] = 0; - x[2] = 0; - ptIds[0] = newPts->InsertNextPoint(x); - - x[0] = 10; - x[1] = 0; - x[2] = 0; - ptIds[1] = newPts->InsertNextPoint(x); - newLines->InsertNextCell(2,ptIds); - - x[0] = 0; - x[1] = -10; - x[2] = 0; - ptIds[0] = newPts->InsertNextPoint(x); - - x[0] = 0; - x[1] = 10; - x[2] = 0; - ptIds[1] = newPts->InsertNextPoint(x); - newLines->InsertNextCell(2,ptIds); - - x[0] = 0; - x[1] = 0; - x[2] = -10; - ptIds[0] = newPts->InsertNextPoint(x); - - x[0] = 0; - x[1] = 0; - x[2] = 10; - ptIds[1] = newPts->InsertNextPoint(x); - newLines->InsertNextCell(2,ptIds); + vtkIdType ptIds[2]; + double x[3]; + std::cout << "AddCross" << std::endl; + x[0] = -10; + x[1] = 0; + x[2] = 0; + ptIds[0] = newPts->InsertNextPoint(x); + + x[0] = 10; + x[1] = 0; + x[2] = 0; + ptIds[1] = newPts->InsertNextPoint(x); + newLines->InsertNextCell(2,ptIds); + + x[0] = 0; + x[1] = -10; + x[2] = 0; + ptIds[0] = newPts->InsertNextPoint(x); + + x[0] = 0; + x[1] = 10; + x[2] = 0; + ptIds[1] = newPts->InsertNextPoint(x); + newLines->InsertNextCell(2,ptIds); + + x[0] = 0; + x[1] = 0; + x[2] = -10; + ptIds[0] = newPts->InsertNextPoint(x); + + x[0] = 0; + x[1] = 0; + x[2] = 10; + ptIds[1] = newPts->InsertNextPoint(x); + newLines->InsertNextCell(2,ptIds); } void vvLandmarksGlyph::ChangeOrientation(double v[3],int orientation) { - double x=0,y=0,z=0; - switch (orientation) - { - case 0: - x = v[1]; - y = v[2]; - z = v[0]; - break; - case 1: - x = v[2]; - y = v[0]; - z = v[1]; - break; - case 2: - x = v[0]; - y = v[1]; - z = v[2]; - break; - default: - assert(false); //This definitely shouldn't happen - } - v[0] = x; - v[1] = y; - v[2] = z; + double x=0,y=0,z=0; + switch (orientation) { + case 0: + x = v[1]; + y = v[2]; + z = v[0]; + break; + case 1: + x = v[2]; + y = v[0]; + z = v[1]; + break; + case 2: + x = v[0]; + y = v[1]; + z = v[2]; + break; + default: + assert(false); //This definitely shouldn't happen + } + v[0] = x; + v[1] = y; + v[2] = z; } void vvLandmarksGlyph::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); - - os << indent << "Text: " << (this->Text ? this->Text : "(none)") << "\n"; - os << indent << "Background Drawn: " << (this->Backing ? "On\n" : "Off\n"); - os << indent << "ForegroundColor: (" << this->ForegroundColor[0] << ", " - << this->ForegroundColor[1] << ", " << this->ForegroundColor[2] << ")\n"; - os << indent << "BackgroundColor: (" << this->BackgroundColor[0] << ", " - << this->BackgroundColor[1] << ", " << this->BackgroundColor[2] << ")\n"; + this->Superclass::PrintSelf(os,indent); + + os << indent << "Text: " << (this->Text ? this->Text : "(none)") << "\n"; + os << indent << "Background Drawn: " << (this->Backing ? "On\n" : "Off\n"); + os << indent << "ForegroundColor: (" << this->ForegroundColor[0] << ", " + << this->ForegroundColor[1] << ", " << this->ForegroundColor[2] << ")\n"; + os << indent << "BackgroundColor: (" << this->BackgroundColor[0] << ", " + << this->BackgroundColor[1] << ", " << this->BackgroundColor[2] << ")\n"; } diff --git a/vv/vvLandmarksPanel.cxx b/vv/vvLandmarksPanel.cxx index 32b9e82..4607883 100644 --- a/vv/vvLandmarksPanel.cxx +++ b/vv/vvLandmarksPanel.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -29,126 +29,123 @@ //==================================================================== vvLandmarksPanel::vvLandmarksPanel(QWidget * parent):QWidget(parent) { - setupUi(this); - - tableWidget->verticalHeader()->hide(); - loadButton->setEnabled(0); - saveButton->setEnabled(0); - removeButton->setEnabled(0); - connect(loadButton, SIGNAL(clicked()),this,SLOT(Load())); - connect(saveButton, SIGNAL(clicked()),this,SLOT(Save())); - connect(removeButton, SIGNAL(clicked()),this,SLOT(RemoveLastPoint())); - connect(tableWidget,SIGNAL(cellChanged(int,int)),this,SLOT(CommentsChanged(int,int))); + setupUi(this); + + tableWidget->verticalHeader()->hide(); + loadButton->setEnabled(0); + saveButton->setEnabled(0); + removeButton->setEnabled(0); + connect(loadButton, SIGNAL(clicked()),this,SLOT(Load())); + connect(saveButton, SIGNAL(clicked()),this,SLOT(Save())); + connect(removeButton, SIGNAL(clicked()),this,SLOT(RemoveLastPoint())); + connect(tableWidget,SIGNAL(cellChanged(int,int)),this,SLOT(CommentsChanged(int,int))); } void vvLandmarksPanel::Load() { - QString file = QFileDialog::getOpenFileName(this,tr("Load Landmarks"), - mCurrentPath.c_str(),tr("Landmarks ( *.txt)")); - if (!file.isEmpty()) - mCurrentLandmarks->LoadFile(file.toStdString()); - SetCurrentLandmarks(mCurrentLandmarks,2); - emit UpdateRenderWindows(); + QString file = QFileDialog::getOpenFileName(this,tr("Load Landmarks"), + mCurrentPath.c_str(),tr("Landmarks ( *.txt)")); + if (!file.isEmpty()) + mCurrentLandmarks->LoadFile(file.toStdString()); + SetCurrentLandmarks(mCurrentLandmarks,2); + emit UpdateRenderWindows(); } void vvLandmarksPanel::Save() { - QString file = QFileDialog::getSaveFileName(this, - tr("Save Landmarks"), - mCurrentPath.c_str(),tr("Landmarks ( *.txt)")); - if (!file.isEmpty()) - { - std::string filename = vtksys::SystemTools::GetFilenamePath(file.toStdString()); - filename += "/" + vtksys::SystemTools::GetFilenameWithoutLastExtension(file.toStdString()); - filename += ".txt"; - mCurrentLandmarks->SaveFile(filename.c_str()); - } + QString file = QFileDialog::getSaveFileName(this, + tr("Save Landmarks"), + mCurrentPath.c_str(),tr("Landmarks ( *.txt)")); + if (!file.isEmpty()) { + std::string filename = vtksys::SystemTools::GetFilenamePath(file.toStdString()); + filename += "/" + vtksys::SystemTools::GetFilenameWithoutLastExtension(file.toStdString()); + filename += ".txt"; + mCurrentLandmarks->SaveFile(filename.c_str()); + } } void vvLandmarksPanel::RemoveLastPoint() { - if (tableWidget->rowCount() > 0) - { - tableWidget->removeRow(tableWidget->rowCount()-1); - mCurrentLandmarks->RemoveLastLandmark(); - emit UpdateRenderWindows(); - } + if (tableWidget->rowCount() > 0) { + tableWidget->removeRow(tableWidget->rowCount()-1); + mCurrentLandmarks->RemoveLastLandmark(); + emit UpdateRenderWindows(); + } } void vvLandmarksPanel::AddPoint() { - AddPoint(mCurrentLandmarks->GetNumberOfPoints()-1); + AddPoint(mCurrentLandmarks->GetNumberOfPoints()-1); } void vvLandmarksPanel::AddPoint(int landmarksIndex) { - int rowIndex = landmarksIndex; //tableWidget->rowCount(); - tableWidget->setRowCount(rowIndex+1); - tableWidget->setRowHeight(rowIndex,20); - QTableWidgetItem* iItem = new QTableWidgetItem(QString::number(landmarksIndex)); - iItem->setFlags(Qt::NoItemFlags); - tableWidget->setItem(rowIndex,0,iItem); - - QTableWidgetItem* xItem = new QTableWidgetItem( - QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[0],'f',1)); - xItem->setFlags(Qt::NoItemFlags); - tableWidget->setItem(rowIndex,1,xItem); - - QTableWidgetItem* yItem = new QTableWidgetItem( - QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[1],'f',1)); - yItem->setFlags(Qt::NoItemFlags); - tableWidget->setItem(rowIndex,2,yItem); - - QTableWidgetItem* zItem = new QTableWidgetItem( - QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[2],'f',1)); - zItem->setFlags(Qt::NoItemFlags); - tableWidget->setItem(rowIndex,3,zItem); - - QTableWidgetItem* tItem = new QTableWidgetItem( - QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[3],'f',1)); - tItem->setFlags(Qt::NoItemFlags); - tableWidget->setItem(rowIndex,4,tItem); - - - QTableWidgetItem* vItem = new QTableWidgetItem( - QString::number(mCurrentLandmarks->GetPixelValue(landmarksIndex),'f',1)); - vItem->setFlags(Qt::NoItemFlags); - tableWidget->setItem(rowIndex,5,vItem); - - tableWidget->setItem(rowIndex,6, new QTableWidgetItem(mCurrentLandmarks->GetComments(landmarksIndex).c_str())); + int rowIndex = landmarksIndex; //tableWidget->rowCount(); + tableWidget->setRowCount(rowIndex+1); + tableWidget->setRowHeight(rowIndex,20); + QTableWidgetItem* iItem = new QTableWidgetItem(QString::number(landmarksIndex)); + iItem->setFlags(Qt::NoItemFlags); + tableWidget->setItem(rowIndex,0,iItem); + + QTableWidgetItem* xItem = new QTableWidgetItem( + QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[0],'f',1)); + xItem->setFlags(Qt::NoItemFlags); + tableWidget->setItem(rowIndex,1,xItem); + + QTableWidgetItem* yItem = new QTableWidgetItem( + QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[1],'f',1)); + yItem->setFlags(Qt::NoItemFlags); + tableWidget->setItem(rowIndex,2,yItem); + + QTableWidgetItem* zItem = new QTableWidgetItem( + QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[2],'f',1)); + zItem->setFlags(Qt::NoItemFlags); + tableWidget->setItem(rowIndex,3,zItem); + + QTableWidgetItem* tItem = new QTableWidgetItem( + QString::number(mCurrentLandmarks->GetCoordinates(landmarksIndex)[3],'f',1)); + tItem->setFlags(Qt::NoItemFlags); + tableWidget->setItem(rowIndex,4,tItem); + + + QTableWidgetItem* vItem = new QTableWidgetItem( + QString::number(mCurrentLandmarks->GetPixelValue(landmarksIndex),'f',1)); + vItem->setFlags(Qt::NoItemFlags); + tableWidget->setItem(rowIndex,5,vItem); + + tableWidget->setItem(rowIndex,6, new QTableWidgetItem(mCurrentLandmarks->GetComments(landmarksIndex).c_str())); } void vvLandmarksPanel::SetCurrentLandmarks(vvLandmarks* lm,int time) { - loadButton->setEnabled(1); - saveButton->setEnabled(1); - removeButton->setEnabled(1); - mCurrentLandmarks = lm; - tableWidget->clearContents(); - tableWidget->setRowCount(mCurrentLandmarks->GetNumberOfPoints()); - for (int i = 0; i < mCurrentLandmarks->GetNumberOfPoints(); i++) - AddPoint(i); - //if (time > 1) - //tableWidget->setColumnHidden(4,1); - //else - //tableWidget->setColumnHidden(4,0); - tableWidget->resizeColumnsToContents(); + loadButton->setEnabled(1); + saveButton->setEnabled(1); + removeButton->setEnabled(1); + mCurrentLandmarks = lm; + tableWidget->clearContents(); + tableWidget->setRowCount(mCurrentLandmarks->GetNumberOfPoints()); + for (int i = 0; i < mCurrentLandmarks->GetNumberOfPoints(); i++) + AddPoint(i); + //if (time > 1) + //tableWidget->setColumnHidden(4,1); + //else + //tableWidget->setColumnHidden(4,0); + tableWidget->resizeColumnsToContents(); } void vvLandmarksPanel::SetCurrentImage(std::string filename) { - QString image = "CurrentImage : "; - image += vtksys::SystemTools::GetFilenameWithoutLastExtension(filename).c_str(); - nameLabel->setText(image); + QString image = "CurrentImage : "; + image += vtksys::SystemTools::GetFilenameWithoutLastExtension(filename).c_str(); + nameLabel->setText(image); } void vvLandmarksPanel::CommentsChanged(int row, int column) { - if (column == 6) - { - mCurrentLandmarks->ChangeComments(row,std::string(tableWidget->item(row,column)->text().toStdString())); - tableWidget->resizeColumnsToContents(); - } + if (column == 6) { + mCurrentLandmarks->ChangeComments(row,std::string(tableWidget->item(row,column)->text().toStdString())); + tableWidget->resizeColumnsToContents(); + } } #endif /* end #define _vvLandmarksPanel_CXX */ diff --git a/vv/vvLinkPanel.cxx b/vv/vvLinkPanel.cxx index 5cfd853..7dc2e88 100644 --- a/vv/vvLinkPanel.cxx +++ b/vv/vvLinkPanel.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -63,24 +63,21 @@ void vvLinkPanel::removeImage(int index) std::string idRemoved = image1Ids[index]; std::vector::iterator Nameiter = imageNames.begin(); std::vector::iterator Iditer = image1Ids.begin(); - for (int i = 0; i < index; i++) - { - Nameiter++; - Iditer++; - } + for (int i = 0; i < index; i++) { + Nameiter++; + Iditer++; + } imageNames.erase(Nameiter); image1Ids.erase(Iditer); UpdateComboBox1(); - for (int i = linkTableWidget->rowCount() - 1; i >= 0 ;i--) - { - if (linkTableWidget->item(i,4)->text().toStdString() == idRemoved || - linkTableWidget->item(i,5)->text().toStdString() == idRemoved) - { - emit removeLink(linkTableWidget->item(i,4)->text(),linkTableWidget->item(i,5)->text()); - linkTableWidget->removeRow(i); - UpdateComboBox2(image1ComboBox->currentIndex()); - } + for (int i = linkTableWidget->rowCount() - 1; i >= 0 ; i--) { + if (linkTableWidget->item(i,4)->text().toStdString() == idRemoved || + linkTableWidget->item(i,5)->text().toStdString() == idRemoved) { + emit removeLink(linkTableWidget->item(i,4)->text(),linkTableWidget->item(i,5)->text()); + linkTableWidget->removeRow(i); + UpdateComboBox2(image1ComboBox->currentIndex()); } + } } //------------------------------------------------------------------------------ @@ -89,10 +86,9 @@ void vvLinkPanel::removeImage(int index) void vvLinkPanel::UpdateComboBox1() { image1ComboBox->clear(); - for (unsigned int i = 0; i < imageNames.size();i++) - { - image1ComboBox->addItem(imageNames[i].c_str()); - } + for (unsigned int i = 0; i < imageNames.size(); i++) { + image1ComboBox->addItem(imageNames[i].c_str()); + } } //------------------------------------------------------------------------------ @@ -102,32 +98,26 @@ void vvLinkPanel::UpdateComboBox2(int index) { image2ComboBox->clear(); image2Ids.resize(0); - if (imageNames.size() > 1 && index >= 0) - { - for (unsigned int i = 0; i < imageNames.size();i++) - { - if ((int)i != index) - { - bool AlreadyLinked = false; - for (int row = 0; row < linkTableWidget->rowCount();row++) - { - if ((linkTableWidget->item(row,1)->text().toStdString() == imageNames[index] && - linkTableWidget->item(row,3)->text().toStdString() == imageNames[i]) || - (linkTableWidget->item(row,3)->text().toStdString() == imageNames[index] && - linkTableWidget->item(row,1)->text().toStdString() == imageNames[i])) - { - AlreadyLinked = true; - break; - } - } - if (!AlreadyLinked) - { - image2ComboBox->addItem(imageNames[i].c_str()); - image2Ids.push_back(image1Ids[i]); - } - } + if (imageNames.size() > 1 && index >= 0) { + for (unsigned int i = 0; i < imageNames.size(); i++) { + if ((int)i != index) { + bool AlreadyLinked = false; + for (int row = 0; row < linkTableWidget->rowCount(); row++) { + if ((linkTableWidget->item(row,1)->text().toStdString() == imageNames[index] && + linkTableWidget->item(row,3)->text().toStdString() == imageNames[i]) || + (linkTableWidget->item(row,3)->text().toStdString() == imageNames[index] && + linkTableWidget->item(row,1)->text().toStdString() == imageNames[i])) { + AlreadyLinked = true; + break; + } + } + if (!AlreadyLinked) { + image2ComboBox->addItem(imageNames[i].c_str()); + image2Ids.push_back(image1Ids[i]); } + } } + } if (image2ComboBox->count() == 0) linkButton->setEnabled(0); else @@ -144,13 +134,12 @@ void vvLinkPanel::linkAll() removeLink(1,1); //Now create all possible links int count=image2ComboBox->count(); - for (int j=0;jsetCurrentIndex(j); - image2ComboBox->setCurrentIndex(0); - for (int i=0;i< count-j;i++) - addLink(); - } + for (int j=0; jsetCurrentIndex(j); + image2ComboBox->setCurrentIndex(0); + for (int i=0; i< count-j; i++) + addLink(); + } } //------------------------------------------------------------------------------ @@ -159,35 +148,34 @@ void vvLinkPanel::linkAll() void vvLinkPanel::addLink() { if (!image1ComboBox->currentText().isEmpty() - && !image2ComboBox->currentText().isEmpty()) - { - int row = linkTableWidget->rowCount(); - linkTableWidget->insertRow(row); - - linkTableWidget->setItem(row,1,new QTableWidgetItem(image1ComboBox->currentText())); - linkTableWidget->setItem(row,2,new QTableWidgetItem("&")); - linkTableWidget->setItem(row,3,new QTableWidgetItem(image2ComboBox->currentText())); - linkTableWidget->setItem(row,4,new QTableWidgetItem(image1Ids[image1ComboBox->currentIndex()].c_str())); - linkTableWidget->setItem(row,5,new QTableWidgetItem(image2Ids[image2ComboBox->currentIndex()].c_str())); - QTreePushButton* cButton = new QTreePushButton; - cButton->setIndex(linkTableWidget->rowCount()); - cButton->setColumn(0); - cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); - connect(cButton,SIGNAL(clickedInto(int, int)), - this,SLOT(removeLink(int, int))); - cButton->setToolTip(tr("remove link")); - linkTableWidget->setCellWidget(row,0,cButton); - - linkTableWidget->resizeColumnToContents(0); - linkTableWidget->resizeColumnToContents(1); - linkTableWidget->resizeColumnToContents(2); - linkTableWidget->resizeColumnToContents(3); - linkTableWidget->setRowHeight(row,17); - - emit addLink(image1Ids[image1ComboBox->currentIndex()].c_str(), - image2Ids[image2ComboBox->currentIndex()].c_str()); - UpdateComboBox2(image1ComboBox->currentIndex()); - } + && !image2ComboBox->currentText().isEmpty()) { + int row = linkTableWidget->rowCount(); + linkTableWidget->insertRow(row); + + linkTableWidget->setItem(row,1,new QTableWidgetItem(image1ComboBox->currentText())); + linkTableWidget->setItem(row,2,new QTableWidgetItem("&")); + linkTableWidget->setItem(row,3,new QTableWidgetItem(image2ComboBox->currentText())); + linkTableWidget->setItem(row,4,new QTableWidgetItem(image1Ids[image1ComboBox->currentIndex()].c_str())); + linkTableWidget->setItem(row,5,new QTableWidgetItem(image2Ids[image2ComboBox->currentIndex()].c_str())); + QTreePushButton* cButton = new QTreePushButton; + cButton->setIndex(linkTableWidget->rowCount()); + cButton->setColumn(0); + cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); + connect(cButton,SIGNAL(clickedInto(int, int)), + this,SLOT(removeLink(int, int))); + cButton->setToolTip(tr("remove link")); + linkTableWidget->setCellWidget(row,0,cButton); + + linkTableWidget->resizeColumnToContents(0); + linkTableWidget->resizeColumnToContents(1); + linkTableWidget->resizeColumnToContents(2); + linkTableWidget->resizeColumnToContents(3); + linkTableWidget->setRowHeight(row,17); + + emit addLink(image1Ids[image1ComboBox->currentIndex()].c_str(), + image2Ids[image2ComboBox->currentIndex()].c_str()); + UpdateComboBox2(image1ComboBox->currentIndex()); + } } //------------------------------------------------------------------------------ @@ -196,18 +184,18 @@ void vvLinkPanel::addLink() //------------------------------------------------------------------------------ void vvLinkPanel::removeLink(int row, int column) { - // DD(row); +// DD(row); // DD(column); while (linkTableWidget->item(row-1,4) == NULL) { --row; - // DD(linkTableWidget->rowCount()); + // DD(linkTableWidget->rowCount()); // DD(row); // return; } if (linkTableWidget->item(row-1,5) == NULL) { return; // should not happend ... } - + emit removeLink(linkTableWidget->item(row-1,4)->text(),linkTableWidget->item(row-1,5)->text()); // DD("after emit"); linkTableWidget->removeRow(row-1); diff --git a/vv/vvMainWindow.cxx b/vv/vvMainWindow.cxx index 4f899d0..05923ff 100644 --- a/vv/vvMainWindow.cxx +++ b/vv/vvMainWindow.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -96,7 +96,8 @@ 5,Qt::UserRole mSlicerManager id*/ //------------------------------------------------------------------------------ -vvMainWindow::vvMainWindow():vvMainWindowBase() { +vvMainWindow::vvMainWindow():vvMainWindowBase() +{ setupUi(this); // this sets up the GUI mInputPathName = ""; @@ -110,24 +111,24 @@ vvMainWindow::vvMainWindow():vvMainWindowBase() { this->setContextMenuPolicy(Qt::CustomContextMenu); contextActions.resize(0); QAction* actionOpen_new_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/fileopen.png")), - tr("O&pen new Image")); + tr("O&pen new Image")); actionOpen_new_image->setShortcut(QKeySequence(tr("Ctrl+O"))); connect(actionOpen_new_image,SIGNAL(triggered()),this,SLOT(OpenImages())); contextActions.push_back(actionOpen_new_image); contextMenu.addSeparator(); QAction* actionClose_Image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/exit.png")), - tr("Close Current Image")); + tr("Close Current Image")); connect(actionClose_Image,SIGNAL(triggered()),this,SLOT(CloseImage())); contextActions.push_back(actionClose_Image); QAction* actionReload_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/rotateright.png")), - tr("Reload Current Image")); + tr("Reload Current Image")); connect(actionReload_image,SIGNAL(triggered()),this,SLOT(ReloadImage())); contextActions.push_back(actionReload_image); QAction* actionSave_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/filesave.png")), - tr("Save Current Image")); + tr("Save Current Image")); connect(actionSave_image,SIGNAL(triggered()),this,SLOT(SaveAs())); contextActions.push_back(actionSave_image); @@ -139,7 +140,7 @@ vvMainWindow::vvMainWindow():vvMainWindowBase() { // contextActions.push_back(actionCrop_image); QAction* actionSplit_image = contextMenu.addAction(QIcon(QString::fromUtf8(":/common/icons/cut.png")), - tr("Split Current Image")); + tr("Split Current Image")); connect(actionSplit_image,SIGNAL(triggered()),this,SLOT(SplitImage())); contextActions.push_back(actionSplit_image); @@ -149,7 +150,7 @@ vvMainWindow::vvMainWindow():vvMainWindowBase() { contextActions.push_back(actionAdd_VF_to_current_Image); QAction* actionAdd_Overlay_to_current_Image = menuOverlay->addAction(QIcon(QString::fromUtf8(":/common/icons/GPSup.png")), - tr("Add overlay image to current image")); + tr("Add overlay image to current image")); contextMenu.addAction(actionAdd_Overlay_to_current_Image); contextActions.push_back(actionAdd_Overlay_to_current_Image); @@ -309,25 +310,23 @@ vvMainWindow::vvMainWindow():vvMainWindowBase() { //Recently opened files std::list recent_files = GetRecentlyOpenedImages(); - if ( !recent_files.empty() ) - { - QMenu * rmenu = new QMenu("Recently opened files..."); - rmenu->setIcon(QIcon(QString::fromUtf8(":/common/icons/open.png"))); - menuFile->insertMenu(actionOpen_Image_With_Time,rmenu); - for (std::list::iterator i = recent_files.begin();i!=recent_files.end();i++) - { - QAction* current=new QAction(QIcon(QString::fromUtf8(":/common/icons/open.png")), - (*i).c_str(),this); - rmenu->addAction(current); - connect(current,SIGNAL(triggered()),this,SLOT(OpenRecentImage())); - } + if ( !recent_files.empty() ) { + QMenu * rmenu = new QMenu("Recently opened files..."); + rmenu->setIcon(QIcon(QString::fromUtf8(":/common/icons/open.png"))); + menuFile->insertMenu(actionOpen_Image_With_Time,rmenu); + for (std::list::iterator i = recent_files.begin(); i!=recent_files.end(); i++) { + QAction* current=new QAction(QIcon(QString::fromUtf8(":/common/icons/open.png")), + (*i).c_str(),this); + rmenu->addAction(current); + connect(current,SIGNAL(triggered()),this,SLOT(OpenRecentImage())); } + } // Adding all new tools (insertion in the menu) vvToolManager::GetInstance()->InsertToolsInMenu(this); if (!CLITK_EXPERIMENTAL) - menuExperimental->menuAction()->setVisible(false); + menuExperimental->menuAction()->setVisible(false); } //------------------------------------------------------------------------------ @@ -340,7 +339,7 @@ void vvMainWindow::ComputeMIP() QFileInfo info(selected_slicer->GetFileName().c_str()); mip.Compute(selected_slicer); if (!mip.error) - AddImage(mip.GetOutput(),info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_mip.mhd"); + AddImage(mip.GetOutput(),info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_mip.mhd"); } //------------------------------------------------------------------------------ @@ -352,22 +351,20 @@ void vvMainWindow::ComputeMidPosition() int index=GetSlicerIndexFromItem(DataTree->selectedItems()[0]); int ref = QInputDialog::getInteger(this,"Chose reference phase","Reference phase",0,0,\ mSlicerManagers[index]->GetImage()->GetVTKImages().size()-1,1,&ok); - if (ok) - { - vvMidPosition midp; - midp.slicer_manager = mSlicerManagers[index]; - midp.reference_image_index = ref; - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - midp.Update(); - if (midp.error) - QMessageBox::warning(this, "Error computing midposition image",midp.error_message.c_str()); - else - { - QFileInfo info(midp.slicer_manager->GetFileName().c_str()); - AddImage(midp.output,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_midposition.mhd"); - } - QApplication::restoreOverrideCursor(); + if (ok) { + vvMidPosition midp; + midp.slicer_manager = mSlicerManagers[index]; + midp.reference_image_index = ref; + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + midp.Update(); + if (midp.error) + QMessageBox::warning(this, "Error computing midposition image",midp.error_message.c_str()); + else { + QFileInfo info(midp.slicer_manager->GetFileName().c_str()); + AddImage(midp.output,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_midposition.mhd"); } + QApplication::restoreOverrideCursor(); + } } //------------------------------------------------------------------------------ @@ -422,23 +419,22 @@ void vvMainWindow::AddContour(int image_index, vvMesh::Pointer contour, bool pro //------------------------------------------------------------------------------ void vvMainWindow::OpenVTKContour() { - if (mSlicerManagers.size() > 0) - { - QString Extensions = "Images ( *.vtk *.obj)"; - Extensions += ";;All Files (*)"; - QString file = QFileDialog::getOpenFileName(this,tr("Open vtkPolyData"),mInputPathName,Extensions); - if (file.isNull()) - return; - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - vvMeshReader reader; - reader.SetImage(mSlicerManagers[index]->GetImage()); - reader.SetModeToVTK(); - reader.SetFilename(file.toStdString()); - reader.Update(); - AddContour(index,reader.GetOutput()[0],false); - QApplication::restoreOverrideCursor(); - } + if (mSlicerManagers.size() > 0) { + QString Extensions = "Images ( *.vtk *.obj)"; + Extensions += ";;All Files (*)"; + QString file = QFileDialog::getOpenFileName(this,tr("Open vtkPolyData"),mInputPathName,Extensions); + if (file.isNull()) + return; + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); + vvMeshReader reader; + reader.SetImage(mSlicerManagers[index]->GetImage()); + reader.SetModeToVTK(); + reader.SetFilename(file.toStdString()); + reader.Update(); + AddContour(index,reader.GetOutput()[0],false); + QApplication::restoreOverrideCursor(); + } } //------------------------------------------------------------------------------ @@ -446,35 +442,33 @@ void vvMainWindow::OpenVTKContour() //------------------------------------------------------------------------------ void vvMainWindow::OpenDCStructContour() { - if (mSlicerManagers.size() > 0) - { - QString Extensions = "Dicom Files ( *.dcm; RS*)"; - Extensions += ";;All Files (*)"; - QString file = QFileDialog::getOpenFileName(this,tr("Merge Images"),mInputPathName,Extensions); - if (file.isNull()) - return; - int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - vvMeshReader reader; - reader.SetFilename(file.toStdString()); - vvStructSelector selector; - selector.SetStructures(reader.GetROINames()); - if (!mSlicerManagers[index]->GetVF().IsNull()) - selector.EnablePropagationCheckBox(); - if (selector.exec()) - { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - reader.SetSelectedItems(selector.getSelectedItems()); - reader.SetImage(mSlicerManagers[index]->GetImage()); - if (selector.PropagationEnabled()) - reader.SetPropagationVF(mSlicerManagers[index]->GetVF()); - reader.Update(); - std::vector contours=reader.GetOutput(); - for (std::vector::iterator i=contours.begin(); - i!=contours.end();i++) - AddContour(index,*i,selector.PropagationEnabled()); - QApplication::restoreOverrideCursor(); - } + if (mSlicerManagers.size() > 0) { + QString Extensions = "Dicom Files ( *.dcm; RS*)"; + Extensions += ";;All Files (*)"; + QString file = QFileDialog::getOpenFileName(this,tr("Merge Images"),mInputPathName,Extensions); + if (file.isNull()) + return; + int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); + vvMeshReader reader; + reader.SetFilename(file.toStdString()); + vvStructSelector selector; + selector.SetStructures(reader.GetROINames()); + if (!mSlicerManagers[index]->GetVF().IsNull()) + selector.EnablePropagationCheckBox(); + if (selector.exec()) { + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + reader.SetSelectedItems(selector.getSelectedItems()); + reader.SetImage(mSlicerManagers[index]->GetImage()); + if (selector.PropagationEnabled()) + reader.SetPropagationVF(mSlicerManagers[index]->GetVF()); + reader.Update(); + std::vector contours=reader.GetOutput(); + for (std::vector::iterator i=contours.begin(); + i!=contours.end(); i++) + AddContour(index,*i,selector.PropagationEnabled()); + QApplication::restoreOverrideCursor(); } + } } //------------------------------------------------------------------------------ @@ -482,20 +476,16 @@ void vvMainWindow::OpenDCStructContour() //------------------------------------------------------------------------------ void vvMainWindow::ComputeDeformableRegistration() { - if (mSlicerManagers.size() > 0) - { - int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - vvDeformationDialog dialog(index,mSlicerManagers); - if (dialog.exec()) - { - std::string base_name=itksys::SystemTools::GetFilenameWithoutExtension(mSlicerManagers[dialog.GetInputFileIndex()]->GetFileName()); - AddField(dialog.GetOutput(),dialog.getFieldFile(),dialog.GetInputFileIndex()); - WarpImage(dialog.GetSelectedSlicer(),dialog.GetReferenceFrameIndex()); - } - else - std::cout << "Error or user cancellation while computing deformation field..." << std::endl; - } - else QMessageBox::information(this, "Need to open image","You must open an image first."); + if (mSlicerManagers.size() > 0) { + int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); + vvDeformationDialog dialog(index,mSlicerManagers); + if (dialog.exec()) { + std::string base_name=itksys::SystemTools::GetFilenameWithoutExtension(mSlicerManagers[dialog.GetInputFileIndex()]->GetFileName()); + AddField(dialog.GetOutput(),dialog.getFieldFile(),dialog.GetInputFileIndex()); + WarpImage(dialog.GetSelectedSlicer(),dialog.GetReferenceFrameIndex()); + } else + std::cout << "Error or user cancellation while computing deformation field..." << std::endl; + } else QMessageBox::information(this, "Need to open image","You must open an image first."); } //------------------------------------------------------------------------------ @@ -504,17 +494,14 @@ void vvMainWindow::ComputeDeformableRegistration() void vvMainWindow::WarpImage() { int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - if (!mSlicerManagers[index]->GetVF().IsNull()) - { - bool ok; - int ref = QInputDialog::getInteger(this,"Chose reference phase","Reference phase",0,0,\ - mSlicerManagers[index]->GetImage()->GetVTKImages().size()-1,1,&ok); - if (ok) - { - WarpImage(mSlicerManagers[index],ref); - } - } - else + if (!mSlicerManagers[index]->GetVF().IsNull()) { + bool ok; + int ref = QInputDialog::getInteger(this,"Chose reference phase","Reference phase",0,0,\ + mSlicerManagers[index]->GetImage()->GetVTKImages().size()-1,1,&ok); + if (ok) { + WarpImage(mSlicerManagers[index],ref); + } + } else QMessageBox::warning(this,tr("No vector field"),tr("Sorry, can't warp without a vector field")); } //------------------------------------------------------------------------------ @@ -523,44 +510,40 @@ void vvMainWindow::WarpImage() //------------------------------------------------------------------------------ void vvMainWindow::WarpImage(vvSlicerManager* selected_slicer,int reference_phase) { - if (!selected_slicer->GetVF().IsNull()) - { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - QFileInfo info(selected_slicer->GetFileName().c_str()); - vvImageWarp warp(selected_slicer->GetImage(),selected_slicer->GetVF(), - reference_phase,this); - if (warp.ComputeWarpedImage()) - { - AddImage(warp.GetWarpedImage(),info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_warped.mhd"); - AddImage(warp.GetDiffImage() ,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_diff.mhd"); - AddImage(warp.GetJacobianImage() ,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_jacobian.mhd"); - QApplication::restoreOverrideCursor(); - } - else - { - QApplication::restoreOverrideCursor(); - QMessageBox::warning(this,tr("Different spacings"),tr("The vector field and image spacings must be the same in order to warp.")); - } + if (!selected_slicer->GetVF().IsNull()) { + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + QFileInfo info(selected_slicer->GetFileName().c_str()); + vvImageWarp warp(selected_slicer->GetImage(),selected_slicer->GetVF(), + reference_phase,this); + if (warp.ComputeWarpedImage()) { + AddImage(warp.GetWarpedImage(),info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_warped.mhd"); + AddImage(warp.GetDiffImage() ,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_diff.mhd"); + AddImage(warp.GetJacobianImage() ,info.path().toStdString()+"/"+info.completeBaseName().toStdString()+"_jacobian.mhd"); + QApplication::restoreOverrideCursor(); + } else { + QApplication::restoreOverrideCursor(); + QMessageBox::warning(this,tr("Different spacings"),tr("The vector field and image spacings must be the same in order to warp.")); } - else + } else QMessageBox::warning(this,tr("No vector field"),tr("Sorry, can't warp without a vector field.")); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vvMainWindow::~vvMainWindow() { - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (mSlicerManagers[i] != NULL) - delete mSlicerManagers[i]; - } +vvMainWindow::~vvMainWindow() +{ + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (mSlicerManagers[i] != NULL) + delete mSlicerManagers[i]; + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::MergeImages() { +void vvMainWindow::MergeImages() +{ QString Extensions = EXTENSIONS; Extensions += ";;All Files (*)"; QStringList files = QFileDialog::getOpenFileNames(this,tr("Merge Images"),mInputPathName,Extensions); @@ -574,50 +557,44 @@ void vvMainWindow::MergeImages() { std::vector currentSize; std::vector currentOrigin; - for (int i = 0; i < files.size(); i++) - { - itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( - files[i].toStdString().c_str(), itk::ImageIOFactory::ReadMode); - reader->SetFileName(files[i].toStdString().c_str()); - reader->ReadImageInformation(); - if (reader) { - //NOViewWidget->hide(); - //NEViewWidget->hide(); - //SOViewWidget->hide(); - //SEViewWidget->hide(); - if (i == 0) - currentDim = reader->GetNumberOfDimensions(); - bool IsOk = true; - for (unsigned int j = 0;j < currentDim; j++) - { - if (i == 0) - { - if (j == 0) - { - currentSpacing.resize(currentDim); - currentSize.resize(currentDim); - currentOrigin.resize(currentDim); - } - currentOrigin[j] = reader->GetOrigin(j); - currentSpacing[j] = reader->GetSpacing(j); - currentSize[j] = reader->GetDimensions(j); - } - else if (currentDim != reader->GetNumberOfDimensions() - || currentSpacing[j] != reader->GetSpacing(j) - || currentSize[j] != (int)reader->GetDimensions(j) - || currentOrigin[j] != reader->GetOrigin(j)) - { - QString error = "Cannot read file (too different from others "; - error += files[i].toStdString().c_str(); - QMessageBox::information(this,tr("Reading problem"),error); - IsOk = false; - break; - } + for (int i = 0; i < files.size(); i++) { + itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( + files[i].toStdString().c_str(), itk::ImageIOFactory::ReadMode); + reader->SetFileName(files[i].toStdString().c_str()); + reader->ReadImageInformation(); + if (reader) { + //NOViewWidget->hide(); + //NEViewWidget->hide(); + //SOViewWidget->hide(); + //SEViewWidget->hide(); + if (i == 0) + currentDim = reader->GetNumberOfDimensions(); + bool IsOk = true; + for (unsigned int j = 0; j < currentDim; j++) { + if (i == 0) { + if (j == 0) { + currentSpacing.resize(currentDim); + currentSize.resize(currentDim); + currentOrigin.resize(currentDim); } - if (IsOk) - vector.push_back(files[i].toStdString()); + currentOrigin[j] = reader->GetOrigin(j); + currentSpacing[j] = reader->GetSpacing(j); + currentSize[j] = reader->GetDimensions(j); + } else if (currentDim != reader->GetNumberOfDimensions() + || currentSpacing[j] != reader->GetSpacing(j) + || currentSize[j] != (int)reader->GetDimensions(j) + || currentOrigin[j] != reader->GetOrigin(j)) { + QString error = "Cannot read file (too different from others "; + error += files[i].toStdString().c_str(); + QMessageBox::information(this,tr("Reading problem"),error); + IsOk = false; + break; + } } + if (IsOk) + vector.push_back(files[i].toStdString()); } + } if (vector.size() > 0) LoadImages(vector, MERGED); } @@ -625,7 +602,8 @@ void vvMainWindow::MergeImages() { //------------------------------------------------------------------------------ -void vvMainWindow::MergeImagesWithTime() { +void vvMainWindow::MergeImagesWithTime() +{ QString Extensions = EXTENSIONS; Extensions += ";;All Files (*)"; QStringList files = QFileDialog::getOpenFileNames(this,tr("Merge Images With Time"),mInputPathName,Extensions); @@ -639,55 +617,46 @@ void vvMainWindow::MergeImagesWithTime() { std::vector currentSize; std::vector currentOrigin; - for (int i = 0; i < files.size(); i++) - { - itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( - files[i].toStdString().c_str(), itk::ImageIOFactory::ReadMode); - if (reader) - { - reader->SetFileName(files[i].toStdString().c_str()); - reader->ReadImageInformation(); - if (i == 0) - currentDim = reader->GetNumberOfDimensions(); - bool IsOk = true; - for (unsigned int j = 0;j < currentDim; j++) - { - if (i == 0) - { - if (j == 0) - { - currentSpacing.resize(currentDim); - currentSize.resize(currentDim); - currentOrigin.resize(currentDim); - } - currentOrigin[j] = reader->GetOrigin(j); - currentSpacing[j] = reader->GetSpacing(j); - currentSize[j] = reader->GetDimensions(j); - } - else if (currentDim != reader->GetNumberOfDimensions() - || currentSpacing[j] != reader->GetSpacing(j) - || currentSize[j] != (int)reader->GetDimensions(j) - || currentOrigin[j] != reader->GetOrigin(j)) - { - QString error = "Cannot read file (too different from others "; - error += files[i].toStdString().c_str(); - QMessageBox::information(this,tr("Reading problem"),error); - IsOk = false; - break; - } - } - if (IsOk) - vector.push_back(files[i].toStdString()); - } - else - { - QString error = "Cannot read file info for "; + for (int i = 0; i < files.size(); i++) { + itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( + files[i].toStdString().c_str(), itk::ImageIOFactory::ReadMode); + if (reader) { + reader->SetFileName(files[i].toStdString().c_str()); + reader->ReadImageInformation(); + if (i == 0) + currentDim = reader->GetNumberOfDimensions(); + bool IsOk = true; + for (unsigned int j = 0; j < currentDim; j++) { + if (i == 0) { + if (j == 0) { + currentSpacing.resize(currentDim); + currentSize.resize(currentDim); + currentOrigin.resize(currentDim); + } + currentOrigin[j] = reader->GetOrigin(j); + currentSpacing[j] = reader->GetSpacing(j); + currentSize[j] = reader->GetDimensions(j); + } else if (currentDim != reader->GetNumberOfDimensions() + || currentSpacing[j] != reader->GetSpacing(j) + || currentSize[j] != (int)reader->GetDimensions(j) + || currentOrigin[j] != reader->GetOrigin(j)) { + QString error = "Cannot read file (too different from others "; error += files[i].toStdString().c_str(); - error += "\n"; - error += "Maybe you're trying to open an image in an unsupported format?\n"; QMessageBox::information(this,tr("Reading problem"),error); + IsOk = false; + break; } + } + if (IsOk) + vector.push_back(files[i].toStdString()); + } else { + QString error = "Cannot read file info for "; + error += files[i].toStdString().c_str(); + error += "\n"; + error += "Maybe you're trying to open an image in an unsupported format?\n"; + QMessageBox::information(this,tr("Reading problem"),error); } + } sort(vector.begin(),vector.end()); if (vector.size() > 1) LoadImages(vector, MERGEDWITHTIME); @@ -698,26 +667,26 @@ void vvMainWindow::MergeImagesWithTime() { //------------------------------------------------------------------------------ -void vvMainWindow::OpenDicom() { +void vvMainWindow::OpenDicom() +{ std::vector files; #ifdef CLITK_VV_USE_BDCM bool r = bdcm::OpenDicomFilesSelectorDialog(files, - "DicomFilesSelectorDialog test", - 0,0,800,800,1); + "DicomFilesSelectorDialog test", + 0,0,800,800,1); if (r) { std::cout << "$$$$ main : user clicked 'OK' $$$$"<::iterator i; - for (i=files.begin();i!=files.end();++i) { + for (i=files.begin(); i!=files.end(); ++i) { std::cout << *i << std::endl; } std::cout << "$$$$ "< vector; - for (int i = 0; i < files.size(); i++) - { - vector.push_back(files[i].toStdString()); - } + for (int i = 0; i < files.size(); i++) { + vector.push_back(files[i].toStdString()); + } LoadImages(vector, IMAGEWITHTIME); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::LoadImages(std::vector files, LoadedImageType filetype) { +void vvMainWindow::LoadImages(std::vector files, LoadedImageType filetype) +{ //Separate the way to open images and dicoms int fileSize; if (filetype == IMAGE || filetype == IMAGEWITHTIME) @@ -787,11 +758,10 @@ void vvMainWindow::LoadImages(std::vector files, LoadedImageType fi //Only add to the list of recently opened files when a single file is opened, //to avoid polluting the list of recently opened files - if (files.size() == 1) - { - QFileInfo finfo=tr(files[0].c_str()); - AddToRecentlyOpenedImages(finfo.absoluteFilePath().toStdString()); - } + if (files.size() == 1) { + QFileInfo finfo=tr(files[0].c_str()); + AddToRecentlyOpenedImages(finfo.absoluteFilePath().toStdString()); + } //init the progress events QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); vvProgressDialog progress("Opening " + files[0],fileSize>1); @@ -818,7 +788,7 @@ void vvMainWindow::LoadImages(std::vector files, LoadedImageType fi vvSlicerManager * v = mSlicerManagers[l]; // DD(v->GetBaseFileName()); // DD(v->GetFileName()); - if (v->GetBaseFileName() == + if (v->GetBaseFileName() == vtksys::SystemTools::GetFilenameName(vtksys::SystemTools::GetFilenameWithoutLastExtension(files[i]))) { number = std::max(number, v->GetBaseFileNameNumber()+1); } @@ -827,97 +797,92 @@ void vvMainWindow::LoadImages(std::vector files, LoadedImageType fi if (filetype == IMAGE || filetype == IMAGEWITHTIME) SetImageSucceed = imageManager->SetImage(files[i],filetype, number); - else - { - SetImageSucceed = imageManager->SetImages(files,filetype, number); - } - if (SetImageSucceed == false) - { - QApplication::restoreOverrideCursor(); - QString error = "Cannot open file \n"; - error += imageManager->GetLastError().c_str(); - QMessageBox::information(this,tr("Reading problem"),error); - delete imageManager; - } - else - { - mSlicerManagers.push_back(imageManager); - - //create an item in the tree with good settings - QTreeWidgetItem *item = new QTreeWidgetItem(); - item->setData(0,Qt::UserRole,files[i].c_str()); - QFileInfo fileinfo(imageManager->GetFileName().c_str()); //Do not show the path - item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName()); - qApp->processEvents(); - - //Create the buttons for reload and close - qApp->processEvents(); - QTreePushButton* cButton = new QTreePushButton; - cButton->setItem(item); - cButton->setColumn(COLUMN_CLOSE_IMAGE); - cButton->setToolTip(tr("close image")); - cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); - connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(CloseImage(QTreeWidgetItem*, int))); + else { + SetImageSucceed = imageManager->SetImages(files,filetype, number); + } + if (SetImageSucceed == false) { + QApplication::restoreOverrideCursor(); + QString error = "Cannot open file \n"; + error += imageManager->GetLastError().c_str(); + QMessageBox::information(this,tr("Reading problem"),error); + delete imageManager; + } else { + mSlicerManagers.push_back(imageManager); - QTreePushButton* rButton = new QTreePushButton; - rButton->setItem(item); - rButton->setColumn(COLUMN_RELOAD_IMAGE); - rButton->setToolTip(tr("reload image")); - rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); - connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(ReloadImage(QTreeWidgetItem*, int))); + //create an item in the tree with good settings + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setData(0,Qt::UserRole,files[i].c_str()); + QFileInfo fileinfo(imageManager->GetFileName().c_str()); //Do not show the path + item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileinfo.fileName()); + qApp->processEvents(); - DataTree->addTopLevelItem(item); - DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); - DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); + //Create the buttons for reload and close + qApp->processEvents(); + QTreePushButton* cButton = new QTreePushButton; + cButton->setItem(item); + cButton->setColumn(COLUMN_CLOSE_IMAGE); + cButton->setToolTip(tr("close image")); + cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); + connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(CloseImage(QTreeWidgetItem*, int))); - //set the id of the image - QString id = files[i].c_str() + QString::number(mSlicerManagers.size()-1); - item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); - mSlicerManagers.back()->SetId(id.toStdString()); + QTreePushButton* rButton = new QTreePushButton; + rButton->setItem(item); + rButton->setColumn(COLUMN_RELOAD_IMAGE); + rButton->setToolTip(tr("reload image")); + rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); + connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(ReloadImage(QTreeWidgetItem*, int))); - linkPanel->addImage(imageManager->GetFileName(), id.toStdString()); + DataTree->addTopLevelItem(item); + DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); + DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); - connect(mSlicerManagers.back(), SIGNAL(currentImageChanged(std::string)), - this,SLOT(CurrentImageChanged(std::string))); - connect(mSlicerManagers.back(), SIGNAL(UpdatePosition(int, double, double, double, double, double, double, double)), - this,SLOT(MousePositionChanged(int,double, double, double, double, double, double, double))); - connect(mSlicerManagers.back(), SIGNAL(UpdateVector(int, double, double, double, double)), - this, SLOT(VectorChanged(int,double,double,double, double))); - connect(mSlicerManagers.back(), SIGNAL(UpdateOverlay(int, double, double)), - this, SLOT(OverlayChanged(int,double,double))); - connect(mSlicerManagers.back(), SIGNAL(UpdateFusion(int, double)), - this, SLOT(FusionChanged(int,double))); - connect(mSlicerManagers.back(), SIGNAL(UpdateWindows(int, int, int)), - this,SLOT(WindowsChanged(int, int, int))); - connect(mSlicerManagers.back(), SIGNAL(WindowLevelChanged(double, double,int, int)), - this,SLOT(WindowLevelChanged(double, double, int, int))); - connect(mSlicerManagers.back(), SIGNAL(UpdateSlice(int,int)), - this,SLOT(UpdateSlice(int,int))); - connect(mSlicerManagers.back(), SIGNAL(UpdateTSlice(int, int)), - this,SLOT(UpdateTSlice(int, int))); - connect(mSlicerManagers.back(), SIGNAL(UpdateSliceRange(int,int,int,int,int)), - this,SLOT(UpdateSliceRange(int,int,int,int,int))); - connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)), - this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int))); - connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)), - this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int))); - connect(mSlicerManagers.back(),SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint())); - InitSlicers(); - numberofsuccesulreads++; - } - } - if (numberofsuccesulreads) - { - NOViewWidget->show(); - NEViewWidget->show(); - SOViewWidget->show(); - SEViewWidget->show(); - UpdateTree(); - InitDisplay(); - ShowLastImage(); + //set the id of the image + QString id = files[i].c_str() + QString::number(mSlicerManagers.size()-1); + item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); + mSlicerManagers.back()->SetId(id.toStdString()); + + linkPanel->addImage(imageManager->GetFileName(), id.toStdString()); + + connect(mSlicerManagers.back(), SIGNAL(currentImageChanged(std::string)), + this,SLOT(CurrentImageChanged(std::string))); + connect(mSlicerManagers.back(), SIGNAL(UpdatePosition(int, double, double, double, double, double, double, double)), + this,SLOT(MousePositionChanged(int,double, double, double, double, double, double, double))); + connect(mSlicerManagers.back(), SIGNAL(UpdateVector(int, double, double, double, double)), + this, SLOT(VectorChanged(int,double,double,double, double))); + connect(mSlicerManagers.back(), SIGNAL(UpdateOverlay(int, double, double)), + this, SLOT(OverlayChanged(int,double,double))); + connect(mSlicerManagers.back(), SIGNAL(UpdateFusion(int, double)), + this, SLOT(FusionChanged(int,double))); + connect(mSlicerManagers.back(), SIGNAL(UpdateWindows(int, int, int)), + this,SLOT(WindowsChanged(int, int, int))); + connect(mSlicerManagers.back(), SIGNAL(WindowLevelChanged(double, double,int, int)), + this,SLOT(WindowLevelChanged(double, double, int, int))); + connect(mSlicerManagers.back(), SIGNAL(UpdateSlice(int,int)), + this,SLOT(UpdateSlice(int,int))); + connect(mSlicerManagers.back(), SIGNAL(UpdateTSlice(int, int)), + this,SLOT(UpdateTSlice(int, int))); + connect(mSlicerManagers.back(), SIGNAL(UpdateSliceRange(int,int,int,int,int)), + this,SLOT(UpdateSliceRange(int,int,int,int,int))); + connect(mSlicerManagers.back(), SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)), + this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int))); + connect(mSlicerManagers.back(), SIGNAL(ChangeImageWithIndexOffset(vvSlicerManager*,int,int)), + this,SLOT(ChangeImageWithIndexOffset(vvSlicerManager*,int,int))); + connect(mSlicerManagers.back(),SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint())); + InitSlicers(); + numberofsuccesulreads++; } + } + if (numberofsuccesulreads) { + NOViewWidget->show(); + NEViewWidget->show(); + SOViewWidget->show(); + SEViewWidget->show(); + UpdateTree(); + InitDisplay(); + ShowLastImage(); + } QApplication::restoreOverrideCursor(); // Try to guess default WindowLevel @@ -927,15 +892,15 @@ void vvMainWindow::LoadImages(std::vector files, LoadedImageType fi // DD(range[1]); if ((range[0] == 0) && (range[1] == 1)) { presetComboBox->setCurrentIndex(5);// binary - } - else { + } else { // TODO } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::UpdateTree() { +void vvMainWindow::UpdateTree() +{ DataTree->resizeColumnToContents(COLUMN_TREE); DataTree->resizeColumnToContents(COLUMN_UL_VIEW); DataTree->resizeColumnToContents(COLUMN_UR_VIEW); @@ -948,28 +913,26 @@ void vvMainWindow::UpdateTree() { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::CurrentImageChanged(std::string id) { +void vvMainWindow::CurrentImageChanged(std::string id) +{ int selected = 0; - for (int i = 0; i < DataTree->topLevelItemCount(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString().toStdString() == id) - { - selected = i; - } - else - { - DataTree->topLevelItem(i)->setSelected(0); - } - for (int child = 0; child < DataTree->topLevelItem(i)->childCount();child++) - DataTree->topLevelItem(i)->child(child)->setSelected(0); - + for (int i = 0; i < DataTree->topLevelItemCount(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString().toStdString() == id) { + selected = i; + } else { + DataTree->topLevelItem(i)->setSelected(0); } + for (int child = 0; child < DataTree->topLevelItem(i)->childCount(); child++) + DataTree->topLevelItem(i)->child(child)->setSelected(0); + + } DataTree->topLevelItem(selected)->setSelected(1); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::ImageInfoChanged() { +void vvMainWindow::ImageInfoChanged() +{ contextActions[7]->setEnabled(1); contextActions[6]->setEnabled(1); actionSave_As->setEnabled(1); @@ -987,15 +950,13 @@ void vvMainWindow::ImageInfoChanged() { int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); colorMapComboBox->setEnabled(1); - for (int i = 0; i < DataTree->topLevelItem(index)->childCount();i++) - { - if (DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "overlay" || - DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "fusion") - { - colorMapComboBox->setEnabled(0); - break; - } + for (int i = 0; i < DataTree->topLevelItem(index)->childCount(); i++) { + if (DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "overlay" || + DataTree->topLevelItem(index)->child(i)->data(1,Qt::UserRole).toString() == "fusion") { + colorMapComboBox->setEnabled(0); + break; } + } std::vector origin; std::vector inputSpacing; @@ -1006,98 +967,84 @@ void vvMainWindow::ImageInfoChanged() { QString inputSizeInBytes; QString image = DataTree->selectedItems()[0]->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - if (mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size() > 1 || playMode == 1) - { - playButton->setEnabled(1); - frameRateLabel->setEnabled(1); - frameRateSpinBox->setEnabled(1); - } - else - { - playButton->setEnabled(0); - frameRateLabel->setEnabled(0); - frameRateSpinBox->setEnabled(0); - } + if (mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetVTKImages().size() > 1 || playMode == 1) { + playButton->setEnabled(1); + frameRateLabel->setEnabled(1); + frameRateSpinBox->setEnabled(1); + } else { + playButton->setEnabled(0); + frameRateLabel->setEnabled(0); + frameRateSpinBox->setEnabled(0); + } //read image header int NPixel = 1; - if (DataTree->topLevelItem(index) == DataTree->selectedItems()[0]) - { - vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetImage(); - dimension = imageSelected->GetNumberOfDimensions(); - origin.resize(dimension); - inputSpacing.resize(dimension); - inputSize.resize(dimension); - sizeMM.resize(dimension); - pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsString().c_str(); - for (int i = 0;i < dimension;i++) - { - origin[i] = imageSelected->GetOrigin()[i]; - inputSpacing[i] = imageSelected->GetSpacing()[i]; - inputSize[i] = imageSelected->GetSize()[i]; - sizeMM[i] = inputSize[i]*inputSpacing[i]; - NPixel *= inputSize[i]; - } - inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + if (DataTree->topLevelItem(index) == DataTree->selectedItems()[0]) { + vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetImage(); + dimension = imageSelected->GetNumberOfDimensions(); + origin.resize(dimension); + inputSpacing.resize(dimension); + inputSize.resize(dimension); + sizeMM.resize(dimension); + pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsString().c_str(); + for (int i = 0; i < dimension; i++) { + origin[i] = imageSelected->GetOrigin()[i]; + inputSpacing[i] = imageSelected->GetSpacing()[i]; + inputSize[i] = imageSelected->GetSize()[i]; + sizeMM[i] = inputSize[i]*inputSpacing[i]; + NPixel *= inputSize[i]; } - else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") - { - vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetVF(); - dimension = imageSelected->GetNumberOfDimensions(); - origin.resize(dimension); - inputSpacing.resize(dimension); - inputSize.resize(dimension); - sizeMM.resize(dimension); - pixelType = mSlicerManagers[index]->GetVF()->GetScalarTypeAsString().c_str(); - for (int i = 0;i < dimension;i++) - { - origin[i] = imageSelected->GetOrigin()[i]; - inputSpacing[i] = imageSelected->GetSpacing()[i]; - inputSize[i] = imageSelected->GetSize()[i]; - sizeMM[i] = inputSize[i]*inputSpacing[i]; - NPixel *= inputSize[i]; - } - inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") { + vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetVF(); + dimension = imageSelected->GetNumberOfDimensions(); + origin.resize(dimension); + inputSpacing.resize(dimension); + inputSize.resize(dimension); + sizeMM.resize(dimension); + pixelType = mSlicerManagers[index]->GetVF()->GetScalarTypeAsString().c_str(); + for (int i = 0; i < dimension; i++) { + origin[i] = imageSelected->GetOrigin()[i]; + inputSpacing[i] = imageSelected->GetSpacing()[i]; + inputSize[i] = imageSelected->GetSize()[i]; + sizeMM[i] = inputSize[i]*inputSpacing[i]; + NPixel *= inputSize[i]; } - else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "overlay") - { - vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetOverlay(); - dimension = imageSelected->GetNumberOfDimensions(); - origin.resize(dimension); - inputSpacing.resize(dimension); - inputSize.resize(dimension); - sizeMM.resize(dimension); - pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsString().c_str(); - for (int i = 0;i < dimension;i++) - { - origin[i] = imageSelected->GetOrigin()[i]; - inputSpacing[i] = imageSelected->GetSpacing()[i]; - inputSize[i] = imageSelected->GetSize()[i]; - sizeMM[i] = inputSize[i]*inputSpacing[i]; - NPixel *= inputSize[i]; - } - inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "overlay") { + vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetOverlay(); + dimension = imageSelected->GetNumberOfDimensions(); + origin.resize(dimension); + inputSpacing.resize(dimension); + inputSize.resize(dimension); + sizeMM.resize(dimension); + pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsString().c_str(); + for (int i = 0; i < dimension; i++) { + origin[i] = imageSelected->GetOrigin()[i]; + inputSpacing[i] = imageSelected->GetSpacing()[i]; + inputSize[i] = imageSelected->GetSize()[i]; + sizeMM[i] = inputSize[i]*inputSpacing[i]; + NPixel *= inputSize[i]; } - else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "fusion") - { - vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetFusion(); - dimension = imageSelected->GetNumberOfDimensions(); - origin.resize(dimension); - inputSpacing.resize(dimension); - inputSize.resize(dimension); - sizeMM.resize(dimension); - pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsString().c_str(); - for (int i = 0;i < dimension;i++) - { - origin[i] = imageSelected->GetOrigin()[i]; - inputSpacing[i] = imageSelected->GetSpacing()[i]; - inputSize[i] = imageSelected->GetSize()[i]; - sizeMM[i] = inputSize[i]*inputSpacing[i]; - NPixel *= inputSize[i]; - } - inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + } else if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "fusion") { + vvImage::Pointer imageSelected = mSlicerManagers[index]->GetSlicer(0)->GetFusion(); + dimension = imageSelected->GetNumberOfDimensions(); + origin.resize(dimension); + inputSpacing.resize(dimension); + inputSize.resize(dimension); + sizeMM.resize(dimension); + pixelType = mSlicerManagers[index]->GetImage()->GetScalarTypeAsString().c_str(); + for (int i = 0; i < dimension; i++) { + origin[i] = imageSelected->GetOrigin()[i]; + inputSpacing[i] = imageSelected->GetSpacing()[i]; + inputSize[i] = imageSelected->GetSize()[i]; + sizeMM[i] = inputSize[i]*inputSpacing[i]; + NPixel *= inputSize[i]; } + inputSizeInBytes = GetSizeInBytes(imageSelected->GetActualMemorySize()*1000); + } QString dim = QString::number(dimension) + " ("; dim += pixelType + ")"; @@ -1116,14 +1063,12 @@ void vvMainWindow::ImageInfoChanged() { landmarksPanel->SetCurrentImage(mSlicerManagers[index]->GetFileName().c_str()); overlayPanel->getCurrentImageName(mSlicerManagers[index]->GetFileName().c_str()); - for (int i = 0; i < 4;i++) - { - if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) - { - mSlicerManagers[index]->UpdateInfoOnCursorPosition(i); - break; - } + for (int i = 0; i < 4; i++) { + if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) { + mSlicerManagers[index]->UpdateInfoOnCursorPosition(i); + break; } + } windowSpinBox->setValue(mSlicerManagers[index]->GetColorWindow()); levelSpinBox->setValue(mSlicerManagers[index]->GetColorLevel()); // DD(mSlicerManagers[index]->GetColorMap()); @@ -1145,330 +1090,294 @@ void vvMainWindow::ImageInfoChanged() { landmarksPanel->SetCurrentImage(mSlicerManagers[index]->GetFileName().c_str()); overlayPanel->getCurrentImageName(mSlicerManagers[index]->GetFileName().c_str()); - for (int i = 0; i < 4;i++) - { - if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) - { - mSlicerManagers[index]->UpdateInfoOnCursorPosition(i); - break; - } + for (int i = 0; i < 4; i++) { + if (DataTree->selectedItems()[0]->data(i+1,Qt::CheckStateRole).toInt() > 0 || i == 3) { + mSlicerManagers[index]->UpdateInfoOnCursorPosition(i); + break; } + } windowSpinBox->setValue(mSlicerManagers[index]->GetColorWindow()); levelSpinBox->setValue(mSlicerManagers[index]->GetColorLevel()); presetComboBox->setCurrentIndex(mSlicerManagers[index]->GetPreset()); colorMapComboBox->setCurrentIndex(mSlicerManagers[index]->GetColorMap()); - if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) - { - overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str()); - overlayPanel->getVFProperty(mSlicerManagers[index]->GetSlicer(0)->GetVFSubSampling(), - mSlicerManagers[index]->GetSlicer(0)->GetVFScale(), - mSlicerManagers[index]->GetSlicer(0)->GetVFLog()); - } - else - { - overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str()); - overlayPanel->getVFProperty(-1,-1,-1); - } - if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) - { - overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str()); - overlayPanel->getOverlayProperty(mSlicerManagers[index]->GetOverlayColor()); - } - else - { - overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str()); - overlayPanel->getOverlayProperty(-1); - } - if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) - { - overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str()); - overlayPanel->getFusionProperty(mSlicerManagers[index]->GetFusionOpacity(), - mSlicerManagers[index]->GetFusionColorMap(), - mSlicerManagers[index]->GetFusionWindow(), - mSlicerManagers[index]->GetFusionLevel()); - } - else - { - overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str()); - overlayPanel->getFusionProperty(-1, -1,-1,-1); - } + if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) { + overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str()); + overlayPanel->getVFProperty(mSlicerManagers[index]->GetSlicer(0)->GetVFSubSampling(), + mSlicerManagers[index]->GetSlicer(0)->GetVFScale(), + mSlicerManagers[index]->GetSlicer(0)->GetVFLog()); + } else { + overlayPanel->getVFName(mSlicerManagers[index]->GetVFName().c_str()); + overlayPanel->getVFProperty(-1,-1,-1); + } + if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) { + overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str()); + overlayPanel->getOverlayProperty(mSlicerManagers[index]->GetOverlayColor()); + } else { + overlayPanel->getOverlayName(mSlicerManagers[index]->GetOverlayName().c_str()); + overlayPanel->getOverlayProperty(-1); + } + if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) { + overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str()); + overlayPanel->getFusionProperty(mSlicerManagers[index]->GetFusionOpacity(), + mSlicerManagers[index]->GetFusionColorMap(), + mSlicerManagers[index]->GetFusionWindow(), + mSlicerManagers[index]->GetFusionLevel()); + } else { + overlayPanel->getFusionName(mSlicerManagers[index]->GetFusionName().c_str()); + overlayPanel->getFusionProperty(-1, -1,-1,-1); + } } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::ShowDocumentation() { +void vvMainWindow::ShowDocumentation() +{ documentation->show(); } //------------------------------------------------------------------------------ -void vvMainWindow::ShowHelpDialog() { +void vvMainWindow::ShowHelpDialog() +{ help_dialog->show(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::ChangeViewMode() { +void vvMainWindow::ChangeViewMode() +{ QListIterator it0(splitter_3->sizes()); QListIterator it1(splitter_3->sizes()); int max0 = 0; int max1 = 1; - while (it0.hasNext()) - { - max0 += it0.next(); - } - while (it1.hasNext()) - { - max1 += it1.next(); - } + while (it0.hasNext()) { + max0 += it0.next(); + } + while (it1.hasNext()) { + max1 += it1.next(); + } QList size0; QList size1; - if (viewMode == 1) - { - viewMode = 0; - size0.push_back(max0); - size0.push_back(0); - size1.push_back(max1); - size1.push_back(0); - splitter_3->setSizes(size0); - OSplitter->setSizes(size1); - DataTree->setColumnHidden(2,1); - DataTree->setColumnHidden(3,1); - DataTree->setColumnHidden(4,1); - } - else - { - viewMode = 1; - size0.push_back(int(max0/2)); - size0.push_back(int(max0/2)); - size1.push_back(int(max1/2)); - size1.push_back(int(max1/2)); - splitter_3->setSizes(size0); - OSplitter->setSizes(size1); - DataTree->setColumnHidden(2,0); - DataTree->setColumnHidden(3,0); - DataTree->setColumnHidden(4,0); - } + if (viewMode == 1) { + viewMode = 0; + size0.push_back(max0); + size0.push_back(0); + size1.push_back(max1); + size1.push_back(0); + splitter_3->setSizes(size0); + OSplitter->setSizes(size1); + DataTree->setColumnHidden(2,1); + DataTree->setColumnHidden(3,1); + DataTree->setColumnHidden(4,1); + } else { + viewMode = 1; + size0.push_back(int(max0/2)); + size0.push_back(int(max0/2)); + size1.push_back(int(max1/2)); + size1.push_back(int(max1/2)); + splitter_3->setSizes(size0); + OSplitter->setSizes(size1); + DataTree->setColumnHidden(2,0); + DataTree->setColumnHidden(3,0); + DataTree->setColumnHidden(4,0); + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -QString vvMainWindow::GetSizeInBytes(unsigned long size) { +QString vvMainWindow::GetSizeInBytes(unsigned long size) +{ QString result = "";// QString::number(size); //result += " bytes ("; - if (size > 1000000000) - { - size /= 1000000000; - result += QString::number(size); - result += "Gb";//)"; - } - else if (size > 1000000) - { - size /= 1000000; - result += QString::number(size); - result += "Mb";//)"; - } - else if (size > 1000) - { - size /= 1000; - result += QString::number(size); - result += "kb";//)"; - } + if (size > 1000000000) { + size /= 1000000000; + result += QString::number(size); + result += "Gb";//)"; + } else if (size > 1000000) { + size /= 1000000; + result += QString::number(size); + result += "Mb";//)"; + } else if (size > 1000) { + size /= 1000; + result += QString::number(size); + result += "kb";//)"; + } return result; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -QString vvMainWindow::GetVectorDoubleAsString(std::vector vectorDouble) { +QString vvMainWindow::GetVectorDoubleAsString(std::vector vectorDouble) +{ QString result; - for (unsigned int i= 0; i < vectorDouble.size(); i++) - { - if (i != 0) - result += " "; - result += QString::number(vectorDouble[i]); - } + for (unsigned int i= 0; i < vectorDouble.size(); i++) { + if (i != 0) + result += " "; + result += QString::number(vectorDouble[i]); + } return result; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -QString vvMainWindow::GetVectorIntAsString(std::vector vectorInt) { +QString vvMainWindow::GetVectorIntAsString(std::vector vectorInt) +{ QString result; - for (unsigned int i= 0; i < vectorInt.size(); i++) - { - if (i != 0) - result += " "; - result += QString::number(vectorInt[i]); - } + for (unsigned int i= 0; i < vectorInt.size(); i++) { + if (i != 0) + result += " "; + result += QString::number(vectorInt[i]); + } return result; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -int vvMainWindow::GetSlicerIndexFromItem(QTreeWidgetItem* item) { +int vvMainWindow::GetSlicerIndexFromItem(QTreeWidgetItem* item) +{ QString id = item->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString(); - for (int i = 0; i < DataTree->topLevelItemCount(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id) - return i; - } + for (int i = 0; i < DataTree->topLevelItemCount(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id) + return i; + } return -1; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -QTreeWidgetItem* vvMainWindow::GetItemFromSlicerManager(vvSlicerManager* sm) { - QString id = sm->GetId().c_str(); - for (int i = 0; i < DataTree->topLevelItemCount(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id) - return DataTree->topLevelItem(i); - } - return NULL; +QTreeWidgetItem* vvMainWindow::GetItemFromSlicerManager(vvSlicerManager* sm) +{ + QString id = sm->GetId().c_str(); + for (int i = 0; i < DataTree->topLevelItemCount(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString() == id) + return DataTree->topLevelItem(i); + } + return NULL; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::DisplayChanged(QTreeWidgetItem *clicked_item, int column) { +void vvMainWindow::DisplayChanged(QTreeWidgetItem *clicked_item, int column) +{ int index = GetSlicerIndexFromItem(clicked_item); if ( column >= COLUMN_CLOSE_IMAGE || column <= 0) return; - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - //Trick to avoid redoing twice the job for a key (sr) - mSlicerManagers[i]->GetSlicer(column-1)->GetRenderWindow()-> GetInteractor()->SetKeySym("Crap"); - - QTreeWidgetItem* current_row=DataTree->topLevelItem(i); - if (DataTree->topLevelItem(index) == current_row) - { - vvSlicer* clicked_slicer=mSlicerManagers[i]->GetSlicer(column-1); - if (current_row == clicked_item) - { - //If we just activated a slicer - if (current_row->data(column,Qt::CheckStateRole).toInt() > 0) - { - mSlicerManagers[i]->UpdateSlicer(column-1,clicked_item->data(column,Qt::CheckStateRole).toInt()); - mSlicerManagers[i]->UpdateInfoOnCursorPosition(column-1); - DisplaySliders(i,column-1); - std::map overlay_counts; - for (int child = 0; child < current_row->childCount(); child++) - { - std::string overlay_type = - current_row->child(child)->data(1,Qt::UserRole).toString().toStdString(); - overlay_counts[overlay_type]++; - current_row->child(child)->setData(column,Qt::CheckStateRole, - current_row->data(column,Qt::CheckStateRole)); - clicked_slicer->SetActorVisibility(overlay_type,overlay_counts[overlay_type]-1,true); - } - } - else //We don't allow simply desactivating a slicer - { - clicked_item->setData(column,Qt::CheckStateRole,2); - return; - } - } - //if we clicked on the vector(or overlay) and not the image - else - { - if (clicked_item->data(column,Qt::CheckStateRole).toInt()) - { - current_row->setData(column,Qt::CheckStateRole,2); - mSlicerManagers[i]->UpdateSlicer(column-1,2); - mSlicerManagers[i]->UpdateInfoOnCursorPosition(column-1); - DisplaySliders(i,column-1); - } - int vis = clicked_item->data(column,Qt::CheckStateRole).toInt(); - std::string overlay_type = clicked_item->data(1,Qt::UserRole).toString().toStdString(); - int overlay_index=0; - for (int child = 0; child < current_row->childCount(); child++) - { - if (current_row->child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type) - overlay_index++; - if (current_row->child(child) == clicked_item) break; - } - clicked_slicer->SetActorVisibility( - clicked_item->data(1,Qt::UserRole).toString().toStdString(), overlay_index-1,vis); - } - } - else if (current_row->data(column,Qt::CheckStateRole).toInt() > 0) - { - current_row->setData(column,Qt::CheckStateRole,0); - mSlicerManagers[i]->UpdateSlicer(column-1,0); + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + //Trick to avoid redoing twice the job for a key (sr) + mSlicerManagers[i]->GetSlicer(column-1)->GetRenderWindow()-> GetInteractor()->SetKeySym("Crap"); + + QTreeWidgetItem* current_row=DataTree->topLevelItem(i); + if (DataTree->topLevelItem(index) == current_row) { + vvSlicer* clicked_slicer=mSlicerManagers[i]->GetSlicer(column-1); + if (current_row == clicked_item) { + //If we just activated a slicer + if (current_row->data(column,Qt::CheckStateRole).toInt() > 0) { + mSlicerManagers[i]->UpdateSlicer(column-1,clicked_item->data(column,Qt::CheckStateRole).toInt()); + mSlicerManagers[i]->UpdateInfoOnCursorPosition(column-1); + DisplaySliders(i,column-1); std::map overlay_counts; - for (int child = 0; child < current_row->childCount(); child++) - { - std::string overlay_type = - current_row->child(child)->data(1,Qt::UserRole).toString().toStdString(); - overlay_counts[overlay_type]++; - current_row->child(child)->setData(column,Qt::CheckStateRole,0); - vvSlicer * current_slicer=mSlicerManagers[i]->GetSlicer(column-1); - current_slicer->SetActorVisibility(overlay_type,overlay_counts[overlay_type]-1,false); - } + for (int child = 0; child < current_row->childCount(); child++) { + std::string overlay_type = + current_row->child(child)->data(1,Qt::UserRole).toString().toStdString(); + overlay_counts[overlay_type]++; + current_row->child(child)->setData(column,Qt::CheckStateRole, + current_row->data(column,Qt::CheckStateRole)); + clicked_slicer->SetActorVisibility(overlay_type,overlay_counts[overlay_type]-1,true); + } + } else { //We don't allow simply desactivating a slicer + clicked_item->setData(column,Qt::CheckStateRole,2); + return; + } + } + //if we clicked on the vector(or overlay) and not the image + else { + if (clicked_item->data(column,Qt::CheckStateRole).toInt()) { + current_row->setData(column,Qt::CheckStateRole,2); + mSlicerManagers[i]->UpdateSlicer(column-1,2); + mSlicerManagers[i]->UpdateInfoOnCursorPosition(column-1); + DisplaySliders(i,column-1); } - //mSlicerManagers[i]->SetColorMap(-1); - mSlicerManagers[i]->SetColorMap(); + int vis = clicked_item->data(column,Qt::CheckStateRole).toInt(); + std::string overlay_type = clicked_item->data(1,Qt::UserRole).toString().toStdString(); + int overlay_index=0; + for (int child = 0; child < current_row->childCount(); child++) { + if (current_row->child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type) + overlay_index++; + if (current_row->child(child) == clicked_item) break; + } + clicked_slicer->SetActorVisibility( + clicked_item->data(1,Qt::UserRole).toString().toStdString(), overlay_index-1,vis); + } + } else if (current_row->data(column,Qt::CheckStateRole).toInt() > 0) { + current_row->setData(column,Qt::CheckStateRole,0); + mSlicerManagers[i]->UpdateSlicer(column-1,0); + std::map overlay_counts; + for (int child = 0; child < current_row->childCount(); child++) { + std::string overlay_type = + current_row->child(child)->data(1,Qt::UserRole).toString().toStdString(); + overlay_counts[overlay_type]++; + current_row->child(child)->setData(column,Qt::CheckStateRole,0); + vvSlicer * current_slicer=mSlicerManagers[i]->GetSlicer(column-1); + current_slicer->SetActorVisibility(overlay_type,overlay_counts[overlay_type]-1,false); + } } + //mSlicerManagers[i]->SetColorMap(-1); + mSlicerManagers[i]->SetColorMap(); + } mSlicerManagers[index]->GetSlicer(column-1)->Render(); } //------------------------------------------------------------------------------ void vvMainWindow::InitSlicers() { - if (mSlicerManagers.size()) - { - mSlicerManagers.back()->GenerateDefaultLookupTable(); + if (mSlicerManagers.size()) { + mSlicerManagers.back()->GenerateDefaultLookupTable(); - mSlicerManagers.back()->SetSlicerWindow(0,NOViewWidget->GetRenderWindow()); - mSlicerManagers.back()->SetSlicerWindow(1,NEViewWidget->GetRenderWindow()); - mSlicerManagers.back()->SetSlicerWindow(2,SOViewWidget->GetRenderWindow()); - mSlicerManagers.back()->SetSlicerWindow(3,SEViewWidget->GetRenderWindow()); - } + mSlicerManagers.back()->SetSlicerWindow(0,NOViewWidget->GetRenderWindow()); + mSlicerManagers.back()->SetSlicerWindow(1,NEViewWidget->GetRenderWindow()); + mSlicerManagers.back()->SetSlicerWindow(2,SOViewWidget->GetRenderWindow()); + mSlicerManagers.back()->SetSlicerWindow(3,SEViewWidget->GetRenderWindow()); + } } //------------------------------------------------------------------------------ -void vvMainWindow::InitDisplay() { - if (mSlicerManagers.size()) - { - //BE CAREFUL : this is absolutely necessary to set the interactor style - //in order to have the same style instanciation for all SlicerManagers in - // a same window - for (int j = 0; j < 4; j++) - { - vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New(); - style->SetAutoAdjustCameraClippingRange(1); - bool AlreadySelected = false; - for (int i = 0; i < DataTree->topLevelItemCount(); i++) - { - mSlicerManagers[i]->SetInteractorStyleNavigator(j,style); - - //select the image only if previous are not selected - if (DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 1) - { - mSlicerManagers[i]->UpdateSlicer(j,1); - AlreadySelected = true; - } - else if (i == DataTree->topLevelItemCount()-1 && !AlreadySelected) - { - if (DataTree->selectedItems().size() == 0) - DataTree->topLevelItem(i)->setSelected(1); - DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,2); - mSlicerManagers[i]->UpdateSlicer(j,1); - DisplaySliders(i,j); - } - else - { - DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,0); - mSlicerManagers[i]->UpdateSlicer(j,0); - } - } - style->Delete(); +void vvMainWindow::InitDisplay() +{ + if (mSlicerManagers.size()) { + //BE CAREFUL : this is absolutely necessary to set the interactor style + //in order to have the same style instanciation for all SlicerManagers in + // a same window + for (int j = 0; j < 4; j++) { + vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New(); + style->SetAutoAdjustCameraClippingRange(1); + bool AlreadySelected = false; + for (int i = 0; i < DataTree->topLevelItemCount(); i++) { + mSlicerManagers[i]->SetInteractorStyleNavigator(j,style); + + //select the image only if previous are not selected + if (DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 1) { + mSlicerManagers[i]->UpdateSlicer(j,1); + AlreadySelected = true; + } else if (i == DataTree->topLevelItemCount()-1 && !AlreadySelected) { + if (DataTree->selectedItems().size() == 0) + DataTree->topLevelItem(i)->setSelected(1); + DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,2); + mSlicerManagers[i]->UpdateSlicer(j,1); + DisplaySliders(i,j); + } else { + DataTree->topLevelItem(i)->setData(j+1,Qt::CheckStateRole,0); + mSlicerManagers[i]->UpdateSlicer(j,0); } + } + style->Delete(); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::DisplaySliders(int slicer, int window) { +void vvMainWindow::DisplaySliders(int slicer, int window) +{ int range[2]; mSlicerManagers[slicer]->GetSlicer(window)->GetSliceRange(range); int position = mSlicerManagers[slicer]->GetSlicer(window)->GetSlice(); @@ -1506,82 +1415,74 @@ void vvMainWindow::DisplaySliders(int slicer, int window) { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::CloseImage(QTreeWidgetItem* item, int column) { +void vvMainWindow::CloseImage(QTreeWidgetItem* item, int column) +{ int index = GetSlicerIndexFromItem(item); - if (DataTree->topLevelItem(index) != item) - { - QString warning = "Do you really want to close the overlay : "; - warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - QMessageBox msgBox(QMessageBox::Warning, tr("Close Overlay"), - warning, 0, this); - msgBox.addButton(tr("Close"), QMessageBox::AcceptRole); - msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); - if (msgBox.exec() == QMessageBox::AcceptRole) - { - std::string overlay_type=item->data(1,Qt::UserRole).toString().toStdString(); - int overlay_index=0; - for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) - { - if (DataTree->topLevelItem(index)->\ - child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type) - overlay_index++; - if (DataTree->topLevelItem(index)->child(child) == item) break; - } - mSlicerManagers[index]->RemoveActor(overlay_type, overlay_index-1); - mSlicerManagers[index]->SetColorMap(0); - DataTree->topLevelItem(index)->takeChild(DataTree->topLevelItem(index)->indexOfChild(item)); - mSlicerManagers[index]->Render(); - } - } - else if (DataTree->topLevelItemCount() <= 1) - { - QString warning = "Do you really want to close the image : "; - warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - warning += "\nThis is the last image, you're about to close vv !!!"; - QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"), - warning, 0, this); - msgBox.addButton(tr("Close vv"), QMessageBox::AcceptRole); - msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); - if (msgBox.exec() == QMessageBox::AcceptRole) - { - this->close(); - } + if (DataTree->topLevelItem(index) != item) { + QString warning = "Do you really want to close the overlay : "; + warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); + QMessageBox msgBox(QMessageBox::Warning, tr("Close Overlay"), + warning, 0, this); + msgBox.addButton(tr("Close"), QMessageBox::AcceptRole); + msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); + if (msgBox.exec() == QMessageBox::AcceptRole) { + std::string overlay_type=item->data(1,Qt::UserRole).toString().toStdString(); + int overlay_index=0; + for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) { + if (DataTree->topLevelItem(index)->\ + child(child)->data(1,Qt::UserRole).toString().toStdString() == overlay_type) + overlay_index++; + if (DataTree->topLevelItem(index)->child(child) == item) break; + } + mSlicerManagers[index]->RemoveActor(overlay_type, overlay_index-1); + mSlicerManagers[index]->SetColorMap(0); + DataTree->topLevelItem(index)->takeChild(DataTree->topLevelItem(index)->indexOfChild(item)); + mSlicerManagers[index]->Render(); } - else - { - QString warning = "Do you really want to close the image : "; - warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"), - warning, 0, this); - msgBox.addButton(tr("Close"), QMessageBox::AcceptRole); - msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); - if (msgBox.exec() == QMessageBox::AcceptRole) - { - - // Tell tools that we close an image - emit AnImageIsBeingClosed(mSlicerManagers[index]); - - std::vector::iterator Manageriter = mSlicerManagers.begin(); - DataTree->takeTopLevelItem(index); - for (int i = 0; i < index; i++) - { - Manageriter++; - } - linkPanel->removeImage(index); - mSlicerManagers[index]->RemoveActors(); - delete mSlicerManagers[index]; - mSlicerManagers.erase(Manageriter); - - // - InitDisplay(); - } + } else if (DataTree->topLevelItemCount() <= 1) { + QString warning = "Do you really want to close the image : "; + warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); + warning += "\nThis is the last image, you're about to close vv !!!"; + QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"), + warning, 0, this); + msgBox.addButton(tr("Close vv"), QMessageBox::AcceptRole); + msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); + if (msgBox.exec() == QMessageBox::AcceptRole) { + this->close(); + } + } else { + QString warning = "Do you really want to close the image : "; + warning += item->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); + QMessageBox msgBox(QMessageBox::Warning, tr("Close Image"), + warning, 0, this); + msgBox.addButton(tr("Close"), QMessageBox::AcceptRole); + msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); + if (msgBox.exec() == QMessageBox::AcceptRole) { + + // Tell tools that we close an image + emit AnImageIsBeingClosed(mSlicerManagers[index]); + + std::vector::iterator Manageriter = mSlicerManagers.begin(); + DataTree->takeTopLevelItem(index); + for (int i = 0; i < index; i++) { + Manageriter++; + } + linkPanel->removeImage(index); + mSlicerManagers[index]->RemoveActors(); + delete mSlicerManagers[index]; + mSlicerManagers.erase(Manageriter); + + // + InitDisplay(); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::ReloadImage(QTreeWidgetItem* item, int column) { +void vvMainWindow::ReloadImage(QTreeWidgetItem* item, int column) +{ // int index = GetSlicerIndexFromItem(item); // QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); // if (item->data(1,Qt::UserRole).toString() == "vector") @@ -1605,7 +1506,7 @@ void vvMainWindow::ReloadImage(QTreeWidgetItem* item, int column) { // Update view and info ImageInfoChanged(); mSlicerManagers[index]->Render(); - QApplication::restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); } //------------------------------------------------------------------------------ @@ -1618,7 +1519,8 @@ void vvMainWindow::ReloadImage(QTreeWidgetItem* item, int column) { // } //------------------------------------------------------------------------------ -void vvMainWindow::SplitImage() { +void vvMainWindow::SplitImage() +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); int dim = mSlicerManagers[index]->GetDimension(); QString warning = "Do you really want to split the "; @@ -1630,151 +1532,150 @@ void vvMainWindow::SplitImage() { warning, 0, this); msgBox.addButton(tr("Split"), QMessageBox::AcceptRole); msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole); - if (msgBox.exec() == QMessageBox::AcceptRole) - { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - if (dim > 2) - { - std::string filename = DataTree->selectedItems()[0]->data(0,Qt::UserRole).toString().toStdString(); - int numberOfSlice = mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetSize()[dim-1]; - std::string path = itksys::SystemTools::GetFilenamePath( - filename); - path += "/"; - path += DataTree->selectedItems()[0]->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString().toStdString(); - path += "%03d"; - path += itksys::SystemTools::GetFilenameLastExtension( - filename).c_str(); - - typedef itk::NumericSeriesFileNames NameGeneratorType; - NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); - nameGenerator->SetSeriesFormat(path.c_str()); - nameGenerator->SetStartIndex(0); - nameGenerator->SetEndIndex(numberOfSlice-1); - nameGenerator->SetIncrementIndex(1); - - for (int i = 0; i < numberOfSlice; i++) - { - vvSlicerManager* imageManager = new vvSlicerManager(4); - imageManager->SetExtractedImage(nameGenerator->GetFileNames()[i], - mSlicerManagers[index]->GetSlicer(0)->GetImage(), i); - mSlicerManagers.push_back(imageManager); - - //create an item in the tree with good settings - QTreeWidgetItem *item = new QTreeWidgetItem(); - item->setData(0,Qt::UserRole,nameGenerator->GetFileNames()[i].c_str()); - std::string fileI = itksys::SystemTools::GetFilenameWithoutLastExtension( - nameGenerator->GetFileNames()[i]).c_str(); - item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileI.c_str()); - for (int j = 1; j <= 4; j++) - { - for (int i = 0; i < DataTree->topLevelItemCount(); i++) - { - DataTree->topLevelItem(i)->setData(j,Qt::CheckStateRole,0); - } - item->setData(j,Qt::CheckStateRole,2); - } - - //Create the buttons for reload and close - QTreePushButton* cButton = new QTreePushButton; - cButton->setItem(item); - cButton->setColumn(COLUMN_CLOSE_IMAGE); - cButton->setToolTip(tr("close image")); - cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); - connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(CloseImage(QTreeWidgetItem*, int))); - - QTreePushButton* rButton = new QTreePushButton; - rButton->setItem(item); - rButton->setColumn(COLUMN_RELOAD_IMAGE); - rButton->setToolTip(tr("reload image")); - rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); - rButton->setEnabled(false); - connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(ReloadImage(QTreeWidgetItem*, int))); - - DataTree->addTopLevelItem(item); - DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); - DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); - - //set the id of the image - QString id = nameGenerator->GetFileNames()[i].c_str() + QString::number(mSlicerManagers.size()-1); - item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); - mSlicerManagers.back()->SetId(id.toStdString()); - linkPanel->addImage(fileI, id.toStdString()); - connect(mSlicerManagers.back(),SIGNAL(currentImageChanged(std::string)), - this,SLOT(CurrentImageChanged(std::string))); - connect(mSlicerManagers.back(),SIGNAL( - UpdatePosition(int, double, double, double, double, double, double, double)),this, - SLOT(MousePositionChanged(int,double, double, double, double, double, double, double))); - connect(mSlicerManagers.back(),SIGNAL(UpdateVector(int, double, double, double, double)), - this, SLOT(VectorChanged(int,double,double,double, double))); - connect(mSlicerManagers.back(),SIGNAL(UpdateOverlay(int, double, double)), - this, SLOT(OverlayChanged(int,double,double))); - connect(mSlicerManagers.back(),SIGNAL(UpdateFusion(int, double)), - this, SLOT(FusionChanged(int,double))); - connect(mSlicerManagers.back(),SIGNAL(UpdateWindows(int, int, int)), - this,SLOT(WindowsChanged(int, int, int))); - connect(mSlicerManagers.back(),SIGNAL(WindowLevelChanged(double, double,int, int)), - this,SLOT(WindowLevelChanged(double, double, int, int))); - connect(mSlicerManagers.back(),SIGNAL(UpdateSlice(int,int)), - this,SLOT(UpdateSlice(int,int))); - connect(mSlicerManagers.back(),SIGNAL(UpdateTSlice(int, int)), - this,SLOT(UpdateTSlice(int, int))); - connect(mSlicerManagers.back(),SIGNAL(UpdateSliceRange(int,int,int,int,int)), - this,SLOT(UpdateSliceRange(int,int,int,int,int))); - connect(mSlicerManagers.back(),SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)), - this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int))); - connect(mSlicerManagers.back(),SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint())); - UpdateTree(); - qApp->processEvents(); - InitSlicers(); - InitDisplay(); - qApp->processEvents(); - } - QApplication::restoreOverrideCursor(); - } - else - { - QApplication::restoreOverrideCursor(); - QString error = "Cannot split file (dimensions must be greater than 2) "; - QMessageBox::information(this,tr("Splitting problem"),error); + if (msgBox.exec() == QMessageBox::AcceptRole) { + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + if (dim > 2) { + std::string filename = DataTree->selectedItems()[0]->data(0,Qt::UserRole).toString().toStdString(); + int numberOfSlice = mSlicerManagers[index]->GetSlicer(0)->GetImage()->GetSize()[dim-1]; + std::string path = itksys::SystemTools::GetFilenamePath( + filename); + path += "/"; + path += DataTree->selectedItems()[0]->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString().toStdString(); + path += "%03d"; + path += itksys::SystemTools::GetFilenameLastExtension( + filename).c_str(); + + typedef itk::NumericSeriesFileNames NameGeneratorType; + NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New(); + nameGenerator->SetSeriesFormat(path.c_str()); + nameGenerator->SetStartIndex(0); + nameGenerator->SetEndIndex(numberOfSlice-1); + nameGenerator->SetIncrementIndex(1); + + for (int i = 0; i < numberOfSlice; i++) { + vvSlicerManager* imageManager = new vvSlicerManager(4); + imageManager->SetExtractedImage(nameGenerator->GetFileNames()[i], + mSlicerManagers[index]->GetSlicer(0)->GetImage(), i); + mSlicerManagers.push_back(imageManager); + + //create an item in the tree with good settings + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setData(0,Qt::UserRole,nameGenerator->GetFileNames()[i].c_str()); + std::string fileI = itksys::SystemTools::GetFilenameWithoutLastExtension( + nameGenerator->GetFileNames()[i]).c_str(); + item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,fileI.c_str()); + for (int j = 1; j <= 4; j++) { + for (int i = 0; i < DataTree->topLevelItemCount(); i++) { + DataTree->topLevelItem(i)->setData(j,Qt::CheckStateRole,0); + } + item->setData(j,Qt::CheckStateRole,2); } - } -} -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ -void vvMainWindow::MousePositionChanged(int visibility,double x, double y, double z, double X, double Y, double Z , double value) { + //Create the buttons for reload and close + QTreePushButton* cButton = new QTreePushButton; + cButton->setItem(item); + cButton->setColumn(COLUMN_CLOSE_IMAGE); + cButton->setToolTip(tr("close image")); + cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); + connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(CloseImage(QTreeWidgetItem*, int))); + + QTreePushButton* rButton = new QTreePushButton; + rButton->setItem(item); + rButton->setColumn(COLUMN_RELOAD_IMAGE); + rButton->setToolTip(tr("reload image")); + rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); + rButton->setEnabled(false); + connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(ReloadImage(QTreeWidgetItem*, int))); + + DataTree->addTopLevelItem(item); + DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); + DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); + + //set the id of the image + QString id = nameGenerator->GetFileNames()[i].c_str() + QString::number(mSlicerManagers.size()-1); + item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); + mSlicerManagers.back()->SetId(id.toStdString()); + linkPanel->addImage(fileI, id.toStdString()); + connect(mSlicerManagers.back(),SIGNAL(currentImageChanged(std::string)), + this,SLOT(CurrentImageChanged(std::string))); + connect(mSlicerManagers.back(),SIGNAL( + UpdatePosition(int, double, double, double, double, double, double, double)),this, + SLOT(MousePositionChanged(int,double, double, double, double, double, double, double))); + connect(mSlicerManagers.back(),SIGNAL(UpdateVector(int, double, double, double, double)), + this, SLOT(VectorChanged(int,double,double,double, double))); + connect(mSlicerManagers.back(),SIGNAL(UpdateOverlay(int, double, double)), + this, SLOT(OverlayChanged(int,double,double))); + connect(mSlicerManagers.back(),SIGNAL(UpdateFusion(int, double)), + this, SLOT(FusionChanged(int,double))); + connect(mSlicerManagers.back(),SIGNAL(UpdateWindows(int, int, int)), + this,SLOT(WindowsChanged(int, int, int))); + connect(mSlicerManagers.back(),SIGNAL(WindowLevelChanged(double, double,int, int)), + this,SLOT(WindowLevelChanged(double, double, int, int))); + connect(mSlicerManagers.back(),SIGNAL(UpdateSlice(int,int)), + this,SLOT(UpdateSlice(int,int))); + connect(mSlicerManagers.back(),SIGNAL(UpdateTSlice(int, int)), + this,SLOT(UpdateTSlice(int, int))); + connect(mSlicerManagers.back(),SIGNAL(UpdateSliceRange(int,int,int,int,int)), + this,SLOT(UpdateSliceRange(int,int,int,int,int))); + connect(mSlicerManagers.back(),SIGNAL(UpdateLinkManager(std::string,int,double,double,double,int)), + this,SLOT(UpdateLinkManager(std::string,int,double,double,double,int))); + connect(mSlicerManagers.back(),SIGNAL(LandmarkAdded()),landmarksPanel,SLOT(AddPoint())); + UpdateTree(); + qApp->processEvents(); + InitSlicers(); + InitDisplay(); + qApp->processEvents(); + } + QApplication::restoreOverrideCursor(); + } else { + QApplication::restoreOverrideCursor(); + QString error = "Cannot split file (dimensions must be greater than 2) "; + QMessageBox::information(this,tr("Splitting problem"),error); + } + } +} +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +void vvMainWindow::MousePositionChanged(int visibility,double x, double y, double z, double X, double Y, double Z , double value) +{ infoPanel->setCurrentInfo(visibility,x,y,z,X,Y,Z,value); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::VectorChanged(int visibility,double x, double y, double z, double value) { +void vvMainWindow::VectorChanged(int visibility,double x, double y, double z, double value) +{ overlayPanel->getCurrentVectorInfo(visibility,x,y,z,value); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::OverlayChanged(int visibility, double valueOver, double valueRef) { +void vvMainWindow::OverlayChanged(int visibility, double valueOver, double valueRef) +{ overlayPanel->getCurrentOverlayInfo(visibility,valueOver, valueRef); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::FusionChanged(int visibility, double value) { +void vvMainWindow::FusionChanged(int visibility, double value) +{ overlayPanel->getCurrentFusionInfo(visibility,value); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::WindowsChanged(int window, int view, int slice) { +void vvMainWindow::WindowsChanged(int window, int view, int slice) +{ infoPanel->setViews(window, view, slice); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::WindowLevelChanged(double window, double level,int preset,int colormap) { +void vvMainWindow::WindowLevelChanged(double window, double level,int preset,int colormap) +{ windowSpinBox->setValue(window); levelSpinBox->setValue(level); colorMapComboBox->setCurrentIndex(colormap); @@ -1783,38 +1684,40 @@ void vvMainWindow::WindowLevelChanged(double window, double level,int preset,int //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::WindowLevelEdited() { +void vvMainWindow::WindowLevelEdited() +{ presetComboBox->setCurrentIndex(6); UpdateWindowLevel(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::UpdateWindowLevel() { - if (DataTree->selectedItems().size()) - { - if (presetComboBox->currentIndex() == 7) //For ventilation - colorMapComboBox->setCurrentIndex(5); - int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - mSlicerManagers[index]->SetColorWindow(windowSpinBox->value()); - mSlicerManagers[index]->SetColorLevel(levelSpinBox->value()); - mSlicerManagers[index]->SetPreset(presetComboBox->currentIndex()); - mSlicerManagers[index]->Render(); - } +void vvMainWindow::UpdateWindowLevel() +{ + if (DataTree->selectedItems().size()) { + if (presetComboBox->currentIndex() == 7) //For ventilation + colorMapComboBox->setCurrentIndex(5); + int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); + mSlicerManagers[index]->SetColorWindow(windowSpinBox->value()); + mSlicerManagers[index]->SetColorLevel(levelSpinBox->value()); + mSlicerManagers[index]->SetPreset(presetComboBox->currentIndex()); + mSlicerManagers[index]->Render(); + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::UpdateColorMap() { - if (DataTree->selectedItems().size()) - { - int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - mSlicerManagers[index]->SetColorMap(colorMapComboBox->currentIndex()); - mSlicerManagers[index]->Render(); - } +void vvMainWindow::UpdateColorMap() +{ + if (DataTree->selectedItems().size()) { + int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); + mSlicerManagers[index]->SetColorMap(colorMapComboBox->currentIndex()); + mSlicerManagers[index]->Render(); + } } //------------------------------------------------------------------------------ -void vvMainWindow::SwitchWindowLevel() { +void vvMainWindow::SwitchWindowLevel() +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); int window = mSlicerManagers[index]->GetColorWindow(); presetComboBox->setCurrentIndex(6); @@ -1824,79 +1727,78 @@ void vvMainWindow::SwitchWindowLevel() { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::UpdateLinkManager(std::string id, int slicer, double x, double y, double z, int temps) { - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (mSlicerManagers[i]->GetId() == id) - { - //mSlicerManagers[i]->SetTSlice(temps); - mSlicerManagers[i]->GetSlicer(slicer)->SetCurrentPosition(x,y,z,temps); - mSlicerManagers[i]->UpdateViews(0,slicer); - break; - } +void vvMainWindow::UpdateLinkManager(std::string id, int slicer, double x, double y, double z, int temps) +{ + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (mSlicerManagers[i]->GetId() == id) { + //mSlicerManagers[i]->SetTSlice(temps); + mSlicerManagers[i]->GetSlicer(slicer)->SetCurrentPosition(x,y,z,temps); + mSlicerManagers[i]->UpdateViews(0,slicer); + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::ShowContextMenu(QPoint point) { - if (!DataTree->selectedItems().size()) - { - contextActions[1]->setEnabled(0); - contextActions[2]->setEnabled(0); - contextActions[3]->setEnabled(0); +void vvMainWindow::ShowContextMenu(QPoint point) +{ + if (!DataTree->selectedItems().size()) { + contextActions[1]->setEnabled(0); + contextActions[2]->setEnabled(0); + contextActions[3]->setEnabled(0); + contextActions[4]->setEnabled(0); + contextActions[5]->setEnabled(0); + contextActions[6]->setEnabled(0); + contextActions[7]->setEnabled(0); + } else { + int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); + contextActions[1]->setEnabled(1); + contextActions[2]->setEnabled( + DataTree->itemWidget(DataTree->selectedItems()[0], + COLUMN_RELOAD_IMAGE)->isEnabled()); + contextActions[3]->setEnabled(1); + contextActions[5]->setEnabled(1); + contextActions[6]->setEnabled(1); + contextActions[7]->setEnabled(1); + + if (mSlicerManagers[index]->GetDimension() < 3) contextActions[4]->setEnabled(0); - contextActions[5]->setEnabled(0); - contextActions[6]->setEnabled(0); - contextActions[7]->setEnabled(0); - } - else - { - int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - contextActions[1]->setEnabled(1); - contextActions[2]->setEnabled( - DataTree->itemWidget(DataTree->selectedItems()[0], - COLUMN_RELOAD_IMAGE)->isEnabled()); - contextActions[3]->setEnabled(1); - contextActions[5]->setEnabled(1); - contextActions[6]->setEnabled(1); - contextActions[7]->setEnabled(1); - - if (mSlicerManagers[index]->GetDimension() < 3) - contextActions[4]->setEnabled(0); - else - contextActions[4]->setEnabled(1); - } + else + contextActions[4]->setEnabled(1); + } contextMenu.exec(QCursor::pos()); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::CloseImage() { +void vvMainWindow::CloseImage() +{ CloseImage(DataTree->selectedItems()[0],0); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::ReloadImage() { +void vvMainWindow::ReloadImage() +{ ReloadImage(DataTree->selectedItems()[0],0); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SelectOverlayImage() { +void vvMainWindow::SelectOverlayImage() +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); //check if one overlay image is added for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) - if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "overlay") - { - QString error = "Cannot add more than one compared image\n"; - error += "Please remove first "; - error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - QMessageBox::information(this,tr("Problem adding compared image !"),error); - return; - } + if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "overlay") { + QString error = "Cannot add more than one compared image\n"; + error += "Please remove first "; + error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); + QMessageBox::information(this,tr("Problem adding compared image !"),error); + return; + } QString Extensions = EXTENSIONS; Extensions += ";;All Files (*)"; @@ -1907,11 +1809,12 @@ void vvMainWindow::SelectOverlayImage() { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::AddOverlayImage(int index, QString file) { +void vvMainWindow::AddOverlayImage(int index, QString file) +{ mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str(); itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( - file.toStdString().c_str(), itk::ImageIOFactory::ReadMode); + file.toStdString().c_str(), itk::ImageIOFactory::ReadMode); reader->SetFileName(file.toStdString().c_str()); reader->ReadImageInformation(); std::string component = reader->GetComponentTypeAsString(reader->GetComponentType()); @@ -1919,62 +1822,58 @@ void vvMainWindow::AddOverlayImage(int index, QString file) { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); vvProgressDialog progress("Opening " + file.toStdString()); qApp->processEvents(); - - std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str(); - if (mSlicerManagers[index]->SetOverlay(file.toStdString(),dimension, component)) - { - //create an item in the tree with good settings - QTreeWidgetItem *item = new QTreeWidgetItem(); - item->setData(0,Qt::UserRole,file.toStdString().c_str()); - item->setData(1,Qt::UserRole,tr("overlay")); - item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str()); - qApp->processEvents(); - - for (int j = 1; j <= 4; j++) - { - item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole)); - mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("overlay",0, - DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt()); - } - - //Create the buttons for reload and close - qApp->processEvents(); - QTreePushButton* cButton = new QTreePushButton; - cButton->setItem(item); - cButton->setColumn(COLUMN_CLOSE_IMAGE); - cButton->setToolTip(tr("close image")); - cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); - connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(CloseImage(QTreeWidgetItem*, int))); - QTreePushButton* rButton = new QTreePushButton; - rButton->setItem(item); - rButton->setColumn(COLUMN_RELOAD_IMAGE); - rButton->setToolTip(tr("reload image")); - rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); - connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(ReloadImage(QTreeWidgetItem*, int))); - - DataTree->topLevelItem(index)->setExpanded(1); - DataTree->topLevelItem(index)->addChild(item); - DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); - DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); + std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str(); + if (mSlicerManagers[index]->SetOverlay(file.toStdString(),dimension, component)) { + //create an item in the tree with good settings + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setData(0,Qt::UserRole,file.toStdString().c_str()); + item->setData(1,Qt::UserRole,tr("overlay")); + item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str()); + qApp->processEvents(); - //set the id of the image - QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString(); - item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); - UpdateTree(); - qApp->processEvents(); - ImageInfoChanged(); - QApplication::restoreOverrideCursor(); - } - else - { - QApplication::restoreOverrideCursor(); - QString error = "Cannot import the new image.\n"; - error += mSlicerManagers[index]->GetLastError().c_str(); - QMessageBox::information(this,tr("Problem reading image !"),error); + for (int j = 1; j <= 4; j++) { + item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole)); + mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("overlay",0, + DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt()); } + + //Create the buttons for reload and close + qApp->processEvents(); + QTreePushButton* cButton = new QTreePushButton; + cButton->setItem(item); + cButton->setColumn(COLUMN_CLOSE_IMAGE); + cButton->setToolTip(tr("close image")); + cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); + connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(CloseImage(QTreeWidgetItem*, int))); + + QTreePushButton* rButton = new QTreePushButton; + rButton->setItem(item); + rButton->setColumn(COLUMN_RELOAD_IMAGE); + rButton->setToolTip(tr("reload image")); + rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); + connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(ReloadImage(QTreeWidgetItem*, int))); + + DataTree->topLevelItem(index)->setExpanded(1); + DataTree->topLevelItem(index)->addChild(item); + DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); + DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); + + //set the id of the image + QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString(); + item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); + UpdateTree(); + qApp->processEvents(); + ImageInfoChanged(); + QApplication::restoreOverrideCursor(); + } else { + QApplication::restoreOverrideCursor(); + QString error = "Cannot import the new image.\n"; + error += mSlicerManagers[index]->GetLastError().c_str(); + QMessageBox::information(this,tr("Problem reading image !"),error); + } } void vvMainWindow::AddFusionImage() @@ -1983,95 +1882,86 @@ void vvMainWindow::AddFusionImage() //check if one fusion image is added for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) - if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "fusion") - { - QString error = "Cannot add more than one fusion image\n"; - error += "Please remove first "; - error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - QMessageBox::information(this,tr("Problem adding fusion image !"),error); - return; - } + if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "fusion") { + QString error = "Cannot add more than one fusion image\n"; + error += "Please remove first "; + error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); + QMessageBox::information(this,tr("Problem adding fusion image !"),error); + return; + } QString Extensions = EXTENSIONS; Extensions += ";;All Files (*)"; QString file = QFileDialog::getOpenFileName(this,tr("Load Fusion image"),mInputPathName,Extensions); - if (!file.isEmpty()) - { - mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str(); - itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( - file.toStdString().c_str(), itk::ImageIOFactory::ReadMode); - reader->SetFileName(file.toStdString().c_str()); - reader->ReadImageInformation(); - std::string component = reader->GetComponentTypeAsString(reader->GetComponentType()); - if (reader) - { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - vvProgressDialog progress("Opening fusion"); - qApp->processEvents(); - - std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str(); - if (mSlicerManagers[index]->SetFusion(file.toStdString(), - reader->GetNumberOfDimensions(), component)) - { - //create an item in the tree with good settings - QTreeWidgetItem *item = new QTreeWidgetItem(); - item->setData(0,Qt::UserRole,file.toStdString().c_str()); - item->setData(1,Qt::UserRole,tr("fusion")); - item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str()); - qApp->processEvents(); - - for (int j = 1; j <= 4; j++) - { - item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole)); - mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("fusion",0, - DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt()); - } - - //Create the buttons for reload and close - qApp->processEvents(); - QTreePushButton* cButton = new QTreePushButton; - cButton->setItem(item); - cButton->setColumn(COLUMN_CLOSE_IMAGE); - cButton->setToolTip(tr("close image")); - cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); - connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(CloseImage(QTreeWidgetItem*, int))); - - QTreePushButton* rButton = new QTreePushButton; - rButton->setItem(item); - rButton->setColumn(COLUMN_RELOAD_IMAGE); - rButton->setToolTip(tr("reload image")); - rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); - connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), - this,SLOT(ReloadImage(QTreeWidgetItem*, int))); - - DataTree->topLevelItem(index)->setExpanded(1); - DataTree->topLevelItem(index)->addChild(item); - DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); - DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); - - //set the id of the image - QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString(); - item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); - UpdateTree(); - qApp->processEvents(); - ImageInfoChanged(); - QApplication::restoreOverrideCursor(); - } - else - { - QApplication::restoreOverrideCursor(); - QString error = "Cannot import the new image.\n"; - error += mSlicerManagers[index]->GetLastError().c_str(); - QMessageBox::information(this,tr("Problem reading image !"),error); - } - } - else - { - QString error = "Cannot import the new image.\n"; - QMessageBox::information(this,tr("Problem reading image !"),error); + if (!file.isEmpty()) { + mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str(); + itk::ImageIOBase::Pointer reader = itk::ImageIOFactory::CreateImageIO( + file.toStdString().c_str(), itk::ImageIOFactory::ReadMode); + reader->SetFileName(file.toStdString().c_str()); + reader->ReadImageInformation(); + std::string component = reader->GetComponentTypeAsString(reader->GetComponentType()); + if (reader) { + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + vvProgressDialog progress("Opening fusion"); + qApp->processEvents(); + + std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str(); + if (mSlicerManagers[index]->SetFusion(file.toStdString(), + reader->GetNumberOfDimensions(), component)) { + //create an item in the tree with good settings + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setData(0,Qt::UserRole,file.toStdString().c_str()); + item->setData(1,Qt::UserRole,tr("fusion")); + item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename.c_str()); + qApp->processEvents(); + + for (int j = 1; j <= 4; j++) { + item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole)); + mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("fusion",0, + DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt()); } + + //Create the buttons for reload and close + qApp->processEvents(); + QTreePushButton* cButton = new QTreePushButton; + cButton->setItem(item); + cButton->setColumn(COLUMN_CLOSE_IMAGE); + cButton->setToolTip(tr("close image")); + cButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/exit.png"))); + connect(cButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(CloseImage(QTreeWidgetItem*, int))); + + QTreePushButton* rButton = new QTreePushButton; + rButton->setItem(item); + rButton->setColumn(COLUMN_RELOAD_IMAGE); + rButton->setToolTip(tr("reload image")); + rButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/rotateright.png"))); + connect(rButton,SIGNAL(clickedInto(QTreeWidgetItem*, int)), + this,SLOT(ReloadImage(QTreeWidgetItem*, int))); + + DataTree->topLevelItem(index)->setExpanded(1); + DataTree->topLevelItem(index)->addChild(item); + DataTree->setItemWidget(item, COLUMN_CLOSE_IMAGE, cButton); + DataTree->setItemWidget(item, COLUMN_RELOAD_IMAGE, rButton); + + //set the id of the image + QString id = DataTree->topLevelItem(index)->data(COLUMN_IMAGE_NAME,Qt::UserRole).toString(); + item->setData(COLUMN_IMAGE_NAME,Qt::UserRole,id.toStdString().c_str()); + UpdateTree(); + qApp->processEvents(); + ImageInfoChanged(); + QApplication::restoreOverrideCursor(); + } else { + QApplication::restoreOverrideCursor(); + QString error = "Cannot import the new image.\n"; + error += mSlicerManagers[index]->GetLastError().c_str(); + QMessageBox::information(this,tr("Problem reading image !"),error); + } + } else { + QString error = "Cannot import the new image.\n"; + QMessageBox::information(this,tr("Problem reading image !"),error); } + } } //------------------------------------------------------------------------------ @@ -2082,14 +1972,13 @@ void vvMainWindow::OpenField() int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); //check if a vector field has already been added for (int child = 0; child < DataTree->topLevelItem(index)->childCount(); child++) - if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "vector") - { - QString error = "Cannot add more than one vector field\n"; - error += "Please remove first "; - error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); - QMessageBox::information(this,tr("Problem adding vector field!"),error); - return; - } + if (DataTree->topLevelItem(index)->child(child)->data(1,Qt::UserRole).toString() == "vector") { + QString error = "Cannot add more than one vector field\n"; + error += "Please remove first "; + error += DataTree->topLevelItem(index)->child(child)->data(COLUMN_IMAGE_NAME,Qt::DisplayRole).toString(); + QMessageBox::information(this,tr("Problem adding vector field!"),error); + return; + } QString Extensions = "Images ( *.mhd)"; Extensions += ";;Images ( *.vf)"; @@ -2110,12 +1999,11 @@ void vvMainWindow::AddFieldEntry(QString filename,int index,bool from_disk) item->setData(COLUMN_IMAGE_NAME,Qt::DisplayRole,filename); qApp->processEvents(); - for (int j = 1; j <= 4; j++) - { - item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole)); - mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("vector",0, - DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt()); - } + for (int j = 1; j <= 4; j++) { + item->setData(j,Qt::CheckStateRole,DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole)); + mSlicerManagers[index]->GetSlicer(j-1)->SetActorVisibility("vector",0, + DataTree->topLevelItem(index)->data(j,Qt::CheckStateRole).toInt()); + } //Create the buttons for reload and close qApp->processEvents(); @@ -2157,16 +2045,13 @@ void vvMainWindow::AddField(vvImage::Pointer vf,QString file,int index) { QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); vvSlicerManager* imageManager = mSlicerManagers[index]; - if (imageManager->SetVF(vf,file.toStdString())) - { - AddFieldEntry(file,index,false); - } - else - { - QString error = "Cannot import the vector field for this image.\n"; - error += imageManager->GetLastError().c_str(); - QMessageBox::information(this,tr("Problem reading VF !"),error); - } + if (imageManager->SetVF(vf,file.toStdString())) { + AddFieldEntry(file,index,false); + } else { + QString error = "Cannot import the vector field for this image.\n"; + error += imageManager->GetLastError().c_str(); + QMessageBox::information(this,tr("Problem reading VF !"),error); + } QApplication::restoreOverrideCursor(); } //------------------------------------------------------------------------------ @@ -2175,34 +2060,29 @@ void vvMainWindow::AddField(vvImage::Pointer vf,QString file,int index) //------------------------------------------------------------------------------ void vvMainWindow::AddField(QString file,int index) { - if (QFile::exists(file)) - { - mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str(); + if (QFile::exists(file)) { + mInputPathName = itksys::SystemTools::GetFilenamePath(file.toStdString()).c_str(); - //init the progress events - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - vvProgressDialog progress("Opening " + file.toStdString()); - qApp->processEvents(); + //init the progress events + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + vvProgressDialog progress("Opening " + file.toStdString()); + qApp->processEvents(); - //read the vector and put it in the current mSlicerManager - vvSlicerManager* imageManager = mSlicerManagers[index]; - qApp->processEvents(); + //read the vector and put it in the current mSlicerManager + vvSlicerManager* imageManager = mSlicerManagers[index]; + qApp->processEvents(); - std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str(); - if (imageManager->SetVF(file.toStdString())) - { - imageManager->Render(); - AddFieldEntry(file,index,true); - } - else - { - QApplication::restoreOverrideCursor(); - QString error = "Cannot import the vector field for this image.\n"; - error += imageManager->GetLastError().c_str(); - QMessageBox::information(this,tr("Problem reading VF !"),error); - } + std::string filename = itksys::SystemTools::GetFilenameWithoutExtension(file.toStdString()).c_str(); + if (imageManager->SetVF(file.toStdString())) { + imageManager->Render(); + AddFieldEntry(file,index,true); + } else { + QApplication::restoreOverrideCursor(); + QString error = "Cannot import the vector field for this image.\n"; + error += imageManager->GetLastError().c_str(); + QMessageBox::information(this,tr("Problem reading VF !"),error); } - else + } else QMessageBox::information(this,tr("Problem reading VF !"),"File doesn't exist!"); } @@ -2210,226 +2090,209 @@ void vvMainWindow::AddField(QString file,int index) //------------------------------------------------------------------------------ -void vvMainWindow::SetVFProperty(int subsampling, int scale, int log, int width) { +void vvMainWindow::SetVFProperty(int subsampling, int scale, int log, int width) +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) - { - for (int i = 0; i < 4; i++) - { - mSlicerManagers[index]->GetSlicer(i)->SetVFSubSampling(subsampling); - mSlicerManagers[index]->GetSlicer(i)->SetVFScale(scale); - mSlicerManagers[index]->GetSlicer(i)->SetVFWidth(width); - if (log > 0) - mSlicerManagers[index]->GetSlicer(i)->SetVFLog(1); - else - mSlicerManagers[index]->GetSlicer(i)->SetVFLog(0); - } + if (mSlicerManagers[index]->GetSlicer(0)->GetVF()) { + for (int i = 0; i < 4; i++) { + mSlicerManagers[index]->GetSlicer(i)->SetVFSubSampling(subsampling); + mSlicerManagers[index]->GetSlicer(i)->SetVFScale(scale); + mSlicerManagers[index]->GetSlicer(i)->SetVFWidth(width); + if (log > 0) + mSlicerManagers[index]->GetSlicer(i)->SetVFLog(1); + else + mSlicerManagers[index]->GetSlicer(i)->SetVFLog(0); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SetOverlayProperty(int color) { +void vvMainWindow::SetOverlayProperty(int color) +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) - { - mSlicerManagers[index]->SetOverlayColor(color); - mSlicerManagers[index]->SetColorMap(0); - mSlicerManagers[index]->Render(); - } + if (mSlicerManagers[index]->GetSlicer(0)->GetOverlay()) { + mSlicerManagers[index]->SetOverlayColor(color); + mSlicerManagers[index]->SetColorMap(0); + mSlicerManagers[index]->Render(); + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SetFusionProperty(int opacity, int colormap,double window, double level) { +void vvMainWindow::SetFusionProperty(int opacity, int colormap,double window, double level) +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) - { - mSlicerManagers[index]->SetFusionOpacity(opacity); - mSlicerManagers[index]->SetFusionColorMap(colormap); - mSlicerManagers[index]->SetFusionWindow(window); - mSlicerManagers[index]->SetFusionLevel(level); - mSlicerManagers[index]->SetColorMap(0); - mSlicerManagers[index]->Render(); - } + if (mSlicerManagers[index]->GetSlicer(0)->GetFusion()) { + mSlicerManagers[index]->SetFusionOpacity(opacity); + mSlicerManagers[index]->SetFusionColorMap(colormap); + mSlicerManagers[index]->SetFusionWindow(window); + mSlicerManagers[index]->SetFusionLevel(level); + mSlicerManagers[index]->SetColorMap(0); + mSlicerManagers[index]->Render(); + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SaveAs() { - if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") - { - QMessageBox::warning(this,tr("Unsupported type"),tr("Sorry, saving a vector field is unsupported for the moment")); - return; - } +void vvMainWindow::SaveAs() +{ + if (DataTree->selectedItems()[0]->data(1,Qt::UserRole).toString() == "vector") { + QMessageBox::warning(this,tr("Unsupported type"),tr("Sorry, saving a vector field is unsupported for the moment")); + return; + } int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); int dimension = mSlicerManagers[index]->GetDimension(); QStringList OutputListeFormat; OutputListeFormat.clear(); - if (dimension == 1) - { - OutputListeFormat.push_back(".mhd"); - } - if (dimension == 2) - { - OutputListeFormat.push_back(".bmp"); - OutputListeFormat.push_back(".png"); - OutputListeFormat.push_back(".jpeg"); - OutputListeFormat.push_back(".tif"); - OutputListeFormat.push_back(".mhd"); - OutputListeFormat.push_back(".hdr"); - OutputListeFormat.push_back(".vox"); - } - else if (dimension == 3) - { - OutputListeFormat.push_back(".mhd"); - OutputListeFormat.push_back(".hdr"); - OutputListeFormat.push_back(".vox"); - } - else if (dimension == 4) - { - OutputListeFormat.push_back(".mhd"); - } + if (dimension == 1) { + OutputListeFormat.push_back(".mhd"); + } + if (dimension == 2) { + OutputListeFormat.push_back(".bmp"); + OutputListeFormat.push_back(".png"); + OutputListeFormat.push_back(".jpeg"); + OutputListeFormat.push_back(".tif"); + OutputListeFormat.push_back(".mhd"); + OutputListeFormat.push_back(".hdr"); + OutputListeFormat.push_back(".vox"); + } else if (dimension == 3) { + OutputListeFormat.push_back(".mhd"); + OutputListeFormat.push_back(".hdr"); + OutputListeFormat.push_back(".vox"); + } else if (dimension == 4) { + OutputListeFormat.push_back(".mhd"); + } QString Extensions = "AllFiles(*.*)"; - for (int i = 0; i < OutputListeFormat.count(); i++) - { - Extensions += ";;Images ( *"; - Extensions += OutputListeFormat[i]; - Extensions += ")"; - } + for (int i = 0; i < OutputListeFormat.count(); i++) { + Extensions += ";;Images ( *"; + Extensions += OutputListeFormat[i]; + Extensions += ")"; + } QString fileName = QFileDialog::getSaveFileName(this, - tr("Save As"), - mSlicerManagers[index]->GetFileName().c_str(), - Extensions); - if (!fileName.isEmpty()) - { - std::string fileformat = itksys::SystemTools::GetFilenameLastExtension(fileName.toStdString()); - if (OutputListeFormat.contains( - fileformat.c_str())) - { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - std::string action = "Saving"; - vvProgressDialog progress("Saving "+fileName.toStdString()); - qApp->processEvents(); - vvImageWriter *writer = new vvImageWriter; - writer->SetOutputFileName(fileName.toStdString()); - writer->SetInput(mSlicerManagers[index]->GetImage()); - writer->Update(); - QApplication::restoreOverrideCursor(); - if (writer->GetLastError().size()) - { - QString error = "Saving did not succeed\n"; - error += writer->GetLastError().c_str(); - QMessageBox::information(this,tr("Saving Problem"),error); - SaveAs(); - } - } + tr("Save As"), + mSlicerManagers[index]->GetFileName().c_str(), + Extensions); + if (!fileName.isEmpty()) { + std::string fileformat = itksys::SystemTools::GetFilenameLastExtension(fileName.toStdString()); + if (OutputListeFormat.contains( + fileformat.c_str())) { + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + std::string action = "Saving"; + vvProgressDialog progress("Saving "+fileName.toStdString()); + qApp->processEvents(); + vvImageWriter *writer = new vvImageWriter; + writer->SetOutputFileName(fileName.toStdString()); + writer->SetInput(mSlicerManagers[index]->GetImage()); + writer->Update(); + QApplication::restoreOverrideCursor(); + if (writer->GetLastError().size()) { + QString error = "Saving did not succeed\n"; + error += writer->GetLastError().c_str(); + QMessageBox::information(this,tr("Saving Problem"),error); + SaveAs(); + } + } else { + QString error = fileformat.c_str(); + if (error.isEmpty()) + error += "no file format specified !"; else - { - QString error = fileformat.c_str(); - if (error.isEmpty()) - error += "no file format specified !"; - else - error += " format unknown !!!\n"; - QMessageBox::information(this,tr("Saving Problem"),error); - SaveAs(); - } + error += " format unknown !!!\n"; + QMessageBox::information(this,tr("Saving Problem"),error); + SaveAs(); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::AddLink(QString image1,QString image2) { - for (unsigned int i = 0; i < mSlicerManagers.size();i++) - { - if (image1.toStdString() == mSlicerManagers[i]->GetId()) - { - mSlicerManagers[i]->AddLink(image2.toStdString()); - } - if (image2.toStdString() == mSlicerManagers[i]->GetId()) - { - mSlicerManagers[i]->AddLink(image1.toStdString()); - } +void vvMainWindow::AddLink(QString image1,QString image2) +{ + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (image1.toStdString() == mSlicerManagers[i]->GetId()) { + mSlicerManagers[i]->AddLink(image2.toStdString()); + } + if (image2.toStdString() == mSlicerManagers[i]->GetId()) { + mSlicerManagers[i]->AddLink(image1.toStdString()); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::RemoveLink(QString image1,QString image2) { +void vvMainWindow::RemoveLink(QString image1,QString image2) +{ // DD("vvMainWindow:RemoveLink"); - for (unsigned int i = 0; i < mSlicerManagers.size();i++) - { - if (image1.toStdString() == mSlicerManagers[i]->GetId()) - { - mSlicerManagers[i]->RemoveLink(image2.toStdString()); - } - if (image2.toStdString() == mSlicerManagers[i]->GetId()) - { - mSlicerManagers[i]->RemoveLink(image1.toStdString()); - } + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (image1.toStdString() == mSlicerManagers[i]->GetId()) { + mSlicerManagers[i]->RemoveLink(image2.toStdString()); + } + if (image2.toStdString() == mSlicerManagers[i]->GetId()) { + mSlicerManagers[i]->RemoveLink(image1.toStdString()); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void vvMainWindow::ChangeImageWithIndexOffset(vvSlicerManager *sm, int slicer, int offset) { - int index = 0; - while(sm != mSlicerManagers[index]) - index++; - index = (index+offset) % mSlicerManagers.size(); + int index = 0; + while(sm != mSlicerManagers[index]) + index++; + index = (index+offset) % mSlicerManagers.size(); - QTreeWidgetItem* item = GetItemFromSlicerManager(mSlicerManagers[index]); - //CurrentImageChanged(mSlicerManagers[index]->GetId()); //select new image - item->setData(slicer+1,Qt::CheckStateRole,2); //change checkbox - DisplayChanged(item,slicer+1); + QTreeWidgetItem* item = GetItemFromSlicerManager(mSlicerManagers[index]); + //CurrentImageChanged(mSlicerManagers[index]->GetId()); //select new image + item->setData(slicer+1,Qt::CheckStateRole,2); //change checkbox + DisplayChanged(item,slicer+1); } //------------------------------------------------------------------------------ void vvMainWindow::HorizontalSliderMoved(int value,int column, int slicer_index) { - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (DataTree->topLevelItem(i)->data(column,Qt::CheckStateRole).toInt() > 1) - { - for (int j = 0; j < 4; j++) - { - mSlicerManagers[i]->SetTSliceInSlicer(value,j); - //if (mSlicerManagers[i]->GetSlicer(j)->GetImageActor()->GetVisibility()) - //UpdateTSlice(j,value); - } - mSlicerManagers[i]->GetSlicer(slicer_index)->Render(); - break; - } + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (DataTree->topLevelItem(i)->data(column,Qt::CheckStateRole).toInt() > 1) { + for (int j = 0; j < 4; j++) { + mSlicerManagers[i]->SetTSliceInSlicer(value,j); + //if (mSlicerManagers[i]->GetSlicer(j)->GetImageActor()->GetVisibility()) + //UpdateTSlice(j,value); + } + mSlicerManagers[i]->GetSlicer(slicer_index)->Render(); + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::NOHorizontalSliderMoved() { +void vvMainWindow::NOHorizontalSliderMoved() +{ // if (mCurrentTime == NOHorizontalSlider->value()) return; HorizontalSliderMoved(NOHorizontalSlider->value(),COLUMN_UL_VIEW,0); - // mCurrentTime = NOHorizontalSlider->value(); +// mCurrentTime = NOHorizontalSlider->value(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::NEHorizontalSliderMoved() { +void vvMainWindow::NEHorizontalSliderMoved() +{ // if (mCurrentTime == NEHorizontalSlider->value()) return; HorizontalSliderMoved(NEHorizontalSlider->value(),COLUMN_UR_VIEW,1); - // mCurrentTime = NEHorizontalSlider->value(); +// mCurrentTime = NEHorizontalSlider->value(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SOHorizontalSliderMoved() { +void vvMainWindow::SOHorizontalSliderMoved() +{ // if (mCurrentTime == SOHorizontalSlider->value()) return; HorizontalSliderMoved(SOHorizontalSlider->value(),COLUMN_DL_VIEW,2); // mCurrentTime = SOHorizontalSlider->value(); @@ -2438,7 +2301,8 @@ void vvMainWindow::SOHorizontalSliderMoved() { //------------------------------------------------------------------------------ -void vvMainWindow::SEHorizontalSliderMoved() { +void vvMainWindow::SEHorizontalSliderMoved() +{ // if (mCurrentTime == SEHorizontalSlider->value()) return; HorizontalSliderMoved(SEHorizontalSlider->value(),COLUMN_DR_VIEW,3); // mCurrentTime = SEHorizontalSlider->value(); @@ -2446,119 +2310,115 @@ void vvMainWindow::SEHorizontalSliderMoved() { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::NOVerticalSliderChanged() { +void vvMainWindow::NOVerticalSliderChanged() +{ static int value=-1; if (value == NOVerticalSlider->value()) return; - else value = NOVerticalSlider->value(); + else value = NOVerticalSlider->value(); // int value = NOVerticalSlider->value(); - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_UL_VIEW,Qt::CheckStateRole).toInt() > 1) - { - if (mSlicerManagers[i]->GetSlicer(0)->GetSlice() != value) { - mSlicerManagers[i]->GetSlicer(0)->SetSlice(value); - mSlicerManagers[i]->VerticalSliderHasChanged(0, value); - mSlicerManagers[i]->UpdateSlice(0); // <-- DS add this. Not too much update ? YES. but needed for ImageContour ... - //mSlicerManagers[i]->GetSlicer(0)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? - } - break; - } + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_UL_VIEW,Qt::CheckStateRole).toInt() > 1) { + if (mSlicerManagers[i]->GetSlicer(0)->GetSlice() != value) { + mSlicerManagers[i]->GetSlicer(0)->SetSlice(value); + mSlicerManagers[i]->VerticalSliderHasChanged(0, value); + mSlicerManagers[i]->UpdateSlice(0); // <-- DS add this. Not too much update ? YES. but needed for ImageContour ... + //mSlicerManagers[i]->GetSlicer(0)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? + } + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::NEVerticalSliderChanged() { +void vvMainWindow::NEVerticalSliderChanged() +{ static int value=-1; if (value == NEVerticalSlider->value()) return; - else value = NEVerticalSlider->value(); + else value = NEVerticalSlider->value(); // int value = NEVerticalSlider->value(); - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_UR_VIEW,Qt::CheckStateRole).toInt() > 1) - { - if (mSlicerManagers[i]->GetSlicer(1)->GetSlice() != value) { - mSlicerManagers[i]->GetSlicer(1)->SetSlice(value); - mSlicerManagers[i]->VerticalSliderHasChanged(1, value); - mSlicerManagers[i]->UpdateSlice(1); - //mSlicerManagers[i]->GetSlicer(1)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? - } - break; - } + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_UR_VIEW,Qt::CheckStateRole).toInt() > 1) { + if (mSlicerManagers[i]->GetSlicer(1)->GetSlice() != value) { + mSlicerManagers[i]->GetSlicer(1)->SetSlice(value); + mSlicerManagers[i]->VerticalSliderHasChanged(1, value); + mSlicerManagers[i]->UpdateSlice(1); + //mSlicerManagers[i]->GetSlicer(1)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? + } + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SOVerticalSliderChanged() { +void vvMainWindow::SOVerticalSliderChanged() +{ // DD("SOVerticalSliderChanged"); static int value=-1; // DD(value); // DD(SOVerticalSlider->value()); if (value == SOVerticalSlider->value()) return; - else value = SOVerticalSlider->value(); + else value = SOVerticalSlider->value(); //int value = SOVerticalSlider->value(); - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_DL_VIEW,Qt::CheckStateRole).toInt() > 1) - { - if (mSlicerManagers[i]->GetSlicer(2)->GetSlice() != value) { - mSlicerManagers[i]->GetSlicer(2)->SetSlice(value); - mSlicerManagers[i]->VerticalSliderHasChanged(2, value); - mSlicerManagers[i]->UpdateSlice(2); - //mSlicerManagers[i]->GetSlicer(2)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? - } - // else { DD("avoid SOVerticalSlider slicer update"); } - break; - } + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_DL_VIEW,Qt::CheckStateRole).toInt() > 1) { + if (mSlicerManagers[i]->GetSlicer(2)->GetSlice() != value) { + mSlicerManagers[i]->GetSlicer(2)->SetSlice(value); + mSlicerManagers[i]->VerticalSliderHasChanged(2, value); + mSlicerManagers[i]->UpdateSlice(2); + //mSlicerManagers[i]->GetSlicer(2)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? + } + // else { DD("avoid SOVerticalSlider slicer update"); } + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SEVerticalSliderChanged() { +void vvMainWindow::SEVerticalSliderChanged() +{ static int value=-1; if (value == SEVerticalSlider->value()) return; - else value = SEVerticalSlider->value(); + else value = SEVerticalSlider->value(); // int value = SEVerticalSlider->value(); - for (unsigned int i = 0; i < mSlicerManagers.size(); i++) - { - if (DataTree->topLevelItem(i)->data(COLUMN_DR_VIEW,Qt::CheckStateRole).toInt() > 1) - { - if (mSlicerManagers[i]->GetSlicer(3)->GetSlice() != value) { - mSlicerManagers[i]->GetSlicer(3)->SetSlice(value); - mSlicerManagers[i]->VerticalSliderHasChanged(3, value); - mSlicerManagers[i]->UpdateSlice(3); - //mSlicerManagers[i]->GetSlicer(3)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? - } - break; - } + for (unsigned int i = 0; i < mSlicerManagers.size(); i++) { + if (DataTree->topLevelItem(i)->data(COLUMN_DR_VIEW,Qt::CheckStateRole).toInt() > 1) { + if (mSlicerManagers[i]->GetSlicer(3)->GetSlice() != value) { + mSlicerManagers[i]->GetSlicer(3)->SetSlice(value); + mSlicerManagers[i]->VerticalSliderHasChanged(3, value); + mSlicerManagers[i]->UpdateSlice(3); + //mSlicerManagers[i]->GetSlicer(3)->Render(); // <-- DS add this, needed for contour, seems ok ? not too slow ? + } + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::UpdateSlice(int slicer, int slice) { +void vvMainWindow::UpdateSlice(int slicer, int slice) +{ // DD("vvMainWindow::UpdateSlice"); // DD(slicer); // DD(slice); if (slicer == 0) { // if (slice != NOVerticalSlider->value()) NOVerticalSlider->setValue(slice); - } - else { + } else { if (slicer == 1) - NEVerticalSlider->setValue(slice); + NEVerticalSlider->setValue(slice); else { if (slicer == 2) - SOVerticalSlider->setValue(slice); + SOVerticalSlider->setValue(slice); else { - if (slicer == 3) - SEVerticalSlider->setValue(slice); + if (slicer == 3) + SEVerticalSlider->setValue(slice); } } } @@ -2568,64 +2428,59 @@ void vvMainWindow::UpdateSlice(int slicer, int slice) { //------------------------------------------------------------------------------ -void vvMainWindow::UpdateTSlice(int slicer, int slice) { - switch (slicer) - { - case 0: - NOHorizontalSlider->setValue(slice); - break; - case 1: - NEHorizontalSlider->setValue(slice); - break; - case 2: - SOHorizontalSlider->setValue(slice); - break; - case 3: - SEHorizontalSlider->setValue(slice); - break; - } +void vvMainWindow::UpdateTSlice(int slicer, int slice) +{ + switch (slicer) { + case 0: + NOHorizontalSlider->setValue(slice); + break; + case 1: + NEHorizontalSlider->setValue(slice); + break; + case 2: + SOHorizontalSlider->setValue(slice); + break; + case 3: + SEHorizontalSlider->setValue(slice); + break; + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::UpdateSliceRange(int slicer, int min, int max, int tmin, int tmax) { +void vvMainWindow::UpdateSliceRange(int slicer, int min, int max, int tmin, int tmax) +{ int position = int((min+max)/2); int tPosition = int((tmin+tmax)/2); - if (slicer == 0) - { - NOVerticalSlider->setValue(position); - NOVerticalSlider->setRange(min,max); - NOHorizontalSlider->setRange(tmin,tmax); - NOHorizontalSlider->setValue(tPosition); - } - else if (slicer == 1) - { - NEVerticalSlider->setValue(position); - NEVerticalSlider->setRange(min,max); - NEHorizontalSlider->setRange(tmin,tmax); - NEHorizontalSlider->setValue(tPosition); - } - else if (slicer == 2) - { - SOVerticalSlider->setValue(position); - SOVerticalSlider->setRange(min,max); - SOHorizontalSlider->setRange(tmin,tmax); - SOHorizontalSlider->setValue(tPosition); - } - else if (slicer == 3) - { - SEVerticalSlider->setValue(position); - SEVerticalSlider->setRange(min,max); - SEHorizontalSlider->setRange(tmin,tmax); - SEHorizontalSlider->setValue(tPosition); - } + if (slicer == 0) { + NOVerticalSlider->setValue(position); + NOVerticalSlider->setRange(min,max); + NOHorizontalSlider->setRange(tmin,tmax); + NOHorizontalSlider->setValue(tPosition); + } else if (slicer == 1) { + NEVerticalSlider->setValue(position); + NEVerticalSlider->setRange(min,max); + NEHorizontalSlider->setRange(tmin,tmax); + NEHorizontalSlider->setValue(tPosition); + } else if (slicer == 2) { + SOVerticalSlider->setValue(position); + SOVerticalSlider->setRange(min,max); + SOHorizontalSlider->setRange(tmin,tmax); + SOHorizontalSlider->setValue(tPosition); + } else if (slicer == 3) { + SEVerticalSlider->setValue(position); + SEVerticalSlider->setRange(min,max); + SEHorizontalSlider->setRange(tmin,tmax); + SEHorizontalSlider->setValue(tPosition); + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SaveNOScreenshot() { +void vvMainWindow::SaveNOScreenshot() +{ vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New(); w2i->SetInput(NOViewWidget->GetRenderWindow()); w2i->Update(); @@ -2636,7 +2491,8 @@ void vvMainWindow::SaveNOScreenshot() { //------------------------------------------------------------------------------ -void vvMainWindow::SaveNEScreenshot() { +void vvMainWindow::SaveNEScreenshot() +{ vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New(); w2i->SetInput(NEViewWidget->GetRenderWindow()); w2i->Update(); @@ -2647,7 +2503,8 @@ void vvMainWindow::SaveNEScreenshot() { //------------------------------------------------------------------------------ -void vvMainWindow::SaveSOScreenshot() { +void vvMainWindow::SaveSOScreenshot() +{ vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New(); w2i->SetInput(SOViewWidget->GetRenderWindow()); w2i->Update(); @@ -2658,7 +2515,8 @@ void vvMainWindow::SaveSOScreenshot() { //------------------------------------------------------------------------------ -void vvMainWindow::SaveSEScreenshot() { +void vvMainWindow::SaveSEScreenshot() +{ vtkWindowToImageFilter *w2i = vtkWindowToImageFilter::New(); w2i->SetInput(SEViewWidget->GetRenderWindow()); w2i->Update(); @@ -2669,149 +2527,132 @@ void vvMainWindow::SaveSEScreenshot() { //------------------------------------------------------------------------------ -void vvMainWindow::SaveScreenshot(vtkImageData* image) { +void vvMainWindow::SaveScreenshot(vtkImageData* image) +{ QString Extensions = "Images( *.png);;"; Extensions += "Images( *.jpg);;"; Extensions += "Images( *.bmp);;"; Extensions += "Images( *.tif);;"; Extensions += "Images( *.ppm)"; QString fileName = QFileDialog::getSaveFileName(this, - tr("Save As"), - itksys::SystemTools::GetFilenamePath( - mSlicerManagers[0]->GetFileName()).c_str(), - Extensions); - if (!fileName.isEmpty()) - { - const char *ext = fileName.toStdString().c_str() + strlen(fileName.toStdString().c_str()) - 4; - if (!strcmp(ext, ".bmp")) - { - vtkBMPWriter *bmp = vtkBMPWriter::New(); - bmp->SetInput(image); - bmp->SetFileName(fileName.toStdString().c_str()); - bmp->Write(); - bmp->Delete(); - } - else if (!strcmp(ext, ".tif")) - { - vtkTIFFWriter *tif = vtkTIFFWriter::New(); - tif->SetInput(image); - tif->SetFileName(fileName.toStdString().c_str()); - tif->Write(); - tif->Delete(); - } - else if (!strcmp(ext, ".ppm")) - { - vtkPNMWriter *pnm = vtkPNMWriter::New(); - pnm->SetInput(image); - pnm->SetFileName(fileName.toStdString().c_str()); - pnm->Write(); - pnm->Delete(); - } - else if (!strcmp(ext, ".png")) - { - vtkPNGWriter *png = vtkPNGWriter::New(); - png->SetInput(image); - png->SetFileName(fileName.toStdString().c_str()); - png->Write(); - png->Delete(); - } - else if (!strcmp(ext, ".jpg")) - { - vtkJPEGWriter *jpg = vtkJPEGWriter::New(); - jpg->SetInput(image); - jpg->SetFileName(fileName.toStdString().c_str()); - jpg->Write(); - jpg->Delete(); - } - else - { - QMessageBox::information(this,tr("Problem saving screenshot !"),tr("Cannot save image.\nPlease set a file extension !!!")); - } + tr("Save As"), + itksys::SystemTools::GetFilenamePath( + mSlicerManagers[0]->GetFileName()).c_str(), + Extensions); + if (!fileName.isEmpty()) { + const char *ext = fileName.toStdString().c_str() + strlen(fileName.toStdString().c_str()) - 4; + if (!strcmp(ext, ".bmp")) { + vtkBMPWriter *bmp = vtkBMPWriter::New(); + bmp->SetInput(image); + bmp->SetFileName(fileName.toStdString().c_str()); + bmp->Write(); + bmp->Delete(); + } else if (!strcmp(ext, ".tif")) { + vtkTIFFWriter *tif = vtkTIFFWriter::New(); + tif->SetInput(image); + tif->SetFileName(fileName.toStdString().c_str()); + tif->Write(); + tif->Delete(); + } else if (!strcmp(ext, ".ppm")) { + vtkPNMWriter *pnm = vtkPNMWriter::New(); + pnm->SetInput(image); + pnm->SetFileName(fileName.toStdString().c_str()); + pnm->Write(); + pnm->Delete(); + } else if (!strcmp(ext, ".png")) { + vtkPNGWriter *png = vtkPNGWriter::New(); + png->SetInput(image); + png->SetFileName(fileName.toStdString().c_str()); + png->Write(); + png->Delete(); + } else if (!strcmp(ext, ".jpg")) { + vtkJPEGWriter *jpg = vtkJPEGWriter::New(); + jpg->SetInput(image); + jpg->SetFileName(fileName.toStdString().c_str()); + jpg->Write(); + jpg->Delete(); + } else { + QMessageBox::information(this,tr("Problem saving screenshot !"),tr("Cannot save image.\nPlease set a file extension !!!")); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::GoToCursor() { +void vvMainWindow::GoToCursor() +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); - for (int column = 1; column < 5; column++) - { - if (DataTree->selectedItems()[0]->data(column,Qt::CheckStateRole).toInt() > 1) - { - double* cursorPos = mSlicerManagers[index]->GetSlicer(column-1)->GetCursorPosition(); - mSlicerManagers[index]->GetSlicer(column-1)->SetCurrentPosition( - cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]); - mSlicerManagers[index]->UpdateViews(1,column-1); - mSlicerManagers[index]->UpdateLinked(column-1); - break; - } + for (int column = 1; column < 5; column++) { + if (DataTree->selectedItems()[0]->data(column,Qt::CheckStateRole).toInt() > 1) { + double* cursorPos = mSlicerManagers[index]->GetSlicer(column-1)->GetCursorPosition(); + mSlicerManagers[index]->GetSlicer(column-1)->SetCurrentPosition( + cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]); + mSlicerManagers[index]->UpdateViews(1,column-1); + mSlicerManagers[index]->UpdateLinked(column-1); + break; } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::PlayPause() { - if (playMode) - { - playMode = 0; - playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_play.png"))); - ImageInfoChanged(); - return; - } - else - { - int image_number=DataTree->topLevelItemCount(); - bool has_temporal; - for (int i=0;iGetImage()->GetVTKImages().size() > 1) - { - has_temporal=true; - break; - } - if (has_temporal) - { - playMode = 1; - playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_pause.png"))); - QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext())); - } +void vvMainWindow::PlayPause() +{ + if (playMode) { + playMode = 0; + playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_play.png"))); + ImageInfoChanged(); + return; + } else { + int image_number=DataTree->topLevelItemCount(); + bool has_temporal; + for (int i=0; iGetImage()->GetVTKImages().size() > 1) { + has_temporal=true; + break; + } + if (has_temporal) { + playMode = 1; + playButton->setIcon(QIcon(QString::fromUtf8(":/common/icons/player_pause.png"))); + QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext())); } + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::PlayNext() { - if (playMode && !this->isHidden()) - { - int image_number=DataTree->topLevelItemCount(); - ///Only play one slicer per SM, and only if the SM is being displayed - for (int i=0;iGetImage()->GetVTKImages().size() > 1 && - DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 0) - { - mSlicerManagers[i]->SetNextTSlice(j); - break; - } - QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext())); - } +void vvMainWindow::PlayNext() +{ + if (playMode && !this->isHidden()) { + int image_number=DataTree->topLevelItemCount(); + ///Only play one slicer per SM, and only if the SM is being displayed + for (int i=0; iGetImage()->GetVTKImages().size() > 1 && + DataTree->topLevelItem(i)->data(j+1,Qt::CheckStateRole).toInt() > 0) { + mSlicerManagers[i]->SetNextTSlice(j); + break; + } + QTimer::singleShot(1000/mFrameRate, this, SLOT(PlayNext())); + } } //------------------------------------------------------------------------------ void vvMainWindow::ShowLastImage() { - if (mSlicerManagers.size() > 1) - { - QTreeWidgetItem * item=DataTree->topLevelItem(DataTree->topLevelItemCount()-1); - CurrentImageChanged(mSlicerManagers.back()->GetId()); //select new image - item->setData(1,Qt::CheckStateRole,2); //show the new image in the first panel - DisplayChanged(item,1); - } + if (mSlicerManagers.size() > 1) { + QTreeWidgetItem * item=DataTree->topLevelItem(DataTree->topLevelItemCount()-1); + CurrentImageChanged(mSlicerManagers.back()->GetId()); //select new image + item->setData(1,Qt::CheckStateRole,2); //show the new image in the first panel + DisplayChanged(item,1); + } } //------------------------------------------------------------------------------ -void vvMainWindow::UpdateRenderWindows() { +void vvMainWindow::UpdateRenderWindows() +{ if (NOViewWidget->GetRenderWindow()) NOViewWidget->GetRenderWindow()->Render(); if (NEViewWidget->GetRenderWindow()) NEViewWidget->GetRenderWindow()->Render(); if (SOViewWidget->GetRenderWindow()) SOViewWidget->GetRenderWindow()->Render(); @@ -2820,7 +2661,8 @@ void vvMainWindow::UpdateRenderWindows() { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvMainWindow::SegmentationOnCurrentImage() { +void vvMainWindow::SegmentationOnCurrentImage() +{ int index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); vvSegmentationDialog segmentation; @@ -2915,12 +2757,13 @@ void vvMainWindow::AddImage(vvImage::Pointer image,std::string filename) //------------------------------------------------------------------------------ -void vvMainWindow::UpdateCurrentSlicer() { +void vvMainWindow::UpdateCurrentSlicer() +{ int index = -1; if (DataTree->selectedItems().size() > 0) { index = GetSlicerIndexFromItem(DataTree->selectedItems()[0]); } - mSlicerManagerCurrentIndex = index; + mSlicerManagerCurrentIndex = index; } //------------------------------------------------------------------------------ diff --git a/vv/vvMainWindow.txx b/vv/vvMainWindow.txx index 519c86c..9550e7e 100644 --- a/vv/vvMainWindow.txx +++ b/vv/vvMainWindow.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr diff --git a/vv/vvMainWindowBase.cxx b/vv/vvMainWindowBase.cxx index fd7ad83..c94b1cd 100644 --- a/vv/vvMainWindowBase.cxx +++ b/vv/vvMainWindowBase.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr diff --git a/vv/vvMaximumIntensityProjection.cxx b/vv/vvMaximumIntensityProjection.cxx index 8baeb55..077a884 100644 --- a/vv/vvMaximumIntensityProjection.cxx +++ b/vv/vvMaximumIntensityProjection.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -30,48 +30,47 @@ void vvMaximumIntensityProjection::Compute(vvSlicerManager * slicer_manager) { #define TRY_TYPE(TYPE) \ if (clitk::IsSameType(image->GetScalarTypeAsString())) { this->Update_WithPixelType(image); return; } - std::string list = clitk::CreateListOfTypes(); - vvImage::Pointer image=slicer_manager->GetSlicer(0)->GetImage(); - TRY_TYPE(float); - TRY_TYPE(double); - TRY_TYPE(int); - TRY_TYPE(unsigned int); - TRY_TYPE(short); - TRY_TYPE(unsigned short); - TRY_TYPE(char); - TRY_TYPE(unsigned char); - QMessageBox::warning(0,"Unsupported image type",QString("Error, I don't know the type")+QString(image->GetScalarTypeAsString().c_str()) +QString("' for the input image.\nKnown types are ") + QString(list.c_str())); - error=true; + std::string list = clitk::CreateListOfTypes(); + vvImage::Pointer image=slicer_manager->GetSlicer(0)->GetImage(); + TRY_TYPE(float); + TRY_TYPE(double); + TRY_TYPE(int); + TRY_TYPE(unsigned int); + TRY_TYPE(short); + TRY_TYPE(unsigned short); + TRY_TYPE(char); + TRY_TYPE(unsigned char); + QMessageBox::warning(0,"Unsupported image type",QString("Error, I don't know the type")+QString(image->GetScalarTypeAsString().c_str()) +QString("' for the input image.\nKnown types are ") + QString(list.c_str())); + error=true; #undef TRY_TYPE } template void vvMaximumIntensityProjection::Update_WithPixelType(vvImage::Pointer image) { - switch(image->GetNumberOfDimensions()) - { - case 3: - Update_WithDimAndPixelType(image); - break;; - case 4: - Update_WithDimAndPixelType(image); - break;; - default: - QMessageBox::warning(0,"Unsupported image dimension",QString("Unsupported image dimension. Supported dimensions are 3 and 4")); - error=true; - } + switch(image->GetNumberOfDimensions()) { + case 3: + Update_WithDimAndPixelType(image); + break;; + case 4: + Update_WithDimAndPixelType(image); + break;; + default: + QMessageBox::warning(0,"Unsupported image dimension",QString("Unsupported image dimension. Supported dimensions are 3 and 4")); + error=true; + } } template void vvMaximumIntensityProjection::Update_WithDimAndPixelType(vvImage::Pointer image) { - typedef itk::Image ImageType; - typedef itk::Image OutputImageType; - typedef itk::MaximumProjectionImageFilter FilterType; - typename FilterType::Pointer filter = FilterType::New(); - filter->SetProjectionDimension(Dim-1); - typename ImageType::ConstPointer input = vvImageToITK(image); - filter->SetInput(input); - filter->Update(); - mOutputImage=vvImageFromITK(filter->GetOutput()); + typedef itk::Image ImageType; + typedef itk::Image OutputImageType; + typedef itk::MaximumProjectionImageFilter FilterType; + typename FilterType::Pointer filter = FilterType::New(); + filter->SetProjectionDimension(Dim-1); + typename ImageType::ConstPointer input = vvImageToITK(image); + filter->SetInput(input); + filter->Update(); + mOutputImage=vvImageFromITK(filter->GetOutput()); } diff --git a/vv/vvMesh.cxx b/vv/vvMesh.cxx index 4890f19..d666a21 100644 --- a/vv/vvMesh.cxx +++ b/vv/vvMesh.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -36,204 +36,192 @@ #include vvMesh::vvMesh() : - r(1),g(0),b(0), - slice_spacing(-1) + r(1),g(0),b(0), + slice_spacing(-1) {} void vvMesh::AddMesh(vtkPolyData* p) { - vtkPolyData * mesh=vtkPolyData::New(); - mesh->ShallowCopy(p); - meshes.push_back(mesh); + vtkPolyData * mesh=vtkPolyData::New(); + mesh->ShallowCopy(p); + meshes.push_back(mesh); } void vvMesh::ReadFromVTK(const char * filename) { - DD("hello!"); - std::string extension=itksys::SystemTools::GetFilenameLastExtension(std::string(filename)); - if (extension == ".vtk" || extension== ".VTK") - { - assert(GetNumberOfMeshes() == 0); ///We assume the object is empty - vtkSmartPointer r=vtkSmartPointer::New(); - r->SetFileName(filename); - r->Update(); - assert(r->GetOutput()); - AddMesh(r->GetOutput()); - } - else if (extension == ".obj" || extension== ".OBJ") - { - assert(GetNumberOfMeshes() == 0); ///We assume the object is empty - vtkSmartPointer r=vtkSmartPointer::New(); - r->SetFileName(filename); - r->Update(); - assert(r->GetOutput()); - AddMesh(r->GetOutput()); - } - else - assert (false) ; //shouldn't happen - - assert(GetNumberOfMeshes() != 0); ///We assume the object is empty - structure_name=filename; + DD("hello!"); + std::string extension=itksys::SystemTools::GetFilenameLastExtension(std::string(filename)); + if (extension == ".vtk" || extension== ".VTK") { + assert(GetNumberOfMeshes() == 0); ///We assume the object is empty + vtkSmartPointer r=vtkSmartPointer::New(); + r->SetFileName(filename); + r->Update(); + assert(r->GetOutput()); + AddMesh(r->GetOutput()); + } else if (extension == ".obj" || extension== ".OBJ") { + assert(GetNumberOfMeshes() == 0); ///We assume the object is empty + vtkSmartPointer r=vtkSmartPointer::New(); + r->SetFileName(filename); + r->Update(); + assert(r->GetOutput()); + AddMesh(r->GetOutput()); + } else + assert (false) ; //shouldn't happen + + assert(GetNumberOfMeshes() != 0); ///We assume the object is empty + structure_name=filename; } void vvMesh::RemoveMeshes() { - for (std::vector::const_iterator i=meshes.begin();i!=meshes.end();i++) - (*i)->Delete(); - meshes.erase(meshes.begin(),meshes.end()); + for (std::vector::const_iterator i=meshes.begin(); i!=meshes.end(); i++) + (*i)->Delete(); + meshes.erase(meshes.begin(),meshes.end()); } void vvMesh::AddMask(vtkImageData* im) { - assert(im->GetScalarType() == VTK_UNSIGNED_CHAR); - vtkImageData* image=vtkImageData::New(); - image->ShallowCopy(im); - masks.push_back(image); + assert(im->GetScalarType() == VTK_UNSIGNED_CHAR); + vtkImageData* image=vtkImageData::New(); + image->ShallowCopy(im); + masks.push_back(image); } void vvMesh::RemoveMasks() { - for (std::vector::const_iterator i=masks.begin();i!=masks.end();i++) - (*i)->Delete(); - masks.erase(masks.begin(),masks.end()); + for (std::vector::const_iterator i=masks.begin(); i!=masks.end(); i++) + (*i)->Delete(); + masks.erase(masks.begin(),masks.end()); } vvMesh::~vvMesh() { - RemoveMeshes(); - RemoveMasks(); + RemoveMeshes(); + RemoveMasks(); } void vvMesh::CopyInformation(vvMesh::Pointer input) { - r=input->r; - g=input->g; - b=input->b; - structure_name=input->structure_name; - slice_spacing=input->slice_spacing; + r=input->r; + g=input->g; + b=input->b; + structure_name=input->structure_name; + slice_spacing=input->slice_spacing; } void vvMesh::Print() const { - std::cout << this << " : " << structure_name << std::endl << "RGB: " << r << "," << g << "," << b << std::endl; - for (std::vector::const_iterator i=meshes.begin();i!=meshes.end();i++) - { - std::cout << (*i)->GetNumberOfPoints() << " points, " << (*i)->GetNumberOfCells() << " cells." << std::endl; - DDV((*i)->GetBounds(),6); - } - std::cout << "-------------------------" << std::endl << std::endl; + std::cout << this << " : " << structure_name << std::endl << "RGB: " << r << "," << g << "," << b << std::endl; + for (std::vector::const_iterator i=meshes.begin(); i!=meshes.end(); i++) { + std::cout << (*i)->GetNumberOfPoints() << " points, " << (*i)->GetNumberOfCells() << " cells." << std::endl; + DDV((*i)->GetBounds(),6); + } + std::cout << "-------------------------" << std::endl << std::endl; } void vvMesh::ComputeMasks(vtkImageData* sample,bool extrude) { - this->RemoveMasks(); - for (std::vector::iterator i=meshes.begin();i!=meshes.end();i++) - { - vtkPolyData* mesh=*i; - double *bounds=mesh->GetBounds(); - - vtkSmartPointer binary_image=vtkSmartPointer::New(); - binary_image->SetScalarTypeToUnsignedChar(); - ///Use the smallest mask in which the mesh fits - // Add two voxels on each side to make sure the mesh fits - double * samp_origin=sample->GetOrigin(); - double * spacing=sample->GetSpacing(); - binary_image->SetSpacing(spacing); - /// Put the origin on a voxel to avoid small skips - binary_image->SetOrigin(floor((bounds[0]-samp_origin[0])/spacing[0]-2)*spacing[0]+samp_origin[0], - floor((bounds[2]-samp_origin[1])/spacing[1]-2)*spacing[1]+samp_origin[1], - floor((bounds[4]-samp_origin[2])/spacing[2]-2)*spacing[2]+samp_origin[2]); - double * origin=binary_image->GetOrigin(); - binary_image->SetExtent(0,ceil((bounds[1]-origin[0])/spacing[0]+4), - 0,ceil((bounds[3]-origin[1])/spacing[1]+4), - 0,ceil((bounds[5]-origin[2])/spacing[2])+4); - binary_image->AllocateScalars(); - memset(binary_image->GetScalarPointer(),0,binary_image->GetDimensions()[0]*binary_image->GetDimensions()[1]*binary_image->GetDimensions()[2]*sizeof(unsigned char)); - - - vtkSmartPointer sts=vtkSmartPointer::New(); - //The following line is extremely important - //http://www.nabble.com/Bug-in-vtkPolyDataToImageStencil--td23368312.html#a23370933 - sts->SetTolerance(0); - sts->SetInformationInput(binary_image); - - if (extrude) - { - vtkSmartPointer extrude=vtkSmartPointer::New(); - extrude->SetInput(mesh); - ///We extrude in the -slice_spacing direction to respect the FOCAL convention - extrude->SetVector(0, 0, -slice_spacing); - sts->SetInput(extrude->GetOutput()); - } - else - sts->SetInput(mesh); - - vtkSmartPointer stencil=vtkSmartPointer::New(); - stencil->SetStencil(sts->GetOutput()); - stencil->SetInput(binary_image); - stencil->Update(); - this->AddMask(stencil->GetOutput()); - //vtkSmartPointer w = vtkSmartPointer::New(); - //w->SetInput(stencil->GetOutput()); - //w->SetFileName("binary.mhd"); - //w->Write(); - } + this->RemoveMasks(); + for (std::vector::iterator i=meshes.begin(); i!=meshes.end(); i++) { + vtkPolyData* mesh=*i; + double *bounds=mesh->GetBounds(); + + vtkSmartPointer binary_image=vtkSmartPointer::New(); + binary_image->SetScalarTypeToUnsignedChar(); + ///Use the smallest mask in which the mesh fits + // Add two voxels on each side to make sure the mesh fits + double * samp_origin=sample->GetOrigin(); + double * spacing=sample->GetSpacing(); + binary_image->SetSpacing(spacing); + /// Put the origin on a voxel to avoid small skips + binary_image->SetOrigin(floor((bounds[0]-samp_origin[0])/spacing[0]-2)*spacing[0]+samp_origin[0], + floor((bounds[2]-samp_origin[1])/spacing[1]-2)*spacing[1]+samp_origin[1], + floor((bounds[4]-samp_origin[2])/spacing[2]-2)*spacing[2]+samp_origin[2]); + double * origin=binary_image->GetOrigin(); + binary_image->SetExtent(0,ceil((bounds[1]-origin[0])/spacing[0]+4), + 0,ceil((bounds[3]-origin[1])/spacing[1]+4), + 0,ceil((bounds[5]-origin[2])/spacing[2])+4); + binary_image->AllocateScalars(); + memset(binary_image->GetScalarPointer(),0,binary_image->GetDimensions()[0]*binary_image->GetDimensions()[1]*binary_image->GetDimensions()[2]*sizeof(unsigned char)); + + + vtkSmartPointer sts=vtkSmartPointer::New(); + //The following line is extremely important + //http://www.nabble.com/Bug-in-vtkPolyDataToImageStencil--td23368312.html#a23370933 + sts->SetTolerance(0); + sts->SetInformationInput(binary_image); + + if (extrude) { + vtkSmartPointer extrude=vtkSmartPointer::New(); + extrude->SetInput(mesh); + ///We extrude in the -slice_spacing direction to respect the FOCAL convention + extrude->SetVector(0, 0, -slice_spacing); + sts->SetInput(extrude->GetOutput()); + } else + sts->SetInput(mesh); + + vtkSmartPointer stencil=vtkSmartPointer::New(); + stencil->SetStencil(sts->GetOutput()); + stencil->SetInput(binary_image); + stencil->Update(); + this->AddMask(stencil->GetOutput()); + //vtkSmartPointer w = vtkSmartPointer::New(); + //w->SetInput(stencil->GetOutput()); + //w->SetFileName("binary.mhd"); + //w->Write(); + } } void vvMesh::ComputeMeshes() { - this->RemoveMeshes(); - for (std::vector::iterator i=masks.begin();i!=masks.end();i++) - { - vtkSmartPointer marching = vtkSmartPointer::New(); - marching->SetInput(*i); - marching->SetValue(0,0.5); - marching->Update(); - this->AddMesh(marching->GetOutput()); - } + this->RemoveMeshes(); + for (std::vector::iterator i=masks.begin(); i!=masks.end(); i++) { + vtkSmartPointer marching = vtkSmartPointer::New(); + marching->SetInput(*i); + marching->SetValue(0,0.5); + marching->Update(); + this->AddMesh(marching->GetOutput()); + } } void vvMesh::propagateContour(vvImage::Pointer vf) { - assert(this->GetNumberOfMeshes() == 1); - std::vector sgrids=vf->GetVTKImages(); - vtkSmartPointer reference_mesh = vtkSmartPointer::New(); - reference_mesh->ShallowCopy(this->GetMesh(0)); - this->RemoveMeshes(); - - for (std::vector::iterator i=sgrids.begin(); - i!=sgrids.end();i++) - { - vtkPolyData* new_mesh=vtkPolyData::New(); - new_mesh->DeepCopy(reference_mesh); - double Ox=vf->GetOrigin()[0]; - double Oy=vf->GetOrigin()[1]; - double Oz=vf->GetOrigin()[2]; - double Sx=vf->GetSpacing()[0]; - double Sy=vf->GetSpacing()[1]; - double Sz=vf->GetSpacing()[2]; - int *dims=vf->GetVTKImages()[0]->GetDimensions(); - assert((*i)->GetScalarType() == VTK_FLOAT); //vfs are assumed to be of float type - assert((*i)->GetNumberOfScalarComponents() == 3); - float * vector_data=reinterpret_cast((*i)->GetScalarPointer()); - for (int j=0;jGetNumberOfPoints();j++) - { - double* old=new_mesh->GetPoint(j); - int ix=(old[0]-Ox)/Sx; - int iy=(old[1]-Oy)/Sy; - int iz=(old[2]-Oz)/Sz; - float* vector=vector_data+(ix+iy*vf->GetSize()[0]+iz*vf->GetSize()[0]*vf->GetSize()[1])*3; - if (ix>=0 && ix < dims[0] - && iy>=0 && iy < dims[1] - && iz>=0 && iz < dims[2]) - new_mesh->GetPoints()->SetPoint(j,old[0]+vector[0],old[1]+vector[1],old[2]+vector[2]); - } - this->AddMesh(new_mesh); - } - if (GetNumberOfMasks()) //If the input mesh has a mask, use it to compute the warped meshes' masks - { - vtkSmartPointer ref_mask = vtkSmartPointer::New(); - ref_mask->ShallowCopy(GetMask(0)); - this->ComputeMasks(ref_mask); + assert(this->GetNumberOfMeshes() == 1); + std::vector sgrids=vf->GetVTKImages(); + vtkSmartPointer reference_mesh = vtkSmartPointer::New(); + reference_mesh->ShallowCopy(this->GetMesh(0)); + this->RemoveMeshes(); + + for (std::vector::iterator i=sgrids.begin(); + i!=sgrids.end(); i++) { + vtkPolyData* new_mesh=vtkPolyData::New(); + new_mesh->DeepCopy(reference_mesh); + double Ox=vf->GetOrigin()[0]; + double Oy=vf->GetOrigin()[1]; + double Oz=vf->GetOrigin()[2]; + double Sx=vf->GetSpacing()[0]; + double Sy=vf->GetSpacing()[1]; + double Sz=vf->GetSpacing()[2]; + int *dims=vf->GetVTKImages()[0]->GetDimensions(); + assert((*i)->GetScalarType() == VTK_FLOAT); //vfs are assumed to be of float type + assert((*i)->GetNumberOfScalarComponents() == 3); + float * vector_data=reinterpret_cast((*i)->GetScalarPointer()); + for (int j=0; jGetNumberOfPoints(); j++) { + double* old=new_mesh->GetPoint(j); + int ix=(old[0]-Ox)/Sx; + int iy=(old[1]-Oy)/Sy; + int iz=(old[2]-Oz)/Sz; + float* vector=vector_data+(ix+iy*vf->GetSize()[0]+iz*vf->GetSize()[0]*vf->GetSize()[1])*3; + if (ix>=0 && ix < dims[0] + && iy>=0 && iy < dims[1] + && iz>=0 && iz < dims[2]) + new_mesh->GetPoints()->SetPoint(j,old[0]+vector[0],old[1]+vector[1],old[2]+vector[2]); } + this->AddMesh(new_mesh); + } + if (GetNumberOfMasks()) { //If the input mesh has a mask, use it to compute the warped meshes' masks + vtkSmartPointer ref_mask = vtkSmartPointer::New(); + ref_mask->ShallowCopy(GetMask(0)); + this->ComputeMasks(ref_mask); + } } diff --git a/vv/vvMeshActor.cxx b/vv/vvMeshActor.cxx index 649b91a..e725871 100644 --- a/vv/vvMeshActor.cxx +++ b/vv/vvMeshActor.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -26,98 +26,94 @@ #include vvMeshActor::vvMeshActor() : - mCutDimension(NULL), mMesh(NULL), - mMarching(NULL), mMapper(NULL), - mActor(NULL), - mSuperpostionMode(false), mTimeSlice(0) + mCutDimension(NULL), mMesh(NULL), + mMarching(NULL), mMapper(NULL), + mActor(NULL), + mSuperpostionMode(false), mTimeSlice(0) {} vvMeshActor::~vvMeshActor() { - mMarching->Delete(); - mMapper->Delete(); - mActor->Delete(); + mMarching->Delete(); + mMapper->Delete(); + mActor->Delete(); } void vvMeshActor::Init(vvMesh::Pointer mesh,int time_slice,vvImage::Pointer vf) { - mMesh=mesh; + mMesh=mesh; - mMarching=vtkMarchingSquares::New(); - mTimeSlice=time_slice; - if (static_cast(time_slice)GetNumberOfMeshes()) - mMarching->SetInput(mMesh->GetMask(time_slice)); - else - mMarching->SetInput(mMesh->GetMask(0)); - mMarching->SetValue(0,0.5); - //mMarching->Update(); + mMarching=vtkMarchingSquares::New(); + mTimeSlice=time_slice; + if (static_cast(time_slice)GetNumberOfMeshes()) + mMarching->SetInput(mMesh->GetMask(time_slice)); + else + mMarching->SetInput(mMesh->GetMask(0)); + mMarching->SetValue(0,0.5); + //mMarching->Update(); - mMapper=vtkPolyDataMapper::New(); - mMapper->SetInput(mMarching->GetOutput()); - //The following line allows to display the contour over the image - //(http://www.nabble.com/What-happens-when-two-actors-are-at-the-same-depth--td23175458.html) - vtkMapper::SetResolveCoincidentTopologyToPolygonOffset(); - mActor=vtkActor::New(); - mActor->SetMapper(mMapper); - mActor->SetPickable(false); - mActor->GetProperty()->EdgeVisibilityOn(); - mActor->GetProperty()->SetEdgeColor(mMesh->r,mMesh->g,mMesh->b); - mActor->GetProperty()->SetLineWidth(2.); + mMapper=vtkPolyDataMapper::New(); + mMapper->SetInput(mMarching->GetOutput()); + //The following line allows to display the contour over the image + //(http://www.nabble.com/What-happens-when-two-actors-are-at-the-same-depth--td23175458.html) + vtkMapper::SetResolveCoincidentTopologyToPolygonOffset(); + mActor=vtkActor::New(); + mActor->SetMapper(mMapper); + mActor->SetPickable(false); + mActor->GetProperty()->EdgeVisibilityOn(); + mActor->GetProperty()->SetEdgeColor(mMesh->r,mMesh->g,mMesh->b); + mActor->GetProperty()->SetLineWidth(2.); } void vvMeshActor::SetCutSlice(double slice) { - mCutSlice=slice; - vtkImageData* mask; - if (static_cast(mTimeSlice)GetNumberOfMasks()) - mask=mMesh->GetMask(mTimeSlice); - else - mask=mMesh->GetMask(0); - int* dims=mask->GetDimensions(); - int mask_slice=(slice-mask->GetOrigin()[mCutDimension])/mask->GetSpacing()[mCutDimension]; - switch (mCutDimension) - { - case 0: - mMarching->SetImageRange(mask_slice,mask_slice,0,dims[1],0,dims[2]); - break; - case 1: - mMarching->SetImageRange(0,dims[0],mask_slice,mask_slice,0,dims[2]); - break; - case 2: - mMarching->SetImageRange(0,dims[0],0,dims[1],mask_slice,mask_slice); - break; - default: - assert(false); - } - mMarching->Update(); + mCutSlice=slice; + vtkImageData* mask; + if (static_cast(mTimeSlice)GetNumberOfMasks()) + mask=mMesh->GetMask(mTimeSlice); + else + mask=mMesh->GetMask(0); + int* dims=mask->GetDimensions(); + int mask_slice=(slice-mask->GetOrigin()[mCutDimension])/mask->GetSpacing()[mCutDimension]; + switch (mCutDimension) { + case 0: + mMarching->SetImageRange(mask_slice,mask_slice,0,dims[1],0,dims[2]); + break; + case 1: + mMarching->SetImageRange(0,dims[0],mask_slice,mask_slice,0,dims[2]); + break; + case 2: + mMarching->SetImageRange(0,dims[0],0,dims[1],mask_slice,mask_slice); + break; + default: + assert(false); + } + mMarching->Update(); } void vvMeshActor::SetTimeSlice(int time) { - mTimeSlice=time; - if (static_cast(time)GetNumberOfMasks()) - mMarching->SetInput(mMesh->GetMask(time)); - else - mMarching->SetInput(mMesh->GetMask(0)); - SetCutSlice(mCutSlice); //We need to find the new mask cut slice, - //since masks do not all have the same origin + mTimeSlice=time; + if (static_cast(time)GetNumberOfMasks()) + mMarching->SetInput(mMesh->GetMask(time)); + else + mMarching->SetInput(mMesh->GetMask(0)); + SetCutSlice(mCutSlice); //We need to find the new mask cut slice, + //since masks do not all have the same origin } void vvMeshActor::SetSlicingOrientation(unsigned int d) { - mCutDimension=d; + mCutDimension=d; } void vvMeshActor::ToggleSuperposition() { - DD("Warning: superposition not implemented"); + DD("Warning: superposition not implemented"); // std::cout << "vvMeshActor::ToggleSuperposition size = " << mMeshes.size() << std::endl; - if (! mSuperpostionMode && mMesh->GetNumberOfMeshes() > 1) - { - mSuperpostionMode=true; - } - else - { - mSuperpostionMode=false; - } + if (! mSuperpostionMode && mMesh->GetNumberOfMeshes() > 1) { + mSuperpostionMode=true; + } else { + mSuperpostionMode=false; + } } diff --git a/vv/vvMeshReader.cxx b/vv/vvMeshReader.cxx index 980e17d..d5100b1 100644 --- a/vv/vvMeshReader.cxx +++ b/vv/vvMeshReader.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -37,160 +37,150 @@ #include "vvProgressDialog.h" vvMeshReader::vvMeshReader() : - vtk_mode(false) + vtk_mode(false) {} void vvMeshReader::Update() { - //Show a progress bar only when opening a DC-struct (ie. multiple contours) - vvProgressDialog progress("Opening " + filename,(!vtk_mode) && (selected_contours.size()>1)); - this->start(); - while (this->isRunning()) - { - progress.SetProgress(result.size(),selected_contours.size()); - this->wait(50); - qApp->processEvents(); - } + //Show a progress bar only when opening a DC-struct (ie. multiple contours) + vvProgressDialog progress("Opening " + filename,(!vtk_mode) && (selected_contours.size()>1)); + this->start(); + while (this->isRunning()) { + progress.SetProgress(result.size(),selected_contours.size()); + this->wait(50); + qApp->processEvents(); + } } void vvMeshReader::run() { - ///Verify the important stuff has been set - assert(filename != ""); - if (vtk_mode) //Read vtkPolyData - { - vvMesh::Pointer m=vvMesh::New(); - m->ReadFromVTK(filename.c_str()); - if (vf) m->propagateContour(vf); - m->ComputeMasks(image->GetVTKImages()[0],true); - result.push_back(m); - } - else //Read a Dicom-struct file - { - assert(selected_contours.size() > 0); - assert(image); - std::vector contour_stacks=readSelectedContours(); - for (std::vector::iterator i=contour_stacks.begin(); - i!=contour_stacks.end();i++) - { - (*i)->ComputeMasks(image->GetVTKImages()[0],true); //Remesh the contour - (*i)->ComputeMeshes(); - if (vf) (*i)->propagateContour(vf); - result.push_back(*i); - } + ///Verify the important stuff has been set + assert(filename != ""); + if (vtk_mode) { //Read vtkPolyData + vvMesh::Pointer m=vvMesh::New(); + m->ReadFromVTK(filename.c_str()); + if (vf) m->propagateContour(vf); + m->ComputeMasks(image->GetVTKImages()[0],true); + result.push_back(m); + } else { //Read a Dicom-struct file + assert(selected_contours.size() > 0); + assert(image); + std::vector contour_stacks=readSelectedContours(); + for (std::vector::iterator i=contour_stacks.begin(); + i!=contour_stacks.end(); i++) { + (*i)->ComputeMasks(image->GetVTKImages()[0],true); //Remesh the contour + (*i)->ComputeMeshes(); + if (vf) (*i)->propagateContour(vf); + result.push_back(*i); } + } } template ElementType parse_value(std::string str) { - std::istringstream parser(str); - ElementType value; - parser >> value; - assert(!parser.fail()); - return value; + std::istringstream parser(str); + ElementType value; + parser >> value; + assert(!parser.fail()); + return value; } template std::vector parse_string(std::string str,char delim) { - std::istringstream ss(str); - std::string token; - std::vector result; - while (getline(ss,token,delim)) - { - result.push_back(parse_value(token)); - } - return result; + std::istringstream ss(str); + std::string token; + std::vector result; + while (getline(ss,token,delim)) { + result.push_back(parse_value(token)); + } + return result; } std::vector > vvMeshReader::GetROINames() { - assert(filename!=""); - gdcm::File reader; - reader.SetFileName(filename.c_str()); - reader.SetMaxSizeLoadEntry(16384); - reader.Load(); - - gdcm::SeqEntry * roi_info=reader.GetSeqEntry(0x3006,0x0020); - assert(roi_info); - std::vector > roi_names; - // DD("ici"); - //int n=0; - for (gdcm::SQItem* i=roi_info->GetFirstSQItem();i!=0;i=roi_info->GetNextSQItem()) - if (i->GetEntryValue(0x3006,0x0022)!= gdcm::GDCM_UNFOUND) - roi_names.push_back(make_pair(atoi(i->GetEntryValue(0x3006,0x0022).c_str()),i->GetEntryValue(0x3006,0x0026))); - return roi_names; + assert(filename!=""); + gdcm::File reader; + reader.SetFileName(filename.c_str()); + reader.SetMaxSizeLoadEntry(16384); + reader.Load(); + + gdcm::SeqEntry * roi_info=reader.GetSeqEntry(0x3006,0x0020); + assert(roi_info); + std::vector > roi_names; + // DD("ici"); + //int n=0; + for (gdcm::SQItem* i=roi_info->GetFirstSQItem(); i!=0; i=roi_info->GetNextSQItem()) + if (i->GetEntryValue(0x3006,0x0022)!= gdcm::GDCM_UNFOUND) + roi_names.push_back(make_pair(atoi(i->GetEntryValue(0x3006,0x0022).c_str()),i->GetEntryValue(0x3006,0x0026))); + return roi_names; } std::vector vvMeshReader::readSelectedContours() { - gdcm::File reader; - reader.SetFileName(filename.c_str()); - reader.SetMaxSizeLoadEntry(16384); - reader.Load(); - - std::vector result; - gdcm::SeqEntry * rois=reader.GetSeqEntry(0x3006,0x0039); - ///We need to iterate both on the contours themselves, and on the contour info - gdcm::SeqEntry * roi_info=reader.GetSeqEntry(0x3006,0x0020); - gdcm::SQItem* k=roi_info->GetFirstSQItem(); - for(gdcm::SQItem* i=rois->GetFirstSQItem();i!=0;i=rois->GetNextSQItem()) //loop over ROIS - { - assert(k!=0); - vtkSmartPointer append=vtkSmartPointer::New(); - std::istringstream ss(i->GetEntryValue(0x3006,0x0084)); - int roi_number;ss >> roi_number; - if (std::find(selected_contours.begin(),selected_contours.end(),roi_number) != selected_contours.end())//Only read selected ROIs - { - vvMesh::Pointer current_roi=vvMesh::New(); - std::vector rgb=parse_string(i->GetEntryValue(0x3006,0x002a),'\\'); - assert(rgb.size()==3); - current_roi->r=rgb[0]/255; current_roi->g=rgb[1]/255; current_roi->b=rgb[2]/255; - current_roi->structure_name=k->GetEntryValue(0x3006,0x0026); - gdcm::SeqEntry * contours=i->GetSeqEntry(0x3006,0x0040); - double z0=-1; //Used to determine spacing between slices, assumed to be constant - for(gdcm::SQItem* j=contours->GetFirstSQItem();j!=0;j=contours->GetNextSQItem()) //loop over 2D contours - { - std::string contour_type=j->GetEntryValue(0x3006,0x0042); - if (contour_type=="CLOSED_PLANAR ") - { - int point_number=parse_value(j->GetEntryValue(0x3006,0x0046)); - std::vector points=parse_string(j->GetEntryValue(0x3006,0x0050),'\\'); - assert(points.size() == static_cast(point_number)*3); - if (z0 == -1) //First contour - z0=points[2]; - //2nd contour, spacing not yet set. Need to be sure we are on a different slice, - //sometimes there is more than one closed contour per slice - else if (current_roi->GetSpacing()==-1 && points[2] != z0 ) - current_roi->SetSpacing(points[2]-z0); - vtkPolyData * contour=vtkPolyData::New(); - contour->Allocate(); //for cell structures - contour->SetPoints(vtkPoints::New()); - vtkIdType ids[2]; - for (unsigned int idx=0;idxGetPoints()->InsertNextPoint(points[idx],points[idx+1],points[idx+2]); - ids[0]=idx/3;ids[1]=(ids[0]+1)%point_number; //0-1,1-2,...,n-1-0 - contour->GetLines()->InsertNextCell(2,ids); - } - append->AddInput(contour); - } - else if (contour_type == "POINT ") - ; // silently ignore POINT type since we don't need them at the moment - else - std::cerr << "Warning: contour type " << contour_type << " not handled!" << std::endl; - } - append->Update(); - current_roi->AddMesh(append->GetOutput()); - result.push_back(current_roi); - } + gdcm::File reader; + reader.SetFileName(filename.c_str()); + reader.SetMaxSizeLoadEntry(16384); + reader.Load(); + + std::vector result; + gdcm::SeqEntry * rois=reader.GetSeqEntry(0x3006,0x0039); + ///We need to iterate both on the contours themselves, and on the contour info + gdcm::SeqEntry * roi_info=reader.GetSeqEntry(0x3006,0x0020); + gdcm::SQItem* k=roi_info->GetFirstSQItem(); + for(gdcm::SQItem* i=rois->GetFirstSQItem(); i!=0; i=rois->GetNextSQItem()) { //loop over ROIS + assert(k!=0); + vtkSmartPointer append=vtkSmartPointer::New(); + std::istringstream ss(i->GetEntryValue(0x3006,0x0084)); + int roi_number; + ss >> roi_number; + if (std::find(selected_contours.begin(),selected_contours.end(),roi_number) != selected_contours.end()) { //Only read selected ROIs + vvMesh::Pointer current_roi=vvMesh::New(); + std::vector rgb=parse_string(i->GetEntryValue(0x3006,0x002a),'\\'); + assert(rgb.size()==3); + current_roi->r=rgb[0]/255; + current_roi->g=rgb[1]/255; + current_roi->b=rgb[2]/255; + current_roi->structure_name=k->GetEntryValue(0x3006,0x0026); + gdcm::SeqEntry * contours=i->GetSeqEntry(0x3006,0x0040); + double z0=-1; //Used to determine spacing between slices, assumed to be constant + for(gdcm::SQItem* j=contours->GetFirstSQItem(); j!=0; j=contours->GetNextSQItem()) { //loop over 2D contours + std::string contour_type=j->GetEntryValue(0x3006,0x0042); + if (contour_type=="CLOSED_PLANAR ") { + int point_number=parse_value(j->GetEntryValue(0x3006,0x0046)); + std::vector points=parse_string(j->GetEntryValue(0x3006,0x0050),'\\'); + assert(points.size() == static_cast(point_number)*3); + if (z0 == -1) //First contour + z0=points[2]; + //2nd contour, spacing not yet set. Need to be sure we are on a different slice, + //sometimes there is more than one closed contour per slice + else if (current_roi->GetSpacing()==-1 && points[2] != z0 ) + current_roi->SetSpacing(points[2]-z0); + vtkPolyData * contour=vtkPolyData::New(); + contour->Allocate(); //for cell structures + contour->SetPoints(vtkPoints::New()); + vtkIdType ids[2]; + for (unsigned int idx=0; idxGetPoints()->InsertNextPoint(points[idx],points[idx+1],points[idx+2]); + ids[0]=idx/3; + ids[1]=(ids[0]+1)%point_number; //0-1,1-2,...,n-1-0 + contour->GetLines()->InsertNextCell(2,ids); + } + append->AddInput(contour); + } else if (contour_type == "POINT ") + ; // silently ignore POINT type since we don't need them at the moment else - { - //std::cerr << "Warning: ignoring ROI #" << roi_number << std::endl; - } - k=roi_info->GetNextSQItem(); //increment the second loop variable + std::cerr << "Warning: contour type " << contour_type << " not handled!" << std::endl; + } + append->Update(); + current_roi->AddMesh(append->GetOutput()); + result.push_back(current_roi); + } else { + //std::cerr << "Warning: ignoring ROI #" << roi_number << std::endl; } - return result; + k=roi_info->GetNextSQItem(); //increment the second loop variable + } + return result; } diff --git a/vv/vvMidPosition.cxx b/vv/vvMidPosition.cxx index 84d2294..7d9f772 100644 --- a/vv/vvMidPosition.cxx +++ b/vv/vvMidPosition.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -27,22 +27,21 @@ #include "clitkInvertVFFilter.h" vvMidPosition::vvMidPosition() : - slicer_manager(0), error(false), - reference_image_index(0), - p_bar("Computing mid-position...","Cancel", 0,6), - progress(0) + slicer_manager(0), error(false), + reference_image_index(0), + p_bar("Computing mid-position...","Cancel", 0,6), + progress(0) { } void vvMidPosition::Update() { - this->start(); - while (this->isRunning()) - { - this->wait(50); - this->update_progress(); - qApp->processEvents(); - } + this->start(); + while (this->isRunning()) { + this->wait(50); + this->update_progress(); + qApp->processEvents(); + } } //Common typedefs @@ -60,141 +59,135 @@ template vvImage::Pointer WarpRefImage(OutputVFType::Point void vvMidPosition::run() { - error=true; - if(slicer_manager->GetImage()->GetNumberOfDimensions() != 4) - error_message="Computation of midposition is only supported for 4D image sequences."; - else if (!slicer_manager->GetVF()) - error_message="A VF is required for midposition computation"; - else if (slicer_manager->GetVF()->GetScalarTypeAsString() != "float") - error_message="Please use a vector field of type float."; - else - { - VFType::ConstPointer vf = vvImageToITK(slicer_manager->GetVF()); - OutputVFType::Pointer avg_vf=AverageField(vf,this->progress); - clitk::InvertVFFilter::Pointer inv_filter= - clitk::InvertVFFilter::New(); - inv_filter->SetInput(avg_vf); - inv_filter->Update(); - progress++; - if (slicer_manager->GetImage()->GetScalarTypeAsString() == "short") - this->output=WarpRefImage(inv_filter->GetOutput(),slicer_manager->GetImage(),reference_image_index); - else - { - error_message="Unsupported image pixel type."; - return; - } - progress++; - error=false; + error=true; + if(slicer_manager->GetImage()->GetNumberOfDimensions() != 4) + error_message="Computation of midposition is only supported for 4D image sequences."; + else if (!slicer_manager->GetVF()) + error_message="A VF is required for midposition computation"; + else if (slicer_manager->GetVF()->GetScalarTypeAsString() != "float") + error_message="Please use a vector field of type float."; + else { + VFType::ConstPointer vf = vvImageToITK(slicer_manager->GetVF()); + OutputVFType::Pointer avg_vf=AverageField(vf,this->progress); + clitk::InvertVFFilter::Pointer inv_filter= + clitk::InvertVFFilter::New(); + inv_filter->SetInput(avg_vf); + inv_filter->Update(); + progress++; + if (slicer_manager->GetImage()->GetScalarTypeAsString() == "short") + this->output=WarpRefImage(inv_filter->GetOutput(),slicer_manager->GetImage(),reference_image_index); + else { + error_message="Unsupported image pixel type."; + return; } + progress++; + error=false; + } } template vvImage::Pointer WarpRefImage(OutputVFType::Pointer vf,vvImage::Pointer image,int reference_image_index) { - typedef itk::Image ImageType; - typedef itk::WarpImageFilter > FilterType; - - typename ImageType::ConstPointer input = vvSingleFrameToITK<3,ImagePixelType>(image,reference_image_index); - - //We resample the VF because itk's warp filter doesn't like it when the vf and the image have - //different spacings - typename itk::VectorResampleImageFilter::Pointer - resampler =itk::VectorResampleImageFilter::New(); - resampler->SetInput(vf); - resampler->SetOutputSpacing(input->GetSpacing()); - resampler->SetOutputOrigin(vf->GetOrigin()); - //Calculate the new size so that it contains the vf - typename ImageType::SizeType newSize; - for (unsigned int i=0 ; i <3; i++) - newSize[i]=(unsigned int) (vf->GetLargestPossibleRegion().GetSize()[i]*vf->GetSpacing()[i]/input->GetSpacing()[i]); - resampler->SetSize( newSize); - - typename FilterType::Pointer warp_filter = FilterType::New(); - warp_filter->SetInput(input); - warp_filter->SetDeformationField(resampler->GetOutput()); - warp_filter->SetOutputSpacing(input->GetSpacing()); - warp_filter->SetOutputOrigin(input->GetOrigin()); - warp_filter->SetOutputSize(input->GetLargestPossibleRegion().GetSize()); - warp_filter->SetEdgePaddingValue(-1000); - warp_filter->Update(); - return vvImageFromITK<3,ImagePixelType>(warp_filter->GetOutput()); + typedef itk::Image ImageType; + typedef itk::WarpImageFilter > FilterType; + + typename ImageType::ConstPointer input = vvSingleFrameToITK<3,ImagePixelType>(image,reference_image_index); + + //We resample the VF because itk's warp filter doesn't like it when the vf and the image have + //different spacings + typename itk::VectorResampleImageFilter::Pointer + resampler =itk::VectorResampleImageFilter::New(); + resampler->SetInput(vf); + resampler->SetOutputSpacing(input->GetSpacing()); + resampler->SetOutputOrigin(vf->GetOrigin()); + //Calculate the new size so that it contains the vf + typename ImageType::SizeType newSize; + for (unsigned int i=0 ; i <3; i++) + newSize[i]=(unsigned int) (vf->GetLargestPossibleRegion().GetSize()[i]*vf->GetSpacing()[i]/input->GetSpacing()[i]); + resampler->SetSize( newSize); + + typename FilterType::Pointer warp_filter = FilterType::New(); + warp_filter->SetInput(input); + warp_filter->SetDeformationField(resampler->GetOutput()); + warp_filter->SetOutputSpacing(input->GetSpacing()); + warp_filter->SetOutputOrigin(input->GetOrigin()); + warp_filter->SetOutputSize(input->GetLargestPossibleRegion().GetSize()); + warp_filter->SetEdgePaddingValue(-1000); + warp_filter->Update(); + return vvImageFromITK<3,ImagePixelType>(warp_filter->GetOutput()); } itk::Image,3>::Pointer AverageField(itk::Image,4>::ConstPointer vf, int& progress) { - progress++; - - VFType::RegionType region4D=vf->GetLargestPossibleRegion(); - VFType::RegionType::SizeType size4D=region4D.GetSize(); - VFType::IndexType index4D=region4D.GetIndex(); - VFType::SpacingType spacing4D=vf->GetSpacing(); - VFType::PointType origin4D=vf->GetOrigin(); - - OutputVFType::RegionType region; - OutputVFType::RegionType::SizeType size; - OutputVFType::IndexType index; - OutputVFType::SpacingType spacing; - OutputVFType::PointType origin; - for (unsigned int i=0; i< 3; i++) - { - size[i]=size4D[i]; - index[i]=index4D[i]; - spacing[i]=spacing4D[i]; - origin[i]=origin4D[i]; + progress++; + + VFType::RegionType region4D=vf->GetLargestPossibleRegion(); + VFType::RegionType::SizeType size4D=region4D.GetSize(); + VFType::IndexType index4D=region4D.GetIndex(); + VFType::SpacingType spacing4D=vf->GetSpacing(); + VFType::PointType origin4D=vf->GetOrigin(); + + OutputVFType::RegionType region; + OutputVFType::RegionType::SizeType size; + OutputVFType::IndexType index; + OutputVFType::SpacingType spacing; + OutputVFType::PointType origin; + for (unsigned int i=0; i< 3; i++) { + size[i]=size4D[i]; + index[i]=index4D[i]; + spacing[i]=spacing4D[i]; + origin[i]=origin4D[i]; + } + region.SetSize(size); + region.SetIndex(index); + OutputVFType::Pointer output= OutputVFType::New(); + output->SetRegions(region); + output->SetSpacing(spacing); + output->SetOrigin(origin); + output->Allocate(); + progress++; + + + // Region iterators + typedef itk::ImageRegionConstIterator IteratorType; + std::vector iterators(size4D[3]); + for (unsigned int i=0; i< size4D[3]; i++) { + VFType::RegionType regionIt=region4D; + VFType::RegionType::SizeType sizeIt=regionIt.GetSize(); + sizeIt[3]=1; + regionIt.SetSize(sizeIt); + VFType::IndexType indexIt=regionIt.GetIndex(); + indexIt[3]=i; + regionIt.SetIndex(indexIt); + iterators[i]=IteratorType(vf, regionIt); + } + progress++; + + typedef itk::ImageRegionIterator OutputIteratorType; + OutputIteratorType avIt(output, output->GetLargestPossibleRegion()); + + // Average + VFPixelType vector; + VFPixelType zeroVector=itk::NumericTraits::Zero; + + while (!(iterators[0]).IsAtEnd()) { + vector=zeroVector; + for (unsigned int i=0; iSetRegions(region); - output->SetSpacing(spacing); - output->SetOrigin(origin); - output->Allocate(); - progress++; - - - // Region iterators - typedef itk::ImageRegionConstIterator IteratorType; - std::vector iterators(size4D[3]); - for (unsigned int i=0; i< size4D[3]; i++) - { - VFType::RegionType regionIt=region4D; - VFType::RegionType::SizeType sizeIt=regionIt.GetSize(); - sizeIt[3]=1; - regionIt.SetSize(sizeIt); - VFType::IndexType indexIt=regionIt.GetIndex(); - indexIt[3]=i; - regionIt.SetIndex(indexIt); - iterators[i]=IteratorType(vf, regionIt); - } - progress++; - - typedef itk::ImageRegionIterator OutputIteratorType; - OutputIteratorType avIt(output, output->GetLargestPossibleRegion()); - - // Average - VFPixelType vector; - VFPixelType zeroVector=itk::NumericTraits::Zero; - - while (!(iterators[0]).IsAtEnd()) - { - vector=zeroVector; - for (unsigned int i=0; ihide(); - compareFrame->hide(); - fusionFrame->hide(); - subSamplingSpinBox->setEnabled(0); - scaleSpinBox->setEnabled(0); - lutCheckBox->hide(); - lutCheckBox->setEnabled(0); - connect(subSamplingSpinBox,SIGNAL(editingFinished()),this,SLOT(setVFProperty())); - connect(scaleSpinBox,SIGNAL(editingFinished()),this,SLOT(setVFProperty())); - connect(lutCheckBox,SIGNAL(clicked()),this,SLOT(setVFProperty())); - connect(vfWidthSpinBox,SIGNAL(editingFinished()),this,SLOT(setVFProperty())); - connect(colorHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(setOverlayProperty())); - connect(opacityHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(setFusionProperty())); - connect(fusionColorMapComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setFusionProperty())); - connect(windowSpinBox,SIGNAL(valueChanged(double)),this,SLOT(setFusionProperty())); - connect(levelSpinBox,SIGNAL(valueChanged(double)),this,SLOT(setFusionProperty())); + setupUi(this); + + vFFrame->hide(); + compareFrame->hide(); + fusionFrame->hide(); + subSamplingSpinBox->setEnabled(0); + scaleSpinBox->setEnabled(0); + lutCheckBox->hide(); + lutCheckBox->setEnabled(0); + connect(subSamplingSpinBox,SIGNAL(editingFinished()),this,SLOT(setVFProperty())); + connect(scaleSpinBox,SIGNAL(editingFinished()),this,SLOT(setVFProperty())); + connect(lutCheckBox,SIGNAL(clicked()),this,SLOT(setVFProperty())); + connect(vfWidthSpinBox,SIGNAL(editingFinished()),this,SLOT(setVFProperty())); + connect(colorHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(setOverlayProperty())); + connect(opacityHorizontalSlider,SIGNAL(valueChanged(int)),this,SLOT(setFusionProperty())); + connect(fusionColorMapComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(setFusionProperty())); + connect(windowSpinBox,SIGNAL(valueChanged(double)),this,SLOT(setFusionProperty())); + connect(levelSpinBox,SIGNAL(valueChanged(double)),this,SLOT(setFusionProperty())); } void vvOverlayPanel::getCurrentImageName(QString name) { - QString filename = "Current image : "; - filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); - currentImageLabel->setText(filename.toStdString().c_str()); + QString filename = "Current image : "; + filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); + currentImageLabel->setText(filename.toStdString().c_str()); } void vvOverlayPanel::getVFProperty(int subsampling, int scale, int log) { - if (subsampling != -1) - { - vFFrame->show(); - vFFrame->setEnabled(1); - subSamplingSpinBox->setEnabled(1); - subSamplingSpinBox->setValue(subsampling); - scaleSpinBox->setEnabled(1); - scaleSpinBox->setValue(scale); - lutCheckBox->setEnabled(1); - if (log > 0) - lutCheckBox->setCheckState(Qt::Checked); - else - lutCheckBox->setCheckState(Qt::Unchecked); - } + if (subsampling != -1) { + vFFrame->show(); + vFFrame->setEnabled(1); + subSamplingSpinBox->setEnabled(1); + subSamplingSpinBox->setValue(subsampling); + scaleSpinBox->setEnabled(1); + scaleSpinBox->setValue(scale); + lutCheckBox->setEnabled(1); + if (log > 0) + lutCheckBox->setCheckState(Qt::Checked); else - { - vFFrame->hide(); - vFFrame->setEnabled(0); - subSamplingSpinBox->setEnabled(0); - subSamplingSpinBox->setValue(0); - scaleSpinBox->setEnabled(0); - scaleSpinBox->setValue(0); - lutCheckBox->setEnabled(0); - lutCheckBox->setCheckState(Qt::Unchecked); - } + lutCheckBox->setCheckState(Qt::Unchecked); + } else { + vFFrame->hide(); + vFFrame->setEnabled(0); + subSamplingSpinBox->setEnabled(0); + subSamplingSpinBox->setValue(0); + scaleSpinBox->setEnabled(0); + scaleSpinBox->setValue(0); + lutCheckBox->setEnabled(0); + lutCheckBox->setCheckState(Qt::Unchecked); + } } void vvOverlayPanel::getVFName(QString name) { - QString filename = "Deformation Field : "; - filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); - vectorFieldNameLabel->setText(filename.toStdString().c_str()); + QString filename = "Deformation Field : "; + filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); + vectorFieldNameLabel->setText(filename.toStdString().c_str()); } void vvOverlayPanel::setVFProperty() { - emit VFPropertyUpdated(subSamplingSpinBox->value(), - scaleSpinBox->value(), - lutCheckBox->checkState(), - vfWidthSpinBox->value()); + emit VFPropertyUpdated(subSamplingSpinBox->value(), + scaleSpinBox->value(), + lutCheckBox->checkState(), + vfWidthSpinBox->value()); } void vvOverlayPanel::getCurrentVectorInfo(int visibility, double x,double y,double z, double value) { - QString motion = "Displacement : "; - QString motionValue = "Length : "; - if (visibility) - { - motion += QString::number(x,'f',1) + " "; - motion += QString::number(y,'f',1) + " "; - motion += QString::number(z,'f',1) + " "; - - motionValue += QString::number(value,'f',1); - } - coordinatesLabel->setText(motion); - normLabel->setText(motionValue); + QString motion = "Displacement : "; + QString motionValue = "Length : "; + if (visibility) { + motion += QString::number(x,'f',1) + " "; + motion += QString::number(y,'f',1) + " "; + motion += QString::number(z,'f',1) + " "; + + motionValue += QString::number(value,'f',1); + } + coordinatesLabel->setText(motion); + normLabel->setText(motionValue); } void vvOverlayPanel::getOverlayName(QString name) { - QString filename = "Compare with : "; - filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); - imageComparedLabel->setText(filename.toStdString().c_str()); + QString filename = "Compare with : "; + filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); + imageComparedLabel->setText(filename.toStdString().c_str()); } void vvOverlayPanel::getOverlayProperty(int value) { - if (value > -1) - { - compareFrame->show(); - compareFrame->setEnabled(1); - colorHorizontalSlider->setEnabled(1); - colorHorizontalSlider->setValue(value); - } - else - { - compareFrame->hide(); - compareFrame->setEnabled(0); - colorHorizontalSlider->setEnabled(0); - colorHorizontalSlider->setValue(0); - } + if (value > -1) { + compareFrame->show(); + compareFrame->setEnabled(1); + colorHorizontalSlider->setEnabled(1); + colorHorizontalSlider->setValue(value); + } else { + compareFrame->hide(); + compareFrame->setEnabled(0); + colorHorizontalSlider->setEnabled(0); + colorHorizontalSlider->setValue(0); + } } void vvOverlayPanel::setOverlayProperty() { - emit OverlayPropertyUpdated(colorHorizontalSlider->value()); + emit OverlayPropertyUpdated(colorHorizontalSlider->value()); } void vvOverlayPanel::getCurrentOverlayInfo(int visibility,double valueOver, double valueRef) { - QString refValue = "Pixel value in image 1 : "; - QString overlayValue = "Pixel value in image 2 : "; - QString diffValue = "Pixel difference : "; - if (visibility) - { - refValue += QString::number(valueRef); - overlayValue += QString::number(valueOver,'f',1); - diffValue += QString::number(valueRef - valueOver,'f',1); - } - refValueLabel->setText(refValue); - valueLabel->setText(overlayValue); - diffValueLabel->setText(diffValue); + QString refValue = "Pixel value in image 1 : "; + QString overlayValue = "Pixel value in image 2 : "; + QString diffValue = "Pixel difference : "; + if (visibility) { + refValue += QString::number(valueRef); + overlayValue += QString::number(valueOver,'f',1); + diffValue += QString::number(valueRef - valueOver,'f',1); + } + refValueLabel->setText(refValue); + valueLabel->setText(overlayValue); + diffValueLabel->setText(diffValue); } void vvOverlayPanel::getFusionName(QString name) { - QString filename = "Fusion with : "; - filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); - dataFusionnedLabel->setText(filename.toStdString().c_str()); + QString filename = "Fusion with : "; + filename += vtksys::SystemTools::GetFilenameWithoutExtension(name.toStdString()).c_str(); + dataFusionnedLabel->setText(filename.toStdString().c_str()); } void vvOverlayPanel::getFusionProperty(int opacity, int colormap, double window, double level) { - if (opacity > -1) - { - fusionFrame->show(); - fusionFrame->setEnabled(1); - opacityHorizontalSlider->setEnabled(1); - opacityHorizontalSlider->setValue(opacity); - fusionColorMapComboBox->setEnabled(1); - fusionColorMapComboBox->setCurrentIndex(colormap); - windowSpinBox->setEnabled(1); - levelSpinBox->setEnabled(1); - windowSpinBox->setValue(window); - levelSpinBox->setValue(level); - } - else - { - fusionFrame->hide(); - fusionFrame->setEnabled(0); - opacityHorizontalSlider->setEnabled(0); - opacityHorizontalSlider->setValue(0); - fusionColorMapComboBox->setEnabled(0); - fusionColorMapComboBox->setCurrentIndex(-1); - windowSpinBox->setEnabled(0); - levelSpinBox->setEnabled(0); - } + if (opacity > -1) { + fusionFrame->show(); + fusionFrame->setEnabled(1); + opacityHorizontalSlider->setEnabled(1); + opacityHorizontalSlider->setValue(opacity); + fusionColorMapComboBox->setEnabled(1); + fusionColorMapComboBox->setCurrentIndex(colormap); + windowSpinBox->setEnabled(1); + levelSpinBox->setEnabled(1); + windowSpinBox->setValue(window); + levelSpinBox->setValue(level); + } else { + fusionFrame->hide(); + fusionFrame->setEnabled(0); + opacityHorizontalSlider->setEnabled(0); + opacityHorizontalSlider->setValue(0); + fusionColorMapComboBox->setEnabled(0); + fusionColorMapComboBox->setCurrentIndex(-1); + windowSpinBox->setEnabled(0); + levelSpinBox->setEnabled(0); + } } void vvOverlayPanel::setFusionProperty() { - emit FusionPropertyUpdated(opacityHorizontalSlider->value(), fusionColorMapComboBox->currentIndex(), - windowSpinBox->value(), levelSpinBox->value()); + emit FusionPropertyUpdated(opacityHorizontalSlider->value(), fusionColorMapComboBox->currentIndex(), + windowSpinBox->value(), levelSpinBox->value()); } void vvOverlayPanel::getCurrentFusionInfo(int visibility,double value) { - QString fusionValue = "Pixel value in image 2 : "; - if (visibility) - { - fusionValue += QString::number(value,'f',1); - } - valueFusionnedLabel->setText(fusionValue); + QString fusionValue = "Pixel value in image 2 : "; + if (visibility) { + fusionValue += QString::number(value,'f',1); + } + valueFusionnedLabel->setText(fusionValue); } #endif /* end #define _vvOverlayPanel_CXX */ diff --git a/vv/vvQDicomSeriesSelector.cxx b/vv/vvQDicomSeriesSelector.cxx index 04e2aac..2102ddb 100644 --- a/vv/vvQDicomSeriesSelector.cxx +++ b/vv/vvQDicomSeriesSelector.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -27,272 +27,282 @@ //==================================================================== vvDicomSeriesSelector::vvDicomSeriesSelector(QWidget* parent) - :QDialog(parent) { - // Set GUI - ui.setupUi(this); - // Correct GUI for splitter ... - // QSplitter * splitter = new QSplitter(this); - // splitter->setOrientation(Qt::Horizontal); - // ui.gridLayout1->addWidget(splitter, 0, 0, 1, 1); - // ui.mFrameLeft->setParent(splitter); - // ui.mFrameRight->setParent(splitter); - // ui.toolBox->setCurrentIndex(0); - - - - ui.mButtonBox->button(QDialogButtonBox::Open)->setEnabled(false); - - connect(ui.mBrowseButton, SIGNAL(released()), - this, SLOT(BrowseButtonRelease())); - connect(ui.mSearchButton, SIGNAL(released()), - this, SLOT(SearchButtonRelease())); - connect(ui.mListWidget, SIGNAL(itemSelectionChanged()), - this, SLOT(itemSelectionChanged())); - connect(ui.mDicomDetailsListWidget, SIGNAL(itemSelectionChanged()), - this, SLOT(itemDetailsSelectionChanged())); - - // Initialization - /* if (config::get_current_path() != QString(0)) - mFoldername = config::get_current_path(); - else*/ - mFoldername = QFileInfo("./").absolutePath(); - - mPreviousPath = mFoldername; - ui.mFolderLineEdit->setText(mFoldername); - // ui.mTableWidget->setRowCount(0); + :QDialog(parent) +{ + // Set GUI + ui.setupUi(this); + // Correct GUI for splitter ... + // QSplitter * splitter = new QSplitter(this); + // splitter->setOrientation(Qt::Horizontal); + // ui.gridLayout1->addWidget(splitter, 0, 0, 1, 1); + // ui.mFrameLeft->setParent(splitter); + // ui.mFrameRight->setParent(splitter); + // ui.toolBox->setCurrentIndex(0); + + + + ui.mButtonBox->button(QDialogButtonBox::Open)->setEnabled(false); + + connect(ui.mBrowseButton, SIGNAL(released()), + this, SLOT(BrowseButtonRelease())); + connect(ui.mSearchButton, SIGNAL(released()), + this, SLOT(SearchButtonRelease())); + connect(ui.mListWidget, SIGNAL(itemSelectionChanged()), + this, SLOT(itemSelectionChanged())); + connect(ui.mDicomDetailsListWidget, SIGNAL(itemSelectionChanged()), + this, SLOT(itemDetailsSelectionChanged())); + + // Initialization + /* if (config::get_current_path() != QString(0)) + mFoldername = config::get_current_path(); + else*/ + mFoldername = QFileInfo("./").absolutePath(); + + mPreviousPath = mFoldername; + ui.mFolderLineEdit->setText(mFoldername); + // ui.mTableWidget->setRowCount(0); } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::show() { - QDialog::show(); - //grabKeyboard(); - // ui.mListWidget->grabKeyboard(); - // ui.mDicomDetailsListWidget->grabKeyboard(); +void vvDicomSeriesSelector::show() +{ + QDialog::show(); + //grabKeyboard(); + // ui.mListWidget->grabKeyboard(); + // ui.mDicomDetailsListWidget->grabKeyboard(); } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::close() { - QDialog::close(); - // ui.mListWidget->releaseKeyboard() - //releaseKeyboard(); +void vvDicomSeriesSelector::close() +{ + QDialog::close(); + // ui.mListWidget->releaseKeyboard() + //releaseKeyboard(); } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::BrowseButtonRelease() { - QFileDialog dialog(this); - dialog.setFileMode(QFileDialog::AnyFile); - dialog.setFilter("DICOM files (*.dcm); All files (*)"); - mFoldername = dialog.getExistingDirectory(this, - "Select a folder to find DICOM image", - mPreviousPath); - ui.mFolderLineEdit->setText(mFoldername); - mPreviousPath = QFileInfo(mFoldername).absolutePath(); - // config::set_current_path(mPreviousPath); +void vvDicomSeriesSelector::BrowseButtonRelease() +{ + QFileDialog dialog(this); + dialog.setFileMode(QFileDialog::AnyFile); + dialog.setFilter("DICOM files (*.dcm); All files (*)"); + mFoldername = dialog.getExistingDirectory(this, + "Select a folder to find DICOM image", + mPreviousPath); + ui.mFolderLineEdit->setText(mFoldername); + mPreviousPath = QFileInfo(mFoldername).absolutePath(); + // config::set_current_path(mPreviousPath); } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::SearchButtonRelease() { - typedef itk::GDCMSeriesFileNames NamesGeneratorType; - NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New(); - nameGenerator->SetUseSeriesDetails(true); - //nameGenerator->SetDirectory(mFoldername.toStdString()); - nameGenerator->SetRecursive(ui.mIsRecursiveCheckBox->checkState() == Qt::Checked); - - //ds gérer recursive moi-meme pour progress ... - nameGenerator->SetInputDirectory(mFoldername.toStdString()); - - // insert in table - typedef std::vector SeriesIdContainer; - const SeriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs(); - - for (unsigned int i=0; i * filenames = new std::vector; - const std::vector & temp = nameGenerator->GetFileNames(seriesUID[i]); - for (unsigned int j=0; jpush_back(temp[j]); - } - mListOfSeriesFilenames[seriesUID[i]] = filenames; - - // store first header - gdcm::File *header = new gdcm::File(); - header->SetFileName((*filenames)[0]); - header->SetMaxSizeLoadEntry(16384); - header->SetLoadMode(gdcm::LD_NOSHADOW);// don't load shadow tags (in order to save memory) - header->Load(); - - - // - DD(header->GetEntryValue(0x0028,0x0030).c_str()); - - //DS TEST DAVID - DD(header->GetXSize()); - DD(header->GetYSize()); - DD(header->GetZSize()); - DD(header->GetXSpacing()); - DD(header->GetYSpacing()); - DD(header->GetZSpacing()); - DD(header->GetXOrigin()); - DD(header->GetYOrigin()); - DD(header->GetZOrigin()); - DD("\n"); - /* - QString size = QString("%1x%2x%3") - .arg(header->GetXSize()) - .arg(header->GetYSize()) - .arg(header->GetZSize()); - QString spacing = QString("%1x%2x%3") - .arg(header->GetXSpacing()) - .arg(header->GetYSpacing()) - .arg(header->GetZSpacing()); - QString origin = QString("%1x%2x%3") - .arg(header->GetXOrigin()) - .arg(header->GetYOrigin()) - .arg(header->GetZOrigin()); - */ - - - mDicomHeader[seriesUID[i]] = header; - - // new item - QListWidgetItem *newItem = new QListWidgetItem; - newItem->setText(seriesUID[i].c_str()); - ui.mListWidget->insertItem(i, newItem); - - //AddSerieToTheTable(i, *filenames); - } +void vvDicomSeriesSelector::SearchButtonRelease() +{ + typedef itk::GDCMSeriesFileNames NamesGeneratorType; + NamesGeneratorType::Pointer nameGenerator = NamesGeneratorType::New(); + nameGenerator->SetUseSeriesDetails(true); + //nameGenerator->SetDirectory(mFoldername.toStdString()); + nameGenerator->SetRecursive(ui.mIsRecursiveCheckBox->checkState() == Qt::Checked); + + //ds gérer recursive moi-meme pour progress ... + nameGenerator->SetInputDirectory(mFoldername.toStdString()); + + // insert in table + typedef std::vector SeriesIdContainer; + const SeriesIdContainer & seriesUID = nameGenerator->GetSeriesUIDs(); + + for (unsigned int i=0; i * filenames = new std::vector; + const std::vector & temp = nameGenerator->GetFileNames(seriesUID[i]); + for (unsigned int j=0; jpush_back(temp[j]); + } + mListOfSeriesFilenames[seriesUID[i]] = filenames; + + // store first header + gdcm::File *header = new gdcm::File(); + header->SetFileName((*filenames)[0]); + header->SetMaxSizeLoadEntry(16384); + header->SetLoadMode(gdcm::LD_NOSHADOW);// don't load shadow tags (in order to save memory) + header->Load(); + + + // + DD(header->GetEntryValue(0x0028,0x0030).c_str()); + + //DS TEST DAVID + DD(header->GetXSize()); + DD(header->GetYSize()); + DD(header->GetZSize()); + DD(header->GetXSpacing()); + DD(header->GetYSpacing()); + DD(header->GetZSpacing()); + DD(header->GetXOrigin()); + DD(header->GetYOrigin()); + DD(header->GetZOrigin()); + DD("\n"); + /* + QString size = QString("%1x%2x%3") + .arg(header->GetXSize()) + .arg(header->GetYSize()) + .arg(header->GetZSize()); + QString spacing = QString("%1x%2x%3") + .arg(header->GetXSpacing()) + .arg(header->GetYSpacing()) + .arg(header->GetZSpacing()); + QString origin = QString("%1x%2x%3") + .arg(header->GetXOrigin()) + .arg(header->GetYOrigin()) + .arg(header->GetZOrigin()); + */ + + + mDicomHeader[seriesUID[i]] = header; + + // new item + QListWidgetItem *newItem = new QListWidgetItem; + newItem->setText(seriesUID[i].c_str()); + ui.mListWidget->insertItem(i, newItem); + + //AddSerieToTheTable(i, *filenames); } + } } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::itemSelectionChanged() { - // mLabelSelected.setText( - mCurrentSerie = ui.mListWidget->selectedItems()[0]->text().toStdString(); - mFilenames = mListOfSeriesFilenames[mCurrentSerie]; - ui.mButtonBox->button(QDialogButtonBox::Open)->setEnabled(true); - - if (mDicomInfo[mCurrentSerie] == "") { - // QString m; - // m = QString("Patient : %1
").arg(mDicomHeader[s]->GetEntryValue(0x0010,0x0010).c_str()); // Patient's name - mDicomInfo[mCurrentSerie] = MakeDicomInfo(mCurrentSerie, mDicomHeader[mCurrentSerie]); - } - ui.mDicomInfoPanel->setText(mDicomInfo[mCurrentSerie]); - - // Detail tab - ui.mDicomDetailsListWidget->clear(); - for (unsigned int i=0; isize(); i++) { - QListWidgetItem * newItem = new QListWidgetItem; - newItem->setText(QFileInfo((*mFilenames)[i].c_str()).fileName()); - ui.mDicomDetailsListWidget->insertItem(i, newItem); - } +void vvDicomSeriesSelector::itemSelectionChanged() +{ + // mLabelSelected.setText( + mCurrentSerie = ui.mListWidget->selectedItems()[0]->text().toStdString(); + mFilenames = mListOfSeriesFilenames[mCurrentSerie]; + ui.mButtonBox->button(QDialogButtonBox::Open)->setEnabled(true); + + if (mDicomInfo[mCurrentSerie] == "") { + // QString m; + // m = QString("Patient : %1
").arg(mDicomHeader[s]->GetEntryValue(0x0010,0x0010).c_str()); // Patient's name + mDicomInfo[mCurrentSerie] = MakeDicomInfo(mCurrentSerie, mDicomHeader[mCurrentSerie]); + } + ui.mDicomInfoPanel->setText(mDicomInfo[mCurrentSerie]); + + // Detail tab + ui.mDicomDetailsListWidget->clear(); + for (unsigned int i=0; isize(); i++) { + QListWidgetItem * newItem = new QListWidgetItem; + newItem->setText(QFileInfo((*mFilenames)[i].c_str()).fileName()); + ui.mDicomDetailsListWidget->insertItem(i, newItem); + } } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::itemDetailsSelectionChanged() { - unsigned int i = ui.mDicomDetailsListWidget->currentRow(); - if (isize()) { - if (mDicomDetails[(*mFilenames)[i]] == "") { - std::ostringstream s; - mDicomHeader[mCurrentSerie]->Print(s); - - QString l; - gdcm::File * header = mDicomHeader[mCurrentSerie]; - gdcm::DocEntry * e = header->GetFirstEntry(); - while (e) { - if (e->GetName() != "gdcm::Unknown") { - l += QString("%1 : %2\n") - .arg(e->GetName().c_str()) - .arg((header->GetEntryValue(e->GetGroup(), e->GetElement())).c_str()); - } - e = header->GetNextEntry(); - } - - mDicomDetails[(*mFilenames)[i]] = l.toStdString(); +void vvDicomSeriesSelector::itemDetailsSelectionChanged() +{ + unsigned int i = ui.mDicomDetailsListWidget->currentRow(); + if (isize()) { + if (mDicomDetails[(*mFilenames)[i]] == "") { + std::ostringstream s; + mDicomHeader[mCurrentSerie]->Print(s); + + QString l; + gdcm::File * header = mDicomHeader[mCurrentSerie]; + gdcm::DocEntry * e = header->GetFirstEntry(); + while (e) { + if (e->GetName() != "gdcm::Unknown") { + l += QString("%1 : %2\n") + .arg(e->GetName().c_str()) + .arg((header->GetEntryValue(e->GetGroup(), e->GetElement())).c_str()); } - ui.mDicomDetailsLabel->setText(mDicomDetails[(*mFilenames)[i]].c_str()); + e = header->GetNextEntry(); + } + + mDicomDetails[(*mFilenames)[i]] = l.toStdString(); } + ui.mDicomDetailsLabel->setText(mDicomDetails[(*mFilenames)[i]].c_str()); + } } //==================================================================== //==================================================================== -QString vvDicomSeriesSelector::MakeDicomInfo(std::string & s, gdcm::File *header) { - QString n = QString("%1").arg(mListOfSeriesFilenames[s]->size()); - QString size = QString("%1x%2x%3") - .arg(header->GetXSize()) - .arg(header->GetYSize()) - .arg(header->GetZSize()); - QString spacing = QString("%1x%2x%3") - .arg(header->GetXSpacing()) - .arg(header->GetYSpacing()) - .arg(header->GetZSpacing()); - QString origin = QString("%1x%2x%3") - .arg(header->GetXOrigin()) - .arg(header->GetYOrigin()) - .arg(header->GetZOrigin()); - QString ss = - //AddInfo( "Serie ID : ", s)+ - AddInfo(header, "Patient : ", 0x0010,0x0010)+ - AddInfo( "Folder : ", QFileInfo((*mFilenames)[0].c_str()).canonicalPath().toStdString())+ - AddInfo(header, "Series Description : ", 0x0008,0x103e)+ - AddInfo(header, "Modality : ", 0x0008,0x0060)+ - AddInfo(header, "# images : ", 0x0020,0x0013)+ - AddInfo( "# files : ", n.toStdString())+ - AddInfo( "Size : ", size.toStdString())+ - AddInfo( "Spacing : ", spacing.toStdString())+ - AddInfo( "Origin : ", origin.toStdString())+ - AddInfo(header, "Pixel size : ", 0x0028,0x0100)+ - AddInfo( "Pixel type : ", header->GetPixelType()); - return ss; +QString vvDicomSeriesSelector::MakeDicomInfo(std::string & s, gdcm::File *header) +{ + QString n = QString("%1").arg(mListOfSeriesFilenames[s]->size()); + QString size = QString("%1x%2x%3") + .arg(header->GetXSize()) + .arg(header->GetYSize()) + .arg(header->GetZSize()); + QString spacing = QString("%1x%2x%3") + .arg(header->GetXSpacing()) + .arg(header->GetYSpacing()) + .arg(header->GetZSpacing()); + QString origin = QString("%1x%2x%3") + .arg(header->GetXOrigin()) + .arg(header->GetYOrigin()) + .arg(header->GetZOrigin()); + QString ss = + //AddInfo( "Serie ID : ", s)+ + AddInfo(header, "Patient : ", 0x0010,0x0010)+ + AddInfo( "Folder : ", QFileInfo((*mFilenames)[0].c_str()).canonicalPath().toStdString())+ + AddInfo(header, "Series Description : ", 0x0008,0x103e)+ + AddInfo(header, "Modality : ", 0x0008,0x0060)+ + AddInfo(header, "# images : ", 0x0020,0x0013)+ + AddInfo( "# files : ", n.toStdString())+ + AddInfo( "Size : ", size.toStdString())+ + AddInfo( "Spacing : ", spacing.toStdString())+ + AddInfo( "Origin : ", origin.toStdString())+ + AddInfo(header, "Pixel size : ", 0x0028,0x0100)+ + AddInfo( "Pixel type : ", header->GetPixelType()); + return ss; } //==================================================================== //==================================================================== -QString vvDicomSeriesSelector::AddInfo(gdcm::File *header, QString n, uint16_t group, uint16_t elem) { - return AddInfo(n.toStdString(), header->GetEntryValue(group, elem)); +QString vvDicomSeriesSelector::AddInfo(gdcm::File *header, QString n, uint16_t group, uint16_t elem) +{ + return AddInfo(n.toStdString(), header->GetEntryValue(group, elem)); } //==================================================================== //==================================================================== -QString vvDicomSeriesSelector::AddInfo(std::string n, std::string m) { - QString s = QString("%1 %2
"). - arg(n.c_str()).arg(m.c_str()); - return s; +QString vvDicomSeriesSelector::AddInfo(std::string n, std::string m) +{ + QString s = QString("%1 %2
"). + arg(n.c_str()).arg(m.c_str()); + return s; } //==================================================================== //==================================================================== -void vvDicomSeriesSelector::AddSerieToTheTable(int i, std::vector & filenames) { - gdcm::File *header = new gdcm::File(); - header->SetFileName(filenames[0]); - header->SetMaxSizeLoadEntry(16384); - header->SetLoadMode(gdcm::LD_NOSHADOW);// don't load shadow tags (in order to save memory) - header->Load(); - //header->Print(cout); - // ->GetValEntry - // mDicomHeader[] = header; - - /* - - QTableWidgetItem *newItem = new - QTableWidgetItem(QString("# images = %1").arg(header->GetImageNumber())); - // newItem->setCheckState(Qt::Checked); - //newItem->setFlags(!Qt::ItemIsEditable); - DD(ui.mTableWidget->rowCount()); - ui.mTableWidget->setItem(i, 0, newItem); - */ +void vvDicomSeriesSelector::AddSerieToTheTable(int i, std::vector & filenames) +{ + gdcm::File *header = new gdcm::File(); + header->SetFileName(filenames[0]); + header->SetMaxSizeLoadEntry(16384); + header->SetLoadMode(gdcm::LD_NOSHADOW);// don't load shadow tags (in order to save memory) + header->Load(); + //header->Print(cout); + // ->GetValEntry + // mDicomHeader[] = header; + + /* + + QTableWidgetItem *newItem = new + QTableWidgetItem(QString("# images = %1").arg(header->GetImageNumber())); + // newItem->setCheckState(Qt::Checked); + //newItem->setFlags(!Qt::ItemIsEditable); + DD(ui.mTableWidget->rowCount()); + ui.mTableWidget->setItem(i, 0, newItem); + */ } //==================================================================== diff --git a/vv/vvQProgressDialogITKCommand.cxx b/vv/vvQProgressDialogITKCommand.cxx index 999a98d..23c0702 100644 --- a/vv/vvQProgressDialogITKCommand.cxx +++ b/vv/vvQProgressDialogITKCommand.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -21,36 +21,40 @@ #include "vvQProgressDialogITKCommand.h" //==================================================================== -vvQProgressDialogITKCommand::vvQProgressDialogITKCommand() { - progress.setWindowModality(Qt::WindowModal); - progress.setCancelButtonText("Cancel"); +vvQProgressDialogITKCommand::vvQProgressDialogITKCommand() +{ + progress.setWindowModality(Qt::WindowModal); + progress.setCancelButtonText("Cancel"); } //==================================================================== //==================================================================== -void vvQProgressDialogITKCommand::Initialize(QString title, float sec, int max) { - progress.setMinimumDuration((int)lrint(1000.0*sec)); // number of seconds to wait before displaying dialog - progress.setLabelText(title); - i=0; - progress.setMaximum(max); +void vvQProgressDialogITKCommand::Initialize(QString title, float sec, int max) +{ + progress.setMinimumDuration((int)lrint(1000.0*sec)); // number of seconds to wait before displaying dialog + progress.setLabelText(title); + i=0; + progress.setMaximum(max); } //==================================================================== //==================================================================== -void vvQProgressDialogITKCommand::Execute(itk::Object *caller, const itk::EventObject & event) { - i++; - progress.setValue(i); - if (progress.wasCanceled()) { - itk::ProcessObject * o = dynamic_cast(caller); - o->SetAbortGenerateData(true); - } +void vvQProgressDialogITKCommand::Execute(itk::Object *caller, const itk::EventObject & event) +{ + i++; + progress.setValue(i); + if (progress.wasCanceled()) { + itk::ProcessObject * o = dynamic_cast(caller); + o->SetAbortGenerateData(true); + } } //==================================================================== //==================================================================== -void vvQProgressDialogITKCommand::Execute(const itk::Object *caller, const itk::EventObject & event) { - i++; - progress.setValue(i); +void vvQProgressDialogITKCommand::Execute(const itk::Object *caller, const itk::EventObject & event) +{ + i++; + progress.setValue(i); } //==================================================================== diff --git a/vv/vvROIActor.cxx b/vv/vvROIActor.cxx index 1b3585d..abf3eb6 100644 --- a/vv/vvROIActor.cxx +++ b/vv/vvROIActor.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,7 +31,8 @@ #include //------------------------------------------------------------------------------ -vvROIActor::vvROIActor() { +vvROIActor::vvROIActor() +{ mImageContour.clear(); mOverlayActors.clear(); mIsVisible = true; @@ -42,34 +43,37 @@ vvROIActor::vvROIActor() { //------------------------------------------------------------------------------ -vvROIActor::~vvROIActor() { +vvROIActor::~vvROIActor() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::SetROI(clitk::DicomRT_ROI * s) { +void vvROIActor::SetROI(clitk::DicomRT_ROI * s) +{ mROI = s; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::SetSlicerManager(vvSlicerManager * s) { +void vvROIActor::SetSlicerManager(vvSlicerManager * s) +{ mSlicerManager = s; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::SetVisible(bool b) { +void vvROIActor::SetVisible(bool b) +{ mIsVisible = b; if (!b) { // remove actor - for(unsigned int i= 0; iHideActors(); - } - else { - for(unsigned int i= 0; iShowActors(); } Update(); @@ -78,38 +82,40 @@ void vvROIActor::SetVisible(bool b) { //------------------------------------------------------------------------------ -bool vvROIActor::IsVisible() { +bool vvROIActor::IsVisible() +{ return mIsVisible; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::Initialize() { +void vvROIActor::Initialize() +{ if (mROI->GetImage()) { mImageContour.clear(); mOverlayActors.clear(); - for(int i=0;iNumberOfSlicers(); i++) { + for(int i=0; iNumberOfSlicers(); i++) { mImageContour.push_back(new vvImageContour); mImageContour[i]->setSlicer(mSlicerManager->GetSlicer(i)); mImageContour[i]->setImage(mROI->GetImage()); //mImageContour[i]->setColor(1.0, 0.0, 0.0); - mImageContour[i]->setColor(1.0-mROI->GetDisplayColor()[0], - 1.0-mROI->GetDisplayColor()[1], - 1.0-mROI->GetDisplayColor()[2]); + mImageContour[i]->setColor(1.0-mROI->GetDisplayColor()[0], + 1.0-mROI->GetDisplayColor()[1], + 1.0-mROI->GetDisplayColor()[2]); mImageContour[i]->setPreserveMemoryModeEnabled(true); mImageContour[i]->setSlicer(mSlicerManager->GetSlicer(i)); - + mOverlayActors.push_back(new vvBinaryImageOverlayActor); mOverlayActors[i]->SetImage(mROI->GetImage(), mROI->GetBackgroundValueLabelImage()); - mOverlayActors[i]->SetColor(mROI->GetDisplayColor()[0], - mROI->GetDisplayColor()[1], - mROI->GetDisplayColor()[2]); + mOverlayActors[i]->SetColor(mROI->GetDisplayColor()[0], + mROI->GetDisplayColor()[1], + mROI->GetDisplayColor()[2]); mOverlayActors[i]->SetOpacity(mOpacity); mOverlayActors[i]->SetSlicer(mSlicerManager->GetSlicer(i)); mOverlayActors[i]->Initialize(); } - + connect(mSlicerManager,SIGNAL(UpdateSlice(int,int)),this,SLOT(UpdateSlice(int, int))); //connect(mSlicerManager,SIGNAL(UpdateTSlice(int,int)),this,SLOT(UpdateSlice(int, int))); connect(mSlicerManager, SIGNAL(AVerticalSliderHasChanged(int, int)), SLOT(UpdateSlice(int, int))); @@ -119,7 +125,8 @@ void vvROIActor::Initialize() { //------------------------------------------------------------------------------ -void vvROIActor::Update() { +void vvROIActor::Update() +{ for(int i=0; iNumberOfSlicers(); i++) { UpdateSlice(i, mSlicerManager->GetSlicer(i)->GetSlice()); } @@ -128,9 +135,10 @@ void vvROIActor::Update() { //------------------------------------------------------------------------------ -void vvROIActor::UpdateSlice(int slicer, int slices) { +void vvROIActor::UpdateSlice(int slicer, int slices) +{ if (!mROI->GetImage()) return; - + if (!mIsVisible) return; if (!mSlicerManager) { @@ -138,13 +146,13 @@ void vvROIActor::UpdateSlice(int slicer, int slices) { exit(0); } - // CONTOUR HERE + // CONTOUR HERE DD("vvROIActor::UpdateSlice"); DD(mROI->GetName()); DD(mIsSelected); DD(mROI->GetBackgroundValueLabelImage()); if (mIsSelected) { - mImageContour[slicer]->update(1.0);//mROI->GetBackgroundValueLabelImage()); + mImageContour[slicer]->update(1.0);//mROI->GetBackgroundValueLabelImage()); // mImageContour[slicer]->showActors(); } @@ -152,7 +160,7 @@ void vvROIActor::UpdateSlice(int slicer, int slices) { mOverlayActors[slicer]->UpdateSlice(slicer, slices); // Do not used the following line : TOO SLOW. - // mSlicerManager->GetSlicer(slicer)->GetRenderWindow()->Render(); + // mSlicerManager->GetSlicer(slicer)->GetRenderWindow()->Render(); } //------------------------------------------------------------------------------ @@ -160,30 +168,32 @@ void vvROIActor::UpdateSlice(int slicer, int slices) { //------------------------------------------------------------------------------ // void vvROIActor::UpdateOpacity(double d) { // if (d == mOpacity) return; -// mOpacity = d; +// mOpacity = d; // for(unsigned int i=0; iSetOpacity(d); // mOverlayActors[i]->UpdateColor(); // } -// mSlicerManager->Render(); +// mSlicerManager->Render(); // } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::SetOpacity(double d) { - mOpacity = d; +void vvROIActor::SetOpacity(double d) +{ + mOpacity = d; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::UpdateColor() { +void vvROIActor::UpdateColor() +{ for(unsigned int i=0; iSetOpacity(mOpacity); - mOverlayActors[i]->SetColor(mROI->GetDisplayColor()[0], - mROI->GetDisplayColor()[1], - mROI->GetDisplayColor()[2]); + mOverlayActors[i]->SetColor(mROI->GetDisplayColor()[0], + mROI->GetDisplayColor()[1], + mROI->GetDisplayColor()[2]); mOverlayActors[i]->UpdateColor(); } } @@ -191,26 +201,27 @@ void vvROIActor::UpdateColor() { //------------------------------------------------------------------------------ -double vvROIActor::GetOpacity() { +double vvROIActor::GetOpacity() +{ return mOpacity; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvROIActor::SetSelected(bool b) { +void vvROIActor::SetSelected(bool b) +{ mIsSelected = b; if (b) { for(int i=0; iNumberOfSlicers(); i++) { mImageContour[i]->SetLineWidth(3.0); mImageContour[i]->showActors(); } - } - else { + } else { for(int i=0; iNumberOfSlicers(); i++) { mImageContour[i]->hideActors(); } - } + } } //------------------------------------------------------------------------------ diff --git a/vv/vvSegmentationDialog.cxx b/vv/vvSegmentationDialog.cxx index 0fc59ea..915a281 100644 --- a/vv/vvSegmentationDialog.cxx +++ b/vv/vvSegmentationDialog.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -59,71 +59,72 @@ //==================================================================== vvSegmentationDialog::vvSegmentationDialog(QWidget * parent, Qt::WindowFlags f) - :QDialog(parent,f), Ui::vvSegmentationDialog() { - - // initialization - setupUi(this); - mManager = new vvSlicerManager(1); - - mClipper = vtkImageClip::New(); - mSquares1 = vtkMarchingSquares::New(); - mSquaresMapper1 = vtkPolyDataMapper::New(); - mSquaresActor1 = vtkActor::New(); - - mSquares2 = vtkMarchingSquares::New(); - mSquaresMapper2 = vtkPolyDataMapper::New(); - mSquaresActor2 = vtkActor::New(); - - //m3DMapper = vtkPolyDataMapper::New(); - //m3DActor = vtkActor::New(); - m3DExtractor = vtkMarchingCubes::New(); - m3DMappers.clear(); - m3DActors.clear(); - - mBinaireImages.clear(); - mKernelValue = 2; - - connect(clipping1Slider,SIGNAL(valueChanged(int)),this,SLOT(clippingvaluechanged(int))); - connect(clipping2Slider,SIGNAL(valueChanged(int)),this,SLOT(clippingvaluechanged(int))); - connect(binaryButton,SIGNAL(clicked()),this,SLOT(BinariseSurface())); - connect(saveButton,SIGNAL(clicked()),this,SLOT(Save())); - connect(erodeButton,SIGNAL(clicked()),this,SLOT(Erode())); - connect(dilateButton,SIGNAL(clicked()),this,SLOT(Dilate())); - connect(dimButton,SIGNAL(clicked()),this,SLOT(ChangeDimRendering())); - connect(kernelSpinBox,SIGNAL(valueChanged(int)),this,SLOT(KernelValueChanged(int))); - - binaryButton->setEnabled(0); - erodeButton->setEnabled(0); - dilateButton->setEnabled(0); - infoLabel->setText("Select Up and Down threshold before clicking binarise !"); + :QDialog(parent,f), Ui::vvSegmentationDialog() +{ + + // initialization + setupUi(this); + mManager = new vvSlicerManager(1); + + mClipper = vtkImageClip::New(); + mSquares1 = vtkMarchingSquares::New(); + mSquaresMapper1 = vtkPolyDataMapper::New(); + mSquaresActor1 = vtkActor::New(); + + mSquares2 = vtkMarchingSquares::New(); + mSquaresMapper2 = vtkPolyDataMapper::New(); + mSquaresActor2 = vtkActor::New(); + + //m3DMapper = vtkPolyDataMapper::New(); + //m3DActor = vtkActor::New(); + m3DExtractor = vtkMarchingCubes::New(); + m3DMappers.clear(); + m3DActors.clear(); + + mBinaireImages.clear(); + mKernelValue = 2; + + connect(clipping1Slider,SIGNAL(valueChanged(int)),this,SLOT(clippingvaluechanged(int))); + connect(clipping2Slider,SIGNAL(valueChanged(int)),this,SLOT(clippingvaluechanged(int))); + connect(binaryButton,SIGNAL(clicked()),this,SLOT(BinariseSurface())); + connect(saveButton,SIGNAL(clicked()),this,SLOT(Save())); + connect(erodeButton,SIGNAL(clicked()),this,SLOT(Erode())); + connect(dilateButton,SIGNAL(clicked()),this,SLOT(Dilate())); + connect(dimButton,SIGNAL(clicked()),this,SLOT(ChangeDimRendering())); + connect(kernelSpinBox,SIGNAL(valueChanged(int)),this,SLOT(KernelValueChanged(int))); + + binaryButton->setEnabled(0); + erodeButton->setEnabled(0); + dilateButton->setEnabled(0); + infoLabel->setText("Select Up and Down threshold before clicking binarise !"); } vvSegmentationDialog::~vvSegmentationDialog() { - mClipper->Delete(); + mClipper->Delete(); - mSquaresActor1->Delete(); - mSquaresMapper1->Delete(); - mSquares1->Delete(); + mSquaresActor1->Delete(); + mSquaresMapper1->Delete(); + mSquares1->Delete(); - mSquaresActor2->Delete(); - mSquaresMapper2->Delete(); - mSquares2->Delete(); + mSquaresActor2->Delete(); + mSquaresMapper2->Delete(); + mSquares2->Delete(); - //m3DMapper->Delete(); - //m3DActor->Delete(); - m3DExtractor->Delete(); + //m3DMapper->Delete(); + //m3DActor->Delete(); + m3DExtractor->Delete(); - for (unsigned int i = 0; i < mBinaireImages.size(); i++) - mBinaireImages[i]->Delete(); + for (unsigned int i = 0; i < mBinaireImages.size(); i++) + mBinaireImages[i]->Delete(); - for (unsigned int i = 0; i < m3DActors.size(); i++) - m3DActors[i]->Delete(); + for (unsigned int i = 0; i < m3DActors.size(); i++) + m3DActors[i]->Delete(); - for (unsigned int i = 0; i < m3DMappers.size(); i++) - m3DMappers[i]->Delete(); + for (unsigned int i = 0; i < m3DMappers.size(); i++) + m3DMappers[i]->Delete(); - delete mManager; + delete mManager; } //---------------------------------------------------------------------------- @@ -133,483 +134,439 @@ template void vvImageBinarize(vtkImageData *in1Data, T *in1Ptr, int outExt[6],int clampMin, int clampMax) { - int idxR, idxY, idxZ; - int maxY, maxZ; - vtkIdType inIncX, inIncY, inIncZ; - int rowLength; - - // find the region to loop over - rowLength = - (outExt[1] - outExt[0]+1)*in1Data->GetNumberOfScalarComponents(); - // What a pain. Maybe I should just make another filter. - - maxY = outExt[3] - outExt[2]; - maxZ = outExt[5] - outExt[4]; - - // Get increments to march through data - in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); - - for (idxZ = 0; idxZ <= maxZ; idxZ++) - { - for (idxY = 0; idxY <= maxY; idxY++) - { - for (idxR = 0; idxR < rowLength; idxR++) - { - if (static_cast(*in1Ptr) > clampMin && static_cast(*in1Ptr) <= clampMax) - *in1Ptr = static_cast(1); - else - *in1Ptr = static_cast(0); - in1Ptr++; - } - in1Ptr += inIncY; - } - in1Ptr += inIncZ; + int idxR, idxY, idxZ; + int maxY, maxZ; + vtkIdType inIncX, inIncY, inIncZ; + int rowLength; + + // find the region to loop over + rowLength = + (outExt[1] - outExt[0]+1)*in1Data->GetNumberOfScalarComponents(); + // What a pain. Maybe I should just make another filter. + + maxY = outExt[3] - outExt[2]; + maxZ = outExt[5] - outExt[4]; + + // Get increments to march through data + in1Data->GetContinuousIncrements(outExt, inIncX, inIncY, inIncZ); + + for (idxZ = 0; idxZ <= maxZ; idxZ++) { + for (idxY = 0; idxY <= maxY; idxY++) { + for (idxR = 0; idxR < rowLength; idxR++) { + if (static_cast(*in1Ptr) > clampMin && static_cast(*in1Ptr) <= clampMax) + *in1Ptr = static_cast(1); + else + *in1Ptr = static_cast(0); + in1Ptr++; + } + in1Ptr += inIncY; } + in1Ptr += inIncZ; + } } void vvSegmentationDialog::SetImage(vvImage::Pointer image) { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - mManager->SetImage(image); - mManager->SetSlicerWindow(0,viewWidget->GetRenderWindow()); - vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New(); - mManager->SetInteractorStyleNavigator(0,style); - style->Delete(); - - double range[2]; - mManager->GetImage()->GetScalarRange(range); - mManager->GetSlicer(0)->SetColorWindow(range[1]-range[0]); - mManager->GetSlicer(0)->SetColorLevel((range[1]+range[0])/2); - - clipping1Slider->setMinimum(range[0]); - clipping1Slider->setMaximum(range[1]); - clipping2Slider->setMinimum(range[0]); - clipping2Slider->setMaximum(range[1]); - clipping1Slider->setValue(range[0]); - clipping2Slider->setValue(range[1]); - - mClipper->SetInput(mManager->GetSlicer(0)->GetInput()); - mSquares1->SetValue(0,clipping1Slider->value()); - mSquares2->SetValue(0,clipping2Slider->value()); - mSquares1->SetInput(mClipper->GetOutput()); - mSquares2->SetInput(mClipper->GetOutput()); - - mSquaresMapper1->SetInput(mSquares1->GetOutput()); - mSquaresMapper2->SetInput(mSquares2->GetOutput()); - mSquaresMapper1->ScalarVisibilityOff(); - mSquaresMapper2->ScalarVisibilityOff(); - - mSquaresActor1->SetMapper(mSquaresMapper1); - mSquaresActor2->SetMapper(mSquaresMapper2); - mSquaresActor1->GetProperty()->SetColor(1.0,0,0); - mSquaresActor2->GetProperty()->SetColor(0,0,1.0); - mSquaresActor1->SetPickable(0); - mSquaresActor2->SetPickable(0); - - mManager->GetSlicer(0)->GetRenderer()->AddActor(mSquaresActor1); - mManager->GetSlicer(0)->GetRenderer()->AddActor(mSquaresActor2); - - mSquares1->Update(); - mSquares2->Update(); - - UpdateSlice(0,mManager->GetSlicer(0)->GetSlice()); - - connect(mManager,SIGNAL(UpdateTSlice(int,int)),this,SLOT(UpdateSlice(int, int))); - connect(mManager,SIGNAL(UpdateSlice(int,int)),this,SLOT(UpdateSlice(int, int))); - connect(mManager,SIGNAL(UpdateSliceRange(int,int,int,int,int)),this,SLOT(UpdateSlice(int, int))); - connect(mManager,SIGNAL(LandmarkAdded()),this,SLOT(InsertSeed())); - QApplication::restoreOverrideCursor(); + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + mManager->SetImage(image); + mManager->SetSlicerWindow(0,viewWidget->GetRenderWindow()); + vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New(); + mManager->SetInteractorStyleNavigator(0,style); + style->Delete(); + + double range[2]; + mManager->GetImage()->GetScalarRange(range); + mManager->GetSlicer(0)->SetColorWindow(range[1]-range[0]); + mManager->GetSlicer(0)->SetColorLevel((range[1]+range[0])/2); + + clipping1Slider->setMinimum(range[0]); + clipping1Slider->setMaximum(range[1]); + clipping2Slider->setMinimum(range[0]); + clipping2Slider->setMaximum(range[1]); + clipping1Slider->setValue(range[0]); + clipping2Slider->setValue(range[1]); + + mClipper->SetInput(mManager->GetSlicer(0)->GetInput()); + mSquares1->SetValue(0,clipping1Slider->value()); + mSquares2->SetValue(0,clipping2Slider->value()); + mSquares1->SetInput(mClipper->GetOutput()); + mSquares2->SetInput(mClipper->GetOutput()); + + mSquaresMapper1->SetInput(mSquares1->GetOutput()); + mSquaresMapper2->SetInput(mSquares2->GetOutput()); + mSquaresMapper1->ScalarVisibilityOff(); + mSquaresMapper2->ScalarVisibilityOff(); + + mSquaresActor1->SetMapper(mSquaresMapper1); + mSquaresActor2->SetMapper(mSquaresMapper2); + mSquaresActor1->GetProperty()->SetColor(1.0,0,0); + mSquaresActor2->GetProperty()->SetColor(0,0,1.0); + mSquaresActor1->SetPickable(0); + mSquaresActor2->SetPickable(0); + + mManager->GetSlicer(0)->GetRenderer()->AddActor(mSquaresActor1); + mManager->GetSlicer(0)->GetRenderer()->AddActor(mSquaresActor2); + + mSquares1->Update(); + mSquares2->Update(); + + UpdateSlice(0,mManager->GetSlicer(0)->GetSlice()); + + connect(mManager,SIGNAL(UpdateTSlice(int,int)),this,SLOT(UpdateSlice(int, int))); + connect(mManager,SIGNAL(UpdateSlice(int,int)),this,SLOT(UpdateSlice(int, int))); + connect(mManager,SIGNAL(UpdateSliceRange(int,int,int,int,int)),this,SLOT(UpdateSlice(int, int))); + connect(mManager,SIGNAL(LandmarkAdded()),this,SLOT(InsertSeed())); + QApplication::restoreOverrideCursor(); } void vvSegmentationDialog::UpdateSlice(int slicer,int slices) { - int slice = mManager->GetSlicer(0)->GetSlice(); - int tslice = mManager->GetSlicer(0)->GetTSlice(); - mClipper->SetInput(mManager->GetSlicer(0)->GetInput()); - int* extent = mManager->GetSlicer(0)->GetImageActor()->GetDisplayExtent(); - mClipper->SetOutputWholeExtent(extent[0],extent[1],extent[2],extent[3],extent[4],extent[5]); - int i; - for (i = 0; i < 6;i = i+2) - { - if (extent[i] == extent[i+1]) - { - break; - } + int slice = mManager->GetSlicer(0)->GetSlice(); + int tslice = mManager->GetSlicer(0)->GetTSlice(); + mClipper->SetInput(mManager->GetSlicer(0)->GetInput()); + int* extent = mManager->GetSlicer(0)->GetImageActor()->GetDisplayExtent(); + mClipper->SetOutputWholeExtent(extent[0],extent[1],extent[2],extent[3],extent[4],extent[5]); + int i; + for (i = 0; i < 6; i = i+2) { + if (extent[i] == extent[i+1]) { + break; } - - switch (i) - { - case 0: - if (mManager->GetSlicer(0)->GetRenderer()->GetActiveCamera()->GetPosition()[0] > slice) - { - mSquaresActor1->SetPosition(1,0,0); - mSquaresActor2->SetPosition(1,0,0); - } - else - { - mSquaresActor1->SetPosition(-1,0,0); - mSquaresActor2->SetPosition(-1,0,0); - } - break; - case 2: - if (mManager->GetSlicer(0)->GetRenderer()->GetActiveCamera()->GetPosition()[1] > slice) - { - mSquaresActor1->SetPosition(0,1,0); - mSquaresActor2->SetPosition(0,1,0); - } - else - { - mSquaresActor1->SetPosition(0,-1,0); - mSquaresActor2->SetPosition(0,-1,0); - } - break; - case 4: - if (mManager->GetSlicer(0)->GetRenderer()->GetActiveCamera()->GetPosition()[2] > slice) - { - mSquaresActor1->SetPosition(0,0,1); - mSquaresActor2->SetPosition(0,0,1); - } - else - { - mSquaresActor1->SetPosition(0,0,-1); - mSquaresActor2->SetPosition(0,0,-1); - } - break; + } + + switch (i) { + case 0: + if (mManager->GetSlicer(0)->GetRenderer()->GetActiveCamera()->GetPosition()[0] > slice) { + mSquaresActor1->SetPosition(1,0,0); + mSquaresActor2->SetPosition(1,0,0); + } else { + mSquaresActor1->SetPosition(-1,0,0); + mSquaresActor2->SetPosition(-1,0,0); } - mSquares1->Update(); - mSquares2->Update(); - - if (m3DActors.size()) - { - for (unsigned int i =0; i < m3DActors.size(); i++) - { - if (m3DActors[i]->GetVisibility()) - { - m3DActors[i]->VisibilityOff(); - } - } - std::cout << "display " << tslice << " on " << m3DActors.size() << std::endl; - m3DActors[tslice]->VisibilityOn(); + break; + case 2: + if (mManager->GetSlicer(0)->GetRenderer()->GetActiveCamera()->GetPosition()[1] > slice) { + mSquaresActor1->SetPosition(0,1,0); + mSquaresActor2->SetPosition(0,1,0); + } else { + mSquaresActor1->SetPosition(0,-1,0); + mSquaresActor2->SetPosition(0,-1,0); + } + break; + case 4: + if (mManager->GetSlicer(0)->GetRenderer()->GetActiveCamera()->GetPosition()[2] > slice) { + mSquaresActor1->SetPosition(0,0,1); + mSquaresActor2->SetPosition(0,0,1); + } else { + mSquaresActor1->SetPosition(0,0,-1); + mSquaresActor2->SetPosition(0,0,-1); } + break; + } + mSquares1->Update(); + mSquares2->Update(); + + if (m3DActors.size()) { + for (unsigned int i =0; i < m3DActors.size(); i++) { + if (m3DActors[i]->GetVisibility()) { + m3DActors[i]->VisibilityOff(); + } + } + std::cout << "display " << tslice << " on " << m3DActors.size() << std::endl; + m3DActors[tslice]->VisibilityOn(); + } - mManager->Render(); + mManager->Render(); } void vvSegmentationDialog::clippingvaluechanged(int value) { - binaryButton->setEnabled(1); - int min = (clipping1Slider->value() < clipping2Slider->value() ) ? - clipping1Slider->value():clipping2Slider->value(); - int max = (clipping1Slider->value() > clipping2Slider->value() ) ? - clipping1Slider->value():clipping2Slider->value(); - mSquares1->SetValue(0,min); - mSquares2->SetValue(0,max); - - QString textMin = " Min : "; - textMin += QString::number(min); - QString textMax = "\n Max : "; - textMax += QString::number(max); - minLabel->setText(textMin); - maxLabel->setText(textMax); - - if (mSquares1->GetInput()) - { - mSquares1->Update(); - mSquares2->Update(); - mManager->Render(); - } + binaryButton->setEnabled(1); + int min = (clipping1Slider->value() < clipping2Slider->value() ) ? + clipping1Slider->value():clipping2Slider->value(); + int max = (clipping1Slider->value() > clipping2Slider->value() ) ? + clipping1Slider->value():clipping2Slider->value(); + mSquares1->SetValue(0,min); + mSquares2->SetValue(0,max); + + QString textMin = " Min : "; + textMin += QString::number(min); + QString textMax = "\n Max : "; + textMax += QString::number(max); + minLabel->setText(textMin); + maxLabel->setText(textMax); + + if (mSquares1->GetInput()) { + mSquares1->Update(); + mSquares2->Update(); + mManager->Render(); + } } void vvSegmentationDialog::BinariseSurface() { - infoLabel->setText("Click erode then space on desired organ !"); - - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - int clampMin = (clipping1Slider->value() < clipping2Slider->value() ) ? - clipping1Slider->value():clipping2Slider->value(); - int clampMax = (clipping1Slider->value() > clipping2Slider->value() ) ? - clipping1Slider->value():clipping2Slider->value(); - vtkImageData* outputImage = vtkImageData::New(); - - for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) - { - vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; - int ext[6]; - image->GetWholeExtent(ext); - void *in1Ptr; - in1Ptr = image->GetScalarPointerForExtent(ext); - - switch (image->GetScalarType()) - { - vtkTemplateMacro( - vvImageBinarize(image, static_cast(in1Ptr), - ext,clampMin,clampMax)); - default: - std::cerr << "Error, unknown pixel format : " << image->GetScalarTypeAsString() << std::endl; - return; - } - - outputImage->Initialize(); - outputImage->SetExtent(ext); - outputImage->SetOrigin(image->GetOrigin()); - outputImage->SetSpacing(image->GetSpacing()); - outputImage->SetScalarTypeToUnsignedChar(); - outputImage->CopyAndCastFrom(image,ext); - outputImage->Update(); - - image->DeepCopy(outputImage); - image->UpdateInformation(); - image->PropagateUpdateExtent(); - - vtkImageData* imageBin = vtkImageData::New(); - imageBin->DeepCopy(image); - imageBin->Update(); - mBinaireImages.push_back(imageBin); + infoLabel->setText("Click erode then space on desired organ !"); + + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + int clampMin = (clipping1Slider->value() < clipping2Slider->value() ) ? + clipping1Slider->value():clipping2Slider->value(); + int clampMax = (clipping1Slider->value() > clipping2Slider->value() ) ? + clipping1Slider->value():clipping2Slider->value(); + vtkImageData* outputImage = vtkImageData::New(); + + for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) { + vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; + int ext[6]; + image->GetWholeExtent(ext); + void *in1Ptr; + in1Ptr = image->GetScalarPointerForExtent(ext); + + switch (image->GetScalarType()) { + vtkTemplateMacro( + vvImageBinarize(image, static_cast(in1Ptr), + ext,clampMin,clampMax)); + default: + std::cerr << "Error, unknown pixel format : " << image->GetScalarTypeAsString() << std::endl; + return; } - outputImage->Delete(); - erodeButton->setEnabled(1); - QApplication::restoreOverrideCursor(); - mManager->SetColorWindow(2); - mManager->SetColorLevel(0.5); - mManager->Render(); + outputImage->Initialize(); + outputImage->SetExtent(ext); + outputImage->SetOrigin(image->GetOrigin()); + outputImage->SetSpacing(image->GetSpacing()); + outputImage->SetScalarTypeToUnsignedChar(); + outputImage->CopyAndCastFrom(image,ext); + outputImage->Update(); + + image->DeepCopy(outputImage); + image->UpdateInformation(); + image->PropagateUpdateExtent(); + + vtkImageData* imageBin = vtkImageData::New(); + imageBin->DeepCopy(image); + imageBin->Update(); + mBinaireImages.push_back(imageBin); + } + + outputImage->Delete(); + erodeButton->setEnabled(1); + QApplication::restoreOverrideCursor(); + mManager->SetColorWindow(2); + mManager->SetColorLevel(0.5); + mManager->Render(); } void vvSegmentationDialog::Erode() { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - vtkImageContinuousErode3D* erode = vtkImageContinuousErode3D::New(); - erode->SetKernelSize(mKernelValue,mKernelValue,mKernelValue); - for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) - { - vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; - erode->SetInput(image); - erode->Update(); - image->DeepCopy(erode->GetOutput()); - image->Update(); - } - erode->Delete(); - dilateButton->setEnabled(1); - mManager->Render(); - QApplication::restoreOverrideCursor(); + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + vtkImageContinuousErode3D* erode = vtkImageContinuousErode3D::New(); + erode->SetKernelSize(mKernelValue,mKernelValue,mKernelValue); + for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) { + vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; + erode->SetInput(image); + erode->Update(); + image->DeepCopy(erode->GetOutput()); + image->Update(); + } + erode->Delete(); + dilateButton->setEnabled(1); + mManager->Render(); + QApplication::restoreOverrideCursor(); } void vvSegmentationDialog::Dilate() { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - vtkImageContinuousDilate3D* dilate = vtkImageContinuousDilate3D::New(); - vtkImageLogic* And = vtkImageLogic::New(); - And->SetOperationToAnd(); - dilate->SetKernelSize(mKernelValue,mKernelValue,mKernelValue); - for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) - { - vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; - dilate->SetInput(image); - vtkImageData* mask = mBinaireImages[numImage]; - And->SetInput1(dilate->GetOutput()); - And->SetInput2(mask); - And->Update(); - image->DeepCopy(And->GetOutput()); - image->Update(); - } - And->Delete(); - dilate->Delete(); - mManager->Render(); - QApplication::restoreOverrideCursor(); + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + vtkImageContinuousDilate3D* dilate = vtkImageContinuousDilate3D::New(); + vtkImageLogic* And = vtkImageLogic::New(); + And->SetOperationToAnd(); + dilate->SetKernelSize(mKernelValue,mKernelValue,mKernelValue); + for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) { + vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; + dilate->SetInput(image); + vtkImageData* mask = mBinaireImages[numImage]; + And->SetInput1(dilate->GetOutput()); + And->SetInput2(mask); + And->Update(); + image->DeepCopy(And->GetOutput()); + image->Update(); + } + And->Delete(); + dilate->Delete(); + mManager->Render(); + QApplication::restoreOverrideCursor(); } void vvSegmentationDialog::InsertSeed() { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - int point4D[4]; - point4D[0] = mManager->GetLandmarks()->GetCoordinates( - mManager->GetLandmarks()->GetNumberOfPoints()-1)[0]; - point4D[1] = mManager->GetLandmarks()->GetCoordinates( - mManager->GetLandmarks()->GetNumberOfPoints()-1)[1]; - point4D[2] = mManager->GetLandmarks()->GetCoordinates( - mManager->GetLandmarks()->GetNumberOfPoints()-1)[2]; - point4D[3] = mManager->GetLandmarks()->GetCoordinates( - mManager->GetLandmarks()->GetNumberOfPoints()-1)[3]; - - point4D[0] = point4D[0]/mManager->GetSlicer(0)->GetImage()->GetVTKImages()[0]->GetSpacing()[0]; - point4D[1] = point4D[1]/mManager->GetSlicer(0)->GetImage()->GetVTKImages()[0]->GetSpacing()[1]; - point4D[2] = point4D[2]/mManager->GetSlicer(0)->GetImage()->GetVTKImages()[0]->GetSpacing()[2]; - - vtkImageSeedConnectivity* seed = vtkImageSeedConnectivity::New(); - seed->SetInputConnectValue(1); - seed->SetOutputConnectedValue(1); - seed->SetOutputUnconnectedValue(0); - seed->AddSeed(point4D[0],point4D[1],point4D[2]); - - for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) - { - vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; - seed->SetInput(image); - seed->Update(); - image->DeepCopy(seed->GetOutput()); - image->Update(); - } - - seed->Delete(); - QApplication::restoreOverrideCursor(); + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + int point4D[4]; + point4D[0] = mManager->GetLandmarks()->GetCoordinates( + mManager->GetLandmarks()->GetNumberOfPoints()-1)[0]; + point4D[1] = mManager->GetLandmarks()->GetCoordinates( + mManager->GetLandmarks()->GetNumberOfPoints()-1)[1]; + point4D[2] = mManager->GetLandmarks()->GetCoordinates( + mManager->GetLandmarks()->GetNumberOfPoints()-1)[2]; + point4D[3] = mManager->GetLandmarks()->GetCoordinates( + mManager->GetLandmarks()->GetNumberOfPoints()-1)[3]; + + point4D[0] = point4D[0]/mManager->GetSlicer(0)->GetImage()->GetVTKImages()[0]->GetSpacing()[0]; + point4D[1] = point4D[1]/mManager->GetSlicer(0)->GetImage()->GetVTKImages()[0]->GetSpacing()[1]; + point4D[2] = point4D[2]/mManager->GetSlicer(0)->GetImage()->GetVTKImages()[0]->GetSpacing()[2]; + + vtkImageSeedConnectivity* seed = vtkImageSeedConnectivity::New(); + seed->SetInputConnectValue(1); + seed->SetOutputConnectedValue(1); + seed->SetOutputUnconnectedValue(0); + seed->AddSeed(point4D[0],point4D[1],point4D[2]); + + for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) { + vtkImageData* image = mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]; + seed->SetInput(image); + seed->Update(); + image->DeepCopy(seed->GetOutput()); + image->Update(); + } + + seed->Delete(); + QApplication::restoreOverrideCursor(); } void vvSegmentationDialog::ChangeDimRendering() { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - - if (dimButton->text() == "3D") - { - if (m3DActors.size() == 0) - { - m3DExtractor->SetValue(0,0.5); - for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) - { - vtkActor* actor = vtkActor::New(); - m3DExtractor->SetInput(mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]); - m3DExtractor->Update(); - - vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); - mapper->SetInput(m3DExtractor->GetOutput()); - m3DMappers.push_back(mapper); - - actor->SetMapper(mapper); - actor->GetProperty()->SetColor(1.0,0.7,0.2); - actor->VisibilityOff(); - - mManager->GetSlicer(0)->GetRenderer()->AddActor(actor); - m3DActors.push_back(actor); - } - } + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + + if (dimButton->text() == "3D") { + if (m3DActors.size() == 0) { + m3DExtractor->SetValue(0,0.5); + for (unsigned int numImage = 0; numImage < mManager->GetSlicer(0)->GetImage()->GetVTKImages().size(); numImage++) { + vtkActor* actor = vtkActor::New(); + m3DExtractor->SetInput(mManager->GetSlicer(0)->GetImage()->GetVTKImages()[numImage]); + m3DExtractor->Update(); + + vtkPolyDataMapper* mapper = vtkPolyDataMapper::New(); + mapper->SetInput(m3DExtractor->GetOutput()); + m3DMappers.push_back(mapper); + + actor->SetMapper(mapper); + actor->GetProperty()->SetColor(1.0,0.7,0.2); + actor->VisibilityOff(); + + mManager->GetSlicer(0)->GetRenderer()->AddActor(actor); + m3DActors.push_back(actor); + } + } - mManager->GetSlicer(0)->GetRenderer()->SetBackground(0.5,0.6,0.9); - m3DActors[0]->VisibilityOn(); + mManager->GetSlicer(0)->GetRenderer()->SetBackground(0.5,0.6,0.9); + m3DActors[0]->VisibilityOn(); - vtkInteractorStyleTrackballCamera* style = vtkInteractorStyleTrackballCamera::New(); - mManager->SetInteractorStyleNavigator(0,style); - style->Delete(); + vtkInteractorStyleTrackballCamera* style = vtkInteractorStyleTrackballCamera::New(); + mManager->SetInteractorStyleNavigator(0,style); + style->Delete(); - mManager->GetSlicer(0)->GetImageActor()->VisibilityOff(); - mSquaresActor1->VisibilityOff(); - mSquaresActor2->VisibilityOff(); - mManager->Render(); - dimButton->setText("2D"); - } - else - { - mManager->GetSlicer(0)->GetRenderer()->SetBackground(0.0,0.0,0.0); - vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New(); - mManager->SetInteractorStyleNavigator(0,style); - style->Delete(); - - mManager->GetSlicer(0)->SetSliceOrientation(2); - m3DActors[mManager->GetSlicer(0)->GetTSlice()]->VisibilityOff(); - - mManager->GetSlicer(0)->GetImageActor()->VisibilityOn(); - mSquaresActor1->VisibilityOn(); - mSquaresActor2->VisibilityOn(); - dimButton->setText("3D"); - } - QApplication::restoreOverrideCursor(); + mManager->GetSlicer(0)->GetImageActor()->VisibilityOff(); + mSquaresActor1->VisibilityOff(); + mSquaresActor2->VisibilityOff(); + mManager->Render(); + dimButton->setText("2D"); + } else { + mManager->GetSlicer(0)->GetRenderer()->SetBackground(0.0,0.0,0.0); + vvInteractorStyleNavigator* style = vvInteractorStyleNavigator::New(); + mManager->SetInteractorStyleNavigator(0,style); + style->Delete(); + + mManager->GetSlicer(0)->SetSliceOrientation(2); + m3DActors[mManager->GetSlicer(0)->GetTSlice()]->VisibilityOff(); + + mManager->GetSlicer(0)->GetImageActor()->VisibilityOn(); + mSquaresActor1->VisibilityOn(); + mSquaresActor2->VisibilityOn(); + dimButton->setText("3D"); + } + QApplication::restoreOverrideCursor(); } void vvSegmentationDialog::KernelValueChanged(int kernel) { - mKernelValue = kernel; + mKernelValue = kernel; } void vvSegmentationDialog::Save() { - if (dimButton->text() == "2D") //If in *3D* mode, save the mesh - { - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save Mesh As"), - QDir::home().dirName(), - "Mesh Files (*.vtk *.vtp)"); - if (!fileName.isEmpty()) - { - vtkSmartPointer w = vtkSmartPointer::New(); - w->SetInput(m3DExtractor->GetOutput()); - w->SetFileName(fileName.toStdString().c_str()); - w->Write(); - } + if (dimButton->text() == "2D") { //If in *3D* mode, save the mesh + QString fileName = QFileDialog::getSaveFileName(this, + tr("Save Mesh As"), + QDir::home().dirName(), + "Mesh Files (*.vtk *.vtp)"); + if (!fileName.isEmpty()) { + vtkSmartPointer w = vtkSmartPointer::New(); + w->SetInput(m3DExtractor->GetOutput()); + w->SetFileName(fileName.toStdString().c_str()); + w->Write(); } - else { - QStringList OutputListeFormat; - OutputListeFormat.clear(); - int dimension = mManager->GetDimension(); - if (dimension == 1) - { - OutputListeFormat.push_back(".mhd"); - } - if (dimension == 2) - { - OutputListeFormat.push_back(".bmp"); - OutputListeFormat.push_back(".png"); - OutputListeFormat.push_back(".jpeg"); - OutputListeFormat.push_back(".tif"); - OutputListeFormat.push_back(".mhd"); - OutputListeFormat.push_back(".hdr"); - OutputListeFormat.push_back(".vox"); - } - else if (dimension == 3) - { - OutputListeFormat.push_back(".mhd"); - OutputListeFormat.push_back(".hdr"); - OutputListeFormat.push_back(".vox"); - } - else if (dimension == 4) - { - OutputListeFormat.push_back(".mhd"); - } - QString Extensions = "AllFiles(*.*)"; - for (int i = 0; i < OutputListeFormat.count(); i++) - { - Extensions += ";;Images ( *"; - Extensions += OutputListeFormat[i]; - Extensions += ")"; - } - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save As"), - QDir::home().dirName(), - Extensions); - if (!fileName.isEmpty()) - { - std::string fileformat = vtksys::SystemTools::GetFilenameLastExtension(fileName.toStdString()); - if (OutputListeFormat.contains( - fileformat.c_str())) - { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - vvProgressDialog progress("Saving "+fileName.toStdString()); - qApp->processEvents(); - vvImageWriter *writer = new vvImageWriter; - writer->SetOutputFileName(fileName.toStdString()); - writer->SetInput(mManager->GetSlicer(0)->GetImage()); - writer->Update(dimension,"unsigned_char"); - QApplication::restoreOverrideCursor(); - if (writer->GetLastError().size()) - { - QString error = "Saving did not succeed\n"; - error += writer->GetLastError().c_str(); - QMessageBox::information(this,tr("Saving Problem"),error); - Save(); - } - } - else - { - QString error = fileformat.c_str(); - if (error.isEmpty()) - error += "no file format specified !"; - else - error += " format unknown !!!\n"; - QMessageBox::information(this,tr("Saving Problem"),error); - Save(); - } + } else { + QStringList OutputListeFormat; + OutputListeFormat.clear(); + int dimension = mManager->GetDimension(); + if (dimension == 1) { + OutputListeFormat.push_back(".mhd"); + } + if (dimension == 2) { + OutputListeFormat.push_back(".bmp"); + OutputListeFormat.push_back(".png"); + OutputListeFormat.push_back(".jpeg"); + OutputListeFormat.push_back(".tif"); + OutputListeFormat.push_back(".mhd"); + OutputListeFormat.push_back(".hdr"); + OutputListeFormat.push_back(".vox"); + } else if (dimension == 3) { + OutputListeFormat.push_back(".mhd"); + OutputListeFormat.push_back(".hdr"); + OutputListeFormat.push_back(".vox"); + } else if (dimension == 4) { + OutputListeFormat.push_back(".mhd"); + } + QString Extensions = "AllFiles(*.*)"; + for (int i = 0; i < OutputListeFormat.count(); i++) { + Extensions += ";;Images ( *"; + Extensions += OutputListeFormat[i]; + Extensions += ")"; + } + QString fileName = QFileDialog::getSaveFileName(this, + tr("Save As"), + QDir::home().dirName(), + Extensions); + if (!fileName.isEmpty()) { + std::string fileformat = vtksys::SystemTools::GetFilenameLastExtension(fileName.toStdString()); + if (OutputListeFormat.contains( + fileformat.c_str())) { + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + vvProgressDialog progress("Saving "+fileName.toStdString()); + qApp->processEvents(); + vvImageWriter *writer = new vvImageWriter; + writer->SetOutputFileName(fileName.toStdString()); + writer->SetInput(mManager->GetSlicer(0)->GetImage()); + writer->Update(dimension,"unsigned_char"); + QApplication::restoreOverrideCursor(); + if (writer->GetLastError().size()) { + QString error = "Saving did not succeed\n"; + error += writer->GetLastError().c_str(); + QMessageBox::information(this,tr("Saving Problem"),error); + Save(); } + } else { + QString error = fileformat.c_str(); + if (error.isEmpty()) + error += "no file format specified !"; + else + error += " format unknown !!!\n"; + QMessageBox::information(this,tr("Saving Problem"),error); + Save(); + } } + } } #endif /* end #define _vvSegmentationDialog_CXX */ diff --git a/vv/vvSlicer.cxx b/vv/vvSlicer.cxx index 1de1738..bbecaa4 100644 --- a/vv/vvSlicer.cxx +++ b/vv/vvSlicer.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -143,62 +143,70 @@ vvSlicer::vvSlicer() this->WindowLevel->Delete(); this->WindowLevel = vvImageMapToWLColors::New(); this->InstallPipeline(); - + } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vtkImageMapToWindowLevelColors* vvSlicer::GetOverlayMapper() { +vtkImageMapToWindowLevelColors* vvSlicer::GetOverlayMapper() +{ return mOverlayMapper.GetPointer(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vvBlendImageActor* vvSlicer::GetOverlayActor() { +vvBlendImageActor* vvSlicer::GetOverlayActor() +{ return mOverlayActor.GetPointer(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vtkImageMapToWindowLevelColors* vvSlicer::GetFusionMapper() { +vtkImageMapToWindowLevelColors* vvSlicer::GetFusionMapper() +{ return mFusionMapper.GetPointer(); } //------------------------------------------------------------------------------ - + //------------------------------------------------------------------------------ -vtkImageActor* vvSlicer::GetFusionActor() { +vtkImageActor* vvSlicer::GetFusionActor() +{ return mFusionActor.GetPointer(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vtkActor* vvSlicer::GetVFActor() { +vtkActor* vvSlicer::GetVFActor() +{ return mVFActor.GetPointer(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vtkCornerAnnotation* vvSlicer::GetAnnotation() { +vtkCornerAnnotation* vvSlicer::GetAnnotation() +{ return ca.GetPointer(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvSlicer::EnableReducedExtent(bool b) { +void vvSlicer::EnableReducedExtent(bool b) +{ mUseReducedExtent = b; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvSlicer::SetReducedExtent(int * ext) { +void vvSlicer::SetReducedExtent(int * ext) +{ mReducedExtent = ext; } //------------------------------------------------------------------------------ @@ -225,7 +233,7 @@ void vvSlicer::AddContour(vvMesh::Pointer contour,bool propagate) void vvSlicer::ToggleContourSuperposition() { for (std::vector::iterator i=mSurfaceCutActors.begin(); - i!=mSurfaceCutActors.end();i++) + i!=mSurfaceCutActors.end(); i++) (*i)->ToggleSuperposition(); } //------------------------------------------------------------------------------ @@ -259,7 +267,7 @@ bool vvSlicer::GetCursorVisibility() vvSlicer::~vvSlicer() { for (std::vector::iterator i=mSurfaceCutActors.begin(); - i!=mSurfaceCutActors.end();i++) + i!=mSurfaceCutActors.end(); i++) delete (*i); } //------------------------------------------------------------------------------ @@ -279,34 +287,33 @@ void vvSlicer::SetCurrentPosition(double x, double y, double z, int t) //------------------------------------------------------------------------------ void vvSlicer::SetImage(vvImage::Pointer image) { - if (image->GetVTKImages().size()) - { - mImage = image; - this->Superclass::SetInput(image->GetVTKImages()[0]); - - // Prevent crash when reload -> change slice if outside extent - int extent[6]; - this->GetInput()->GetWholeExtent(extent); - if (SliceOrientation == 0) { - if (Slice >= extent[1]) { - Slice = (extent[1]-extent[0])/2.0; - } + if (image->GetVTKImages().size()) { + mImage = image; + this->Superclass::SetInput(image->GetVTKImages()[0]); + + // Prevent crash when reload -> change slice if outside extent + int extent[6]; + this->GetInput()->GetWholeExtent(extent); + if (SliceOrientation == 0) { + if (Slice >= extent[1]) { + Slice = (extent[1]-extent[0])/2.0; } - if (SliceOrientation == 1) { - if (Slice >= extent[3]) { - Slice = (extent[3]-extent[2])/2.0; - } + } + if (SliceOrientation == 1) { + if (Slice >= extent[3]) { + Slice = (extent[3]-extent[2])/2.0; } - if (SliceOrientation == 2) { - if (Slice >= extent[5]) { - Slice = (extent[5]-extent[4])/2.0; - } + } + if (SliceOrientation == 2) { + if (Slice >= extent[5]) { + Slice = (extent[5]-extent[4])/2.0; } - - this->UpdateDisplayExtent(); - mCurrentTSlice = 0; - ca->SetText(0,mFileName.c_str()); } + + this->UpdateDisplayExtent(); + mCurrentTSlice = 0; + ca->SetText(0,mFileName.c_str()); + } } //------------------------------------------------------------------------------ @@ -314,37 +321,33 @@ void vvSlicer::SetImage(vvImage::Pointer image) //------------------------------------------------------------------------------ void vvSlicer::SetOverlay(vvImage::Pointer overlay) { - if (overlay->GetVTKImages().size()) - { - mOverlay = overlay; - - if (!mOverlayMapper) - mOverlayMapper = vtkImageMapToWindowLevelColors::New(); - mOverlayMapper->SetInput(overlay->GetVTKImages()[0]); - - if (!mOverlayActor) - { - mOverlayActor = vvBlendImageActor::New(); - mOverlayActor->SetInput(mOverlayMapper->GetOutput()); - mOverlayActor->SetPickable(0); - mOverlayActor->SetVisibility(false); - mOverlayActor->SetOpacity(0.5); - this->UpdateDisplayExtent(); - } - - //stupid but necessary : the Overlay need to be rendered before fusion - if (mFusionActor) - { - this->GetRenderer()->RemoveActor(mFusionActor); - this->GetRenderer()->AddActor(mOverlayActor); - this->GetRenderer()->AddActor(mFusionActor); - } - else - this->GetRenderer()->AddActor(mOverlayActor); - - //Synchronize slice - SetTSlice(mCurrentTSlice); + if (overlay->GetVTKImages().size()) { + mOverlay = overlay; + + if (!mOverlayMapper) + mOverlayMapper = vtkImageMapToWindowLevelColors::New(); + mOverlayMapper->SetInput(overlay->GetVTKImages()[0]); + + if (!mOverlayActor) { + mOverlayActor = vvBlendImageActor::New(); + mOverlayActor->SetInput(mOverlayMapper->GetOutput()); + mOverlayActor->SetPickable(0); + mOverlayActor->SetVisibility(false); + mOverlayActor->SetOpacity(0.5); + this->UpdateDisplayExtent(); } + + //stupid but necessary : the Overlay need to be rendered before fusion + if (mFusionActor) { + this->GetRenderer()->RemoveActor(mFusionActor); + this->GetRenderer()->AddActor(mOverlayActor); + this->GetRenderer()->AddActor(mFusionActor); + } else + this->GetRenderer()->AddActor(mOverlayActor); + + //Synchronize slice + SetTSlice(mCurrentTSlice); + } } //------------------------------------------------------------------------------ @@ -352,28 +355,26 @@ void vvSlicer::SetOverlay(vvImage::Pointer overlay) //------------------------------------------------------------------------------ void vvSlicer::SetFusion(vvImage::Pointer fusion) { - if (fusion->GetVTKImages().size()) - { - mFusion = fusion; - - if (!mFusionMapper) - mFusionMapper = vtkImageMapToWindowLevelColors::New(); - mFusionMapper->SetInput(fusion->GetVTKImages()[0]); - - if (!mFusionActor) - { - mFusionActor = vtkImageActor::New(); - mFusionActor->SetInput(mFusionMapper->GetOutput()); - mFusionActor->SetPickable(0); - mFusionActor->SetVisibility(false); - mFusionActor->SetOpacity(0.7); - this->UpdateDisplayExtent(); - this->GetRenderer()->AddActor(mFusionActor); - } - - //Synchronize slice - SetTSlice(mCurrentTSlice); + if (fusion->GetVTKImages().size()) { + mFusion = fusion; + + if (!mFusionMapper) + mFusionMapper = vtkImageMapToWindowLevelColors::New(); + mFusionMapper->SetInput(fusion->GetVTKImages()[0]); + + if (!mFusionActor) { + mFusionActor = vtkImageActor::New(); + mFusionActor->SetInput(mFusionMapper->GetOutput()); + mFusionActor->SetPickable(0); + mFusionActor->SetVisibility(false); + mFusionActor->SetOpacity(0.7); + this->UpdateDisplayExtent(); + this->GetRenderer()->AddActor(mFusionActor); } + + //Synchronize slice + SetTSlice(mCurrentTSlice); + } } //------------------------------------------------------------------------------ @@ -381,18 +382,15 @@ void vvSlicer::SetFusion(vvImage::Pointer fusion) //------------------------------------------------------------------------------ void vvSlicer::SetActorVisibility(const std::string& actor_type, int overlay_index ,bool vis) { - if (actor_type == "vector") - { - this->mVFActor->SetVisibility(vis); - } - if (actor_type == "overlay") - { - this->mOverlayActor->SetVisibility(vis); - } - if (actor_type == "fusion") - { - this->mFusionActor->SetVisibility(vis); - } + if (actor_type == "vector") { + this->mVFActor->SetVisibility(vis); + } + if (actor_type == "overlay") { + this->mOverlayActor->SetVisibility(vis); + } + if (actor_type == "fusion") { + this->mFusionActor->SetVisibility(vis); + } if (actor_type == "contour") this->mSurfaceCutActors[overlay_index]->GetActor()->SetVisibility(vis); UpdateDisplayExtent(); @@ -403,55 +401,53 @@ void vvSlicer::SetActorVisibility(const std::string& actor_type, int overlay_ind //------------------------------------------------------------------------------ void vvSlicer::SetVF(vvImage::Pointer vf) { - if (vf->GetVTKImages().size()) - { - mVF = vf; - - if (!mAAFilter) - { - mAAFilter=vtkAssignAttribute::New(); - mVOIFilter = vtkExtractVOI::New(); - mVOIFilter->SetSampleRate(mSubSampling,mSubSampling,mSubSampling); - } - mVOIFilter->SetInput(vf->GetVTKImages()[0]); - mAAFilter->SetInput(mVOIFilter->GetOutput()); - ///This tells VTK to use the scalar (pixel) data of the image to draw the little arrows - mAAFilter->Assign(vtkDataSetAttributes::SCALARS, vtkDataSetAttributes::VECTORS, vtkAssignAttribute::POINT_DATA); - - if (!mArrow) - mArrow = vvGlyphSource::New(); - mArrow->SetGlyphTypeToSpecificArrow(); - mArrow->SetScale(mScale); - mArrow->FilledOff(); - - // Glyph the gradient vector (with arrows) - if (!mGlyphFilter) - mGlyphFilter = vvGlyph2D::New(); - mGlyphFilter->SetInput(mAAFilter->GetOutput()); - mGlyphFilter->SetSource(mArrow->GetOutput()); - mGlyphFilter->ScalingOn(); - mGlyphFilter->SetScaleModeToScaleByVector(); - mGlyphFilter->OrientOn(); - mGlyphFilter->SetVectorModeToUseVector(); - mGlyphFilter->SetColorModeToColorByVector(); - - if (!mVFMapper) - mVFMapper = vtkPolyDataMapper::New(); - //mVFMapper->SetInputConnection(mGlyphFilter->GetOutputPort()); - mVFMapper->SetInput(mGlyphFilter->GetOutput()); - mVFMapper->ImmediateModeRenderingOn(); - - if (!mVFActor) - mVFActor = vtkActor::New(); - mVFActor->SetMapper(mVFMapper); - mVFActor->SetPickable(0); - mVFActor->GetProperty()->SetLineWidth(mVFWidth); - this->UpdateDisplayExtent(); - this->GetRenderer()->AddActor(mVFActor); + if (vf->GetVTKImages().size()) { + mVF = vf; - //Synchronize slice - SetTSlice(mCurrentTSlice); + if (!mAAFilter) { + mAAFilter=vtkAssignAttribute::New(); + mVOIFilter = vtkExtractVOI::New(); + mVOIFilter->SetSampleRate(mSubSampling,mSubSampling,mSubSampling); } + mVOIFilter->SetInput(vf->GetVTKImages()[0]); + mAAFilter->SetInput(mVOIFilter->GetOutput()); + ///This tells VTK to use the scalar (pixel) data of the image to draw the little arrows + mAAFilter->Assign(vtkDataSetAttributes::SCALARS, vtkDataSetAttributes::VECTORS, vtkAssignAttribute::POINT_DATA); + + if (!mArrow) + mArrow = vvGlyphSource::New(); + mArrow->SetGlyphTypeToSpecificArrow(); + mArrow->SetScale(mScale); + mArrow->FilledOff(); + + // Glyph the gradient vector (with arrows) + if (!mGlyphFilter) + mGlyphFilter = vvGlyph2D::New(); + mGlyphFilter->SetInput(mAAFilter->GetOutput()); + mGlyphFilter->SetSource(mArrow->GetOutput()); + mGlyphFilter->ScalingOn(); + mGlyphFilter->SetScaleModeToScaleByVector(); + mGlyphFilter->OrientOn(); + mGlyphFilter->SetVectorModeToUseVector(); + mGlyphFilter->SetColorModeToColorByVector(); + + if (!mVFMapper) + mVFMapper = vtkPolyDataMapper::New(); + //mVFMapper->SetInputConnection(mGlyphFilter->GetOutputPort()); + mVFMapper->SetInput(mGlyphFilter->GetOutput()); + mVFMapper->ImmediateModeRenderingOn(); + + if (!mVFActor) + mVFActor = vtkActor::New(); + mVFActor->SetMapper(mVFMapper); + mVFActor->SetPickable(0); + mVFActor->GetProperty()->SetLineWidth(mVFWidth); + this->UpdateDisplayExtent(); + this->GetRenderer()->AddActor(mVFActor); + + //Synchronize slice + SetTSlice(mCurrentTSlice); + } } //------------------------------------------------------------------------------ @@ -460,48 +456,47 @@ void vvSlicer::SetVF(vvImage::Pointer vf) void vvSlicer::SetLandmarks(vvLandmarks* landmarks) { mLandmarks = landmarks; - if (landmarks) - { - - if (!mCross) - mCross = vtkCursor3D::New(); - mCross->SetFocalPoint(0.0,0.0,0.0); - mCross->SetModelBounds(-10,10,-10,10,-10,10); - mCross->AllOff(); - mCross->AxesOn(); - - if (!mLandGlyph) - mLandGlyph = vtkGlyph3D::New(); - mLandGlyph->SetSource(mCross->GetOutput()); - mLandGlyph->SetInput(landmarks->GetOutput()); - //mLandGlyph->SetIndexModeToScalar(); - mLandGlyph->SetRange(0,1); - mLandGlyph->ScalingOff(); - - mLandGlyph->SetColorModeToColorByScalar(); - - if (!mClipBox) - mClipBox = vtkBox::New(); - if (!mLandClipper) - mLandClipper = vtkClipPolyData::New(); - mLandClipper->InsideOutOn(); - mLandClipper->SetInput(mLandGlyph->GetOutput()); - mLandClipper->SetClipFunction(mClipBox); - - if (!mLandMapper) - mLandMapper = vtkPolyDataMapper::New(); - mLandMapper->SetInputConnection(mLandClipper->GetOutputPort()); - //mLandMapper->ScalarVisibilityOff(); - - if (!mLandActor) - mLandActor = vtkActor::New(); - mLandActor->SetMapper(mLandMapper); - mLandActor->GetProperty()->SetColor(255,10,212); - mLandActor->SetPickable(0); - mLandActor->SetVisibility(true); - this->UpdateDisplayExtent(); - this->GetRenderer()->AddActor(mLandActor); - } + if (landmarks) { + + if (!mCross) + mCross = vtkCursor3D::New(); + mCross->SetFocalPoint(0.0,0.0,0.0); + mCross->SetModelBounds(-10,10,-10,10,-10,10); + mCross->AllOff(); + mCross->AxesOn(); + + if (!mLandGlyph) + mLandGlyph = vtkGlyph3D::New(); + mLandGlyph->SetSource(mCross->GetOutput()); + mLandGlyph->SetInput(landmarks->GetOutput()); + //mLandGlyph->SetIndexModeToScalar(); + mLandGlyph->SetRange(0,1); + mLandGlyph->ScalingOff(); + + mLandGlyph->SetColorModeToColorByScalar(); + + if (!mClipBox) + mClipBox = vtkBox::New(); + if (!mLandClipper) + mLandClipper = vtkClipPolyData::New(); + mLandClipper->InsideOutOn(); + mLandClipper->SetInput(mLandGlyph->GetOutput()); + mLandClipper->SetClipFunction(mClipBox); + + if (!mLandMapper) + mLandMapper = vtkPolyDataMapper::New(); + mLandMapper->SetInputConnection(mLandClipper->GetOutputPort()); + //mLandMapper->ScalarVisibilityOff(); + + if (!mLandActor) + mLandActor = vtkActor::New(); + mLandActor->SetMapper(mLandMapper); + mLandActor->GetProperty()->SetColor(255,10,212); + mLandActor->SetPickable(0); + mLandActor->SetVisibility(true); + this->UpdateDisplayExtent(); + this->GetRenderer()->AddActor(mLandActor); + } } //------------------------------------------------------------------------------ @@ -509,36 +504,32 @@ void vvSlicer::SetLandmarks(vvLandmarks* landmarks) //FIXME: this function leaks memory, we should fix it someday :) void vvSlicer::RemoveActor(const std::string& actor_type, int overlay_index) { - if (actor_type == "vector") - { - Renderer->RemoveActor(mVFActor); - mGlyphFilter=NULL; - mVF = NULL; - mArrow = NULL; - mAAFilter=NULL; - mVOIFilter = NULL; - mVFMapper = NULL; - mVFActor = NULL; - } - if (actor_type == "overlay") - { - Renderer->RemoveActor(mOverlayActor); - mOverlay = NULL; - mOverlayActor = NULL; - mOverlayMapper = NULL; - } - if (actor_type == "fusion") - { - Renderer->RemoveActor(mFusionActor); - mFusion = NULL; - mFusionActor = NULL; - mFusionMapper = NULL; - } - if (actor_type == "contour") - { - Renderer->RemoveActor(this->mSurfaceCutActors[overlay_index]->GetActor()); - mSurfaceCutActors.erase(mSurfaceCutActors.begin()+overlay_index); - } + if (actor_type == "vector") { + Renderer->RemoveActor(mVFActor); + mGlyphFilter=NULL; + mVF = NULL; + mArrow = NULL; + mAAFilter=NULL; + mVOIFilter = NULL; + mVFMapper = NULL; + mVFActor = NULL; + } + if (actor_type == "overlay") { + Renderer->RemoveActor(mOverlayActor); + mOverlay = NULL; + mOverlayActor = NULL; + mOverlayMapper = NULL; + } + if (actor_type == "fusion") { + Renderer->RemoveActor(mFusionActor); + mFusion = NULL; + mFusionActor = NULL; + mFusionMapper = NULL; + } + if (actor_type == "contour") { + Renderer->RemoveActor(this->mSurfaceCutActors[overlay_index]->GetActor()); + mSurfaceCutActors.erase(mSurfaceCutActors.begin()+overlay_index); + } } //------------------------------------------------------------------------------ @@ -546,11 +537,10 @@ void vvSlicer::RemoveActor(const std::string& actor_type, int overlay_index) //------------------------------------------------------------------------------ void vvSlicer::SetVFSubSampling(int sub) { - if (mVOIFilter) - { - mVOIFilter->SetSampleRate(mSubSampling,mSubSampling,mSubSampling); - mSubSampling = sub; - } + if (mVOIFilter) { + mVOIFilter->SetSampleRate(mSubSampling,mSubSampling,mSubSampling); + mSubSampling = sub; + } UpdateDisplayExtent(); Render(); } @@ -584,11 +574,10 @@ void vvSlicer::SetVFWidth(int width) void vvSlicer::SetVFLog(int log) { mVFLog = log; - if (mGlyphFilter) - { - mGlyphFilter->SetUseLog(mVFLog); - mGlyphFilter->Modified(); - } + if (mGlyphFilter) { + mGlyphFilter->SetUseLog(mVFLog); + mGlyphFilter->Modified(); + } UpdateDisplayExtent(); Render(); } @@ -607,24 +596,21 @@ void vvSlicer::SetTSlice(int t) mCurrentTSlice = t; this->SetInput(mImage->GetVTKImages()[t]); - if (mVF && mVFActor->GetVisibility()) - { - if (mVF->GetVTKImages().size() > (unsigned int)mCurrentTSlice) - mVOIFilter->SetInput(mVF->GetVTKImages()[mCurrentTSlice]); - } - if (mOverlay && mOverlayActor->GetVisibility()) - { - if (mOverlay->GetVTKImages().size() > (unsigned int)mCurrentTSlice) - mOverlayMapper->SetInput(mOverlay->GetVTKImages()[mCurrentTSlice]); - } - if (mFusion && mFusionActor->GetVisibility()) - { - if (mFusion->GetVTKImages().size() > (unsigned int)mCurrentTSlice) - mFusionMapper->SetInput(mFusion->GetVTKImages()[mCurrentTSlice]); - } + if (mVF && mVFActor->GetVisibility()) { + if (mVF->GetVTKImages().size() > (unsigned int)mCurrentTSlice) + mVOIFilter->SetInput(mVF->GetVTKImages()[mCurrentTSlice]); + } + if (mOverlay && mOverlayActor->GetVisibility()) { + if (mOverlay->GetVTKImages().size() > (unsigned int)mCurrentTSlice) + mOverlayMapper->SetInput(mOverlay->GetVTKImages()[mCurrentTSlice]); + } + if (mFusion && mFusionActor->GetVisibility()) { + if (mFusion->GetVTKImages().size() > (unsigned int)mCurrentTSlice) + mFusionMapper->SetInput(mFusion->GetVTKImages()[mCurrentTSlice]); + } if (mSurfaceCutActors.size() > 0) for (std::vector::iterator i=mSurfaceCutActors.begin(); - i!=mSurfaceCutActors.end();i++) + i!=mSurfaceCutActors.end(); i++) (*i)->SetTimeSlice(mCurrentTSlice); UpdateDisplayExtent(); } @@ -649,14 +635,13 @@ void vvSlicer::SetSliceOrientation(int orientation) orientation=2; if (orientation < vtkImageViewer2::SLICE_ORIENTATION_YZ || - orientation > vtkImageViewer2::SLICE_ORIENTATION_XY) - { - vtkErrorMacro("Error - invalid slice orientation " << orientation); - return; - } + orientation > vtkImageViewer2::SLICE_ORIENTATION_XY) { + vtkErrorMacro("Error - invalid slice orientation " << orientation); + return; + } this->SliceOrientation = orientation; - + // Update the viewer int *range = this->GetSliceRange(); if (range) @@ -665,12 +650,11 @@ void vvSlicer::SetSliceOrientation(int orientation) this->UpdateOrientation(); this->UpdateDisplayExtent(); - if (this->Renderer && this->GetInput()) - { - double scale = this->Renderer->GetActiveCamera()->GetParallelScale(); - this->Renderer->ResetCamera(); - this->Renderer->GetActiveCamera()->SetParallelScale(scale); - } + if (this->Renderer && this->GetInput()) { + double scale = this->Renderer->GetActiveCamera()->GetParallelScale(); + this->Renderer->ResetCamera(); + this->Renderer->GetActiveCamera()->SetParallelScale(scale); + } SetContourSlice(); } @@ -678,19 +662,20 @@ void vvSlicer::SetSliceOrientation(int orientation) //---------------------------------------------------------------------------- -int * vvSlicer::GetExtent() { +int * vvSlicer::GetExtent() +{ int *w_ext; if (mUseReducedExtent) { w_ext = mReducedExtent; - } - else w_ext = GetInput()->GetWholeExtent(); + } else w_ext = GetInput()->GetWholeExtent(); return w_ext; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- -int vvSlicer::GetOrientation() { +int vvSlicer::GetOrientation() +{ return this->SliceOrientation; } //---------------------------------------------------------------------------- @@ -700,219 +685,196 @@ int vvSlicer::GetOrientation() { void vvSlicer::UpdateDisplayExtent() { vtkImageData *input = this->GetInput(); - if (!input || !this->ImageActor) - { - return; - } + if (!input || !this->ImageActor) { + return; + } input->UpdateInformation(); int *w_ext;// = input->GetWholeExtent(); if (mUseReducedExtent) { w_ext = mReducedExtent; - } - else w_ext = input->GetWholeExtent(); - - switch (this->SliceOrientation) - { - case vtkImageViewer2::SLICE_ORIENTATION_XY: - this->ImageActor->SetDisplayExtent( - w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice); - if (mVF && mVFActor->GetVisibility()) - { - int vfExtent[6]; - ComputeVFDisplayedExtent(w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice,vfExtent); - mVOIFilter->SetVOI(vfExtent); - mGlyphFilter->SetOrientation(1,1,0); - mVFMapper->Update(); - // put the vector field between the image and the camera - if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) - mVFActor->SetPosition(0,0,ImageActor->GetBounds()[5]+2); - else - mVFActor->SetPosition(0,0,ImageActor->GetBounds()[4]-2); - } - if (mOverlay && mOverlayActor->GetVisibility()) - { - int overExtent[6]; - ComputeOverlayDisplayedExtent(w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice,overExtent); - mOverlayActor->SetDisplayExtent(overExtent); - if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) - mOverlayActor->SetPosition(0,0,1); - else - mOverlayActor->SetPosition(0,0,-1); - } - if (mFusion && mFusionActor->GetVisibility()) - { - int fusExtent[6]; - ComputeFusionDisplayedExtent(w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice,fusExtent); - mFusionActor->SetDisplayExtent(fusExtent); - if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) - mFusionActor->SetPosition(0,0,1.5); - else - mFusionActor->SetPosition(0,0,-1.5); - } - if (mLandActor) - { - if (mClipBox) - { - double bounds [6]; - bounds[0] = ImageActor->GetBounds()[0]; - bounds[1] = ImageActor->GetBounds()[1]; - bounds[2] = ImageActor->GetBounds()[2]; - bounds[3] = ImageActor->GetBounds()[3]; - bounds[4] = ImageActor->GetBounds()[4]-(0.9/this->GetInput()->GetSpacing()[2]); - bounds[5] = ImageActor->GetBounds()[5]+(0.9/this->GetInput()->GetSpacing()[2]); - mClipBox->SetBounds(bounds); - UpdateLandmarks(); - } - if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) - mLandActor->SetPosition(0,0,1.5); - else - mLandActor->SetPosition(0,0,-1.5); - } - break; - - case vtkImageViewer2::SLICE_ORIENTATION_XZ: - this->ImageActor->SetDisplayExtent( - w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5]); - if (mVF && mVFActor->GetVisibility()) - { - int vfExtent[6]; - ComputeVFDisplayedExtent(w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5],vfExtent); - mVOIFilter->SetVOI(vfExtent); - mGlyphFilter->SetOrientation(1,0,1); - mVFMapper->Update(); - // put the vector field between the image aSpacingnd the camera - if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) - mVFActor->SetPosition(0,ImageActor->GetBounds()[3]+2,0); - else - mVFActor->SetPosition(0,ImageActor->GetBounds()[2]-2,0); - } - if (mOverlay && mOverlayActor->GetVisibility()) - { - int overExtent[6]; - ComputeOverlayDisplayedExtent(w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5],overExtent); - mOverlayActor->SetDisplayExtent(overExtent); - if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) - mOverlayActor->SetPosition(0,1,0); - else - mOverlayActor->SetPosition(0,-1,0); - } - if (mFusion && mFusionActor->GetVisibility()) - { - int fusExtent[6]; - ComputeFusionDisplayedExtent(w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5],fusExtent); - mFusionActor->SetDisplayExtent(fusExtent); - if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) - mFusionActor->SetPosition(0,1.5,0); - else - mFusionActor->SetPosition(0,-1.5,0); - } - if (mLandActor) - { - if (mClipBox) - { - double bounds [6]; - bounds[0] = ImageActor->GetBounds()[0]; - bounds[1] = ImageActor->GetBounds()[1]; - bounds[2] = ImageActor->GetBounds()[2]-(0.5/this->GetInput()->GetSpacing()[1]); - bounds[3] = ImageActor->GetBounds()[3]+(0.5/this->GetInput()->GetSpacing()[1]); - bounds[4] = ImageActor->GetBounds()[4]; - bounds[5] = ImageActor->GetBounds()[5]; - mClipBox->SetBounds(bounds); - UpdateLandmarks(); - } - if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) - mLandActor->SetPosition(0,1.5,0); - else - mLandActor->SetPosition(0,-1.5,0); - } - break; - - case vtkImageViewer2::SLICE_ORIENTATION_YZ: - this->ImageActor->SetDisplayExtent( - this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5]); - if (mVF && mVFActor->GetVisibility()) - { - int vfExtent[6]; - ComputeVFDisplayedExtent(this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5],vfExtent); - mVOIFilter->SetVOI(vfExtent); - mGlyphFilter->SetOrientation(0,1,1); - mVFMapper->Update(); - // put the vector field between the image and the camera - if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) - mVFActor->SetPosition(ImageActor->GetBounds()[1]+2,0,0); - else - mVFActor->SetPosition(ImageActor->GetBounds()[0]-2,0,0); - } - if (mOverlay && mOverlayActor->GetVisibility()) - { - int overExtent[6]; - ComputeOverlayDisplayedExtent(this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5],overExtent); - mOverlayActor->SetDisplayExtent(overExtent); - if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) - mOverlayActor->SetPosition(1,0,0); - else - mOverlayActor->SetPosition(-1,0,0); - } - if (mFusion && mFusionActor->GetVisibility()) - { - int fusExtent[6]; - ComputeFusionDisplayedExtent(this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5],fusExtent); - mFusionActor->SetDisplayExtent(fusExtent); - if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) - mFusionActor->SetPosition(1.5,0,0); - else - mFusionActor->SetPosition(-1.5,0,0); - } - if (mLandActor) - { - if (mClipBox) - { - double bounds [6]; - bounds[0] = ImageActor->GetBounds()[0]-(0.5/this->GetInput()->GetSpacing()[0]); - bounds[1] = ImageActor->GetBounds()[1]+(0.5/this->GetInput()->GetSpacing()[0]); - bounds[2] = ImageActor->GetBounds()[2]; - bounds[3] = ImageActor->GetBounds()[3]; - bounds[4] = ImageActor->GetBounds()[4]; - bounds[5] = ImageActor->GetBounds()[5]; - mClipBox->SetBounds(bounds); - UpdateLandmarks(); - } - if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) - mLandActor->SetPosition(1.5,0,0); - else - mLandActor->SetPosition(-1.5,0,0); - } - break; + } else w_ext = input->GetWholeExtent(); + + switch (this->SliceOrientation) { + case vtkImageViewer2::SLICE_ORIENTATION_XY: + this->ImageActor->SetDisplayExtent( + w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice); + if (mVF && mVFActor->GetVisibility()) { + int vfExtent[6]; + ComputeVFDisplayedExtent(w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice,vfExtent); + mVOIFilter->SetVOI(vfExtent); + mGlyphFilter->SetOrientation(1,1,0); + mVFMapper->Update(); + // put the vector field between the image and the camera + if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) + mVFActor->SetPosition(0,0,ImageActor->GetBounds()[5]+2); + else + mVFActor->SetPosition(0,0,ImageActor->GetBounds()[4]-2); + } + if (mOverlay && mOverlayActor->GetVisibility()) { + int overExtent[6]; + ComputeOverlayDisplayedExtent(w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice,overExtent); + mOverlayActor->SetDisplayExtent(overExtent); + if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) + mOverlayActor->SetPosition(0,0,1); + else + mOverlayActor->SetPosition(0,0,-1); + } + if (mFusion && mFusionActor->GetVisibility()) { + int fusExtent[6]; + ComputeFusionDisplayedExtent(w_ext[0], w_ext[1], w_ext[2], w_ext[3], this->Slice, this->Slice,fusExtent); + mFusionActor->SetDisplayExtent(fusExtent); + if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) + mFusionActor->SetPosition(0,0,1.5); + else + mFusionActor->SetPosition(0,0,-1.5); } + if (mLandActor) { + if (mClipBox) { + double bounds [6]; + bounds[0] = ImageActor->GetBounds()[0]; + bounds[1] = ImageActor->GetBounds()[1]; + bounds[2] = ImageActor->GetBounds()[2]; + bounds[3] = ImageActor->GetBounds()[3]; + bounds[4] = ImageActor->GetBounds()[4]-(0.9/this->GetInput()->GetSpacing()[2]); + bounds[5] = ImageActor->GetBounds()[5]+(0.9/this->GetInput()->GetSpacing()[2]); + mClipBox->SetBounds(bounds); + UpdateLandmarks(); + } + if (Renderer->GetActiveCamera()->GetPosition()[2] > this->Slice) + mLandActor->SetPosition(0,0,1.5); + else + mLandActor->SetPosition(0,0,-1.5); + } + break; + + case vtkImageViewer2::SLICE_ORIENTATION_XZ: + this->ImageActor->SetDisplayExtent( + w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5]); + if (mVF && mVFActor->GetVisibility()) { + int vfExtent[6]; + ComputeVFDisplayedExtent(w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5],vfExtent); + mVOIFilter->SetVOI(vfExtent); + mGlyphFilter->SetOrientation(1,0,1); + mVFMapper->Update(); + // put the vector field between the image aSpacingnd the camera + if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) + mVFActor->SetPosition(0,ImageActor->GetBounds()[3]+2,0); + else + mVFActor->SetPosition(0,ImageActor->GetBounds()[2]-2,0); + } + if (mOverlay && mOverlayActor->GetVisibility()) { + int overExtent[6]; + ComputeOverlayDisplayedExtent(w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5],overExtent); + mOverlayActor->SetDisplayExtent(overExtent); + if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) + mOverlayActor->SetPosition(0,1,0); + else + mOverlayActor->SetPosition(0,-1,0); + } + if (mFusion && mFusionActor->GetVisibility()) { + int fusExtent[6]; + ComputeFusionDisplayedExtent(w_ext[0], w_ext[1], this->Slice, this->Slice, w_ext[4], w_ext[5],fusExtent); + mFusionActor->SetDisplayExtent(fusExtent); + if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) + mFusionActor->SetPosition(0,1.5,0); + else + mFusionActor->SetPosition(0,-1.5,0); + } + if (mLandActor) { + if (mClipBox) { + double bounds [6]; + bounds[0] = ImageActor->GetBounds()[0]; + bounds[1] = ImageActor->GetBounds()[1]; + bounds[2] = ImageActor->GetBounds()[2]-(0.5/this->GetInput()->GetSpacing()[1]); + bounds[3] = ImageActor->GetBounds()[3]+(0.5/this->GetInput()->GetSpacing()[1]); + bounds[4] = ImageActor->GetBounds()[4]; + bounds[5] = ImageActor->GetBounds()[5]; + mClipBox->SetBounds(bounds); + UpdateLandmarks(); + } + if (Renderer->GetActiveCamera()->GetPosition()[1] > this->Slice) + mLandActor->SetPosition(0,1.5,0); + else + mLandActor->SetPosition(0,-1.5,0); + } + break; + + case vtkImageViewer2::SLICE_ORIENTATION_YZ: + this->ImageActor->SetDisplayExtent( + this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5]); + if (mVF && mVFActor->GetVisibility()) { + int vfExtent[6]; + ComputeVFDisplayedExtent(this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5],vfExtent); + mVOIFilter->SetVOI(vfExtent); + mGlyphFilter->SetOrientation(0,1,1); + mVFMapper->Update(); + // put the vector field between the image and the camera + if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) + mVFActor->SetPosition(ImageActor->GetBounds()[1]+2,0,0); + else + mVFActor->SetPosition(ImageActor->GetBounds()[0]-2,0,0); + } + if (mOverlay && mOverlayActor->GetVisibility()) { + int overExtent[6]; + ComputeOverlayDisplayedExtent(this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5],overExtent); + mOverlayActor->SetDisplayExtent(overExtent); + if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) + mOverlayActor->SetPosition(1,0,0); + else + mOverlayActor->SetPosition(-1,0,0); + } + if (mFusion && mFusionActor->GetVisibility()) { + int fusExtent[6]; + ComputeFusionDisplayedExtent(this->Slice, this->Slice, w_ext[2], w_ext[3], w_ext[4], w_ext[5],fusExtent); + mFusionActor->SetDisplayExtent(fusExtent); + if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) + mFusionActor->SetPosition(1.5,0,0); + else + mFusionActor->SetPosition(-1.5,0,0); + } + if (mLandActor) { + if (mClipBox) { + double bounds [6]; + bounds[0] = ImageActor->GetBounds()[0]-(0.5/this->GetInput()->GetSpacing()[0]); + bounds[1] = ImageActor->GetBounds()[1]+(0.5/this->GetInput()->GetSpacing()[0]); + bounds[2] = ImageActor->GetBounds()[2]; + bounds[3] = ImageActor->GetBounds()[3]; + bounds[4] = ImageActor->GetBounds()[4]; + bounds[5] = ImageActor->GetBounds()[5]; + mClipBox->SetBounds(bounds); + UpdateLandmarks(); + } + if (Renderer->GetActiveCamera()->GetPosition()[0] > this->Slice) + mLandActor->SetPosition(1.5,0,0); + else + mLandActor->SetPosition(-1.5,0,0); + } + break; + } // Figure out the correct clipping range - if (this->Renderer) - { - if (this->InteractorStyle && - this->InteractorStyle->GetAutoAdjustCameraClippingRange()) - { - this->Renderer->ResetCameraClippingRange(); - } - else - { - vtkCamera *cam = this->Renderer->GetActiveCamera(); - if (cam) - { - double bounds[6]; - this->ImageActor->GetBounds(bounds); - double spos = (double)bounds[this->SliceOrientation * 2]; - double cpos = (double)cam->GetPosition()[this->SliceOrientation]; - double range = fabs(spos - cpos); - double *spacing = input->GetSpacing(); - double avg_spacing = - ((double)spacing[0] + (double)spacing[1] + (double)spacing[2]) / 3.0; - cam->SetClippingRange( - range - avg_spacing * 3.0, range + avg_spacing * 3.0); - } - } + if (this->Renderer) { + if (this->InteractorStyle && + this->InteractorStyle->GetAutoAdjustCameraClippingRange()) { + this->Renderer->ResetCameraClippingRange(); + } else { + vtkCamera *cam = this->Renderer->GetActiveCamera(); + if (cam) { + double bounds[6]; + this->ImageActor->GetBounds(bounds); + double spos = (double)bounds[this->SliceOrientation * 2]; + double cpos = (double)cam->GetPosition()[this->SliceOrientation]; + double range = fabs(spos - cpos); + double *spacing = input->GetSpacing(); + double avg_spacing = + ((double)spacing[0] + (double)spacing[1] + (double)spacing[2]) / 3.0; + cam->SetClippingRange( + range - avg_spacing * 3.0, range + avg_spacing * 3.0); + } } + } } //---------------------------------------------------------------------------- @@ -922,17 +884,17 @@ void vvSlicer::ComputeVFDisplayedExtent(int x1,int x2,int y1,int y2,int z1,int z { vtkImageData* image=this->GetInput(); vfExtent[0] = (( image->GetOrigin()[0] + x1*image->GetSpacing()[0] ) - mVF->GetOrigin()[0]) / - mVF->GetSpacing()[0]; + mVF->GetSpacing()[0]; vfExtent[1] = (( image->GetOrigin()[0] + x2*image->GetSpacing()[0] ) - mVF->GetOrigin()[0]) / - mVF->GetSpacing()[0]; + mVF->GetSpacing()[0]; vfExtent[2] = (( image->GetOrigin()[1] + y1*image->GetSpacing()[1] ) - mVF->GetOrigin()[1]) / - mVF->GetSpacing()[1]; + mVF->GetSpacing()[1]; vfExtent[3] = (( image->GetOrigin()[1] + y2*image->GetSpacing()[1] ) - mVF->GetOrigin()[1]) / - mVF->GetSpacing()[1]; + mVF->GetSpacing()[1]; vfExtent[4] = (( image->GetOrigin()[2] + z1*image->GetSpacing()[2] ) - mVF->GetOrigin()[2]) / - mVF->GetSpacing()[2]; + mVF->GetSpacing()[2]; vfExtent[5] = (( image->GetOrigin()[2] + z2*image->GetSpacing()[2] ) - mVF->GetOrigin()[2]) / - mVF->GetSpacing()[2]; + mVF->GetSpacing()[2]; ClipDisplayedExtent(vfExtent,mVOIFilter->GetInput()->GetWholeExtent()); } @@ -944,17 +906,17 @@ void vvSlicer::ComputeOverlayDisplayedExtent(int x1,int x2,int y1,int y2,int z1, { vtkImageData* image=this->GetInput(); overExtent[0] = (( image->GetOrigin()[0] + x1*image->GetSpacing()[0] ) - mOverlay->GetOrigin()[0]) / - mOverlay->GetSpacing()[0]; + mOverlay->GetSpacing()[0]; overExtent[1] = (( image->GetOrigin()[0] + x2*image->GetSpacing()[0] ) - mOverlay->GetOrigin()[0]) / - mOverlay->GetSpacing()[0]; + mOverlay->GetSpacing()[0]; overExtent[2] = (( image->GetOrigin()[1] + y1*image->GetSpacing()[1] ) - mOverlay->GetOrigin()[1]) / - mOverlay->GetSpacing()[1]; + mOverlay->GetSpacing()[1]; overExtent[3] = (( image->GetOrigin()[1] + y2*image->GetSpacing()[1] ) - mOverlay->GetOrigin()[1]) / - mOverlay->GetSpacing()[1]; + mOverlay->GetSpacing()[1]; overExtent[4] = (( image->GetOrigin()[2] + z1*image->GetSpacing()[2] ) - mOverlay->GetOrigin()[2]) / - mOverlay->GetSpacing()[2]; + mOverlay->GetSpacing()[2]; overExtent[5] = (( image->GetOrigin()[2] + z2*image->GetSpacing()[2] ) - mOverlay->GetOrigin()[2]) / - mOverlay->GetSpacing()[2]; + mOverlay->GetSpacing()[2]; ClipDisplayedExtent(overExtent, mOverlayMapper->GetInput()->GetWholeExtent()); } //---------------------------------------------------------------------------- @@ -965,17 +927,17 @@ void vvSlicer::ComputeFusionDisplayedExtent(int x1,int x2,int y1,int y2,int z1,i { vtkImageData* image=this->GetInput(); fusExtent[0] = (( image->GetOrigin()[0] + x1*image->GetSpacing()[0] ) - mFusion->GetOrigin()[0]) / - mFusion->GetSpacing()[0]; + mFusion->GetSpacing()[0]; fusExtent[1] = (( image->GetOrigin()[0] + x2*image->GetSpacing()[0] ) - mFusion->GetOrigin()[0]) / - mFusion->GetSpacing()[0]; + mFusion->GetSpacing()[0]; fusExtent[2] = (( image->GetOrigin()[1] + y1*image->GetSpacing()[1] ) - mFusion->GetOrigin()[1]) / - mFusion->GetSpacing()[1]; + mFusion->GetSpacing()[1]; fusExtent[3] = (( image->GetOrigin()[1] + y2*image->GetSpacing()[1] ) - mFusion->GetOrigin()[1]) / - mFusion->GetSpacing()[1]; + mFusion->GetSpacing()[1]; fusExtent[4] = (( image->GetOrigin()[2] + z1*image->GetSpacing()[2] ) - mFusion->GetOrigin()[2]) / - mFusion->GetSpacing()[2]; + mFusion->GetSpacing()[2]; fusExtent[5] = (( image->GetOrigin()[2] + z2*image->GetSpacing()[2] ) - mFusion->GetOrigin()[2]) / - mFusion->GetSpacing()[2]; + mFusion->GetSpacing()[2]; ClipDisplayedExtent(fusExtent, mFusionMapper->GetInput()->GetWholeExtent()); } //---------------------------------------------------------------------------- @@ -988,33 +950,29 @@ void vvSlicer::ClipDisplayedExtent(int extent[6], int refExtent[6]) int maxBound = 6; //2D overlay on 3D image specific case - if (refExtent[4] == refExtent[5]) - { - maxBound = 4; - extent[4] = refExtent[4]; - extent[5] = refExtent[5]; - } + if (refExtent[4] == refExtent[5]) { + maxBound = 4; + extent[4] = refExtent[4]; + extent[5] = refExtent[5]; + } - for (int i = 0; i < maxBound; i = i+2) - { - //if we are totally outside the image - if ( extent[i] > refExtent[i+1] || extent[i+1] < refExtent[i] ) - { - out = true; - break; - } - //crop to the limit of the image - extent[i] = (extent[i] > refExtent[i]) ? extent[i] : refExtent[i]; - extent[i] = (extent[i] < refExtent[i+1]) ? extent[i] : refExtent[i+1]; - extent[i+1] = (extent[i+1] > refExtent[i]) ? extent[i+1] : refExtent[i]; - extent[i+1] = (extent[i+1] < refExtent[i+1]) ? extent[i+1] : refExtent[i+1]; + for (int i = 0; i < maxBound; i = i+2) { + //if we are totally outside the image + if ( extent[i] > refExtent[i+1] || extent[i+1] < refExtent[i] ) { + out = true; + break; } + //crop to the limit of the image + extent[i] = (extent[i] > refExtent[i]) ? extent[i] : refExtent[i]; + extent[i] = (extent[i] < refExtent[i+1]) ? extent[i] : refExtent[i+1]; + extent[i+1] = (extent[i+1] > refExtent[i]) ? extent[i+1] : refExtent[i]; + extent[i+1] = (extent[i+1] < refExtent[i+1]) ? extent[i+1] : refExtent[i+1]; + } if (out) - for (int i = 0; i < maxBound; i = i+2) - { - extent[i] = refExtent[i]; - extent[i+1] = refExtent[i]; - } + for (int i = 0; i < maxBound; i = i+2) { + extent[i] = refExtent[i]; + extent[i+1] = refExtent[i]; + } } //---------------------------------------------------------------------------- @@ -1024,29 +982,27 @@ void vvSlicer::UpdateOrientation() { // Set the camera position vtkCamera *cam = this->Renderer ? this->Renderer->GetActiveCamera() : NULL; - if (cam) - { - switch (this->SliceOrientation) - { - case vtkImageViewer2::SLICE_ORIENTATION_XY: - cam->SetFocalPoint(0,0,0); - cam->SetPosition(0,0,-1); // -1 if medical ? - cam->SetViewUp(0,-1,0); - break; - - case vtkImageViewer2::SLICE_ORIENTATION_XZ: - cam->SetFocalPoint(0,0,0); - cam->SetPosition(0,-1,0); // 1 if medical ? - cam->SetViewUp(0,0,1); - break; - - case vtkImageViewer2::SLICE_ORIENTATION_YZ: - cam->SetFocalPoint(0,0,0); - cam->SetPosition(-1,0,0); // -1 if medical ? - cam->SetViewUp(0,0,1); - break; - } + if (cam) { + switch (this->SliceOrientation) { + case vtkImageViewer2::SLICE_ORIENTATION_XY: + cam->SetFocalPoint(0,0,0); + cam->SetPosition(0,0,-1); // -1 if medical ? + cam->SetViewUp(0,-1,0); + break; + + case vtkImageViewer2::SLICE_ORIENTATION_XZ: + cam->SetFocalPoint(0,0,0); + cam->SetPosition(0,-1,0); // 1 if medical ? + cam->SetViewUp(0,0,1); + break; + + case vtkImageViewer2::SLICE_ORIENTATION_YZ: + cam->SetFocalPoint(0,0,0); + cam->SetPosition(-1,0,0); // -1 if medical ? + cam->SetViewUp(0,0,1); + break; } + } } //---------------------------------------------------------------------------- @@ -1095,15 +1051,14 @@ void vvSlicer::SetRenderWindow(int orientation, vtkRenderWindow * rw) //---------------------------------------------------------------------------- void vvSlicer::ResetCamera() { - if (this->GetInput()) - { - double* input_bounds=this->GetInput()->GetBounds(); - double bmax=input_bounds[1]-input_bounds[0]; - if (bmax < input_bounds[3]-input_bounds[2]) bmax=input_bounds[3]-input_bounds[2]; - if (bmax < input_bounds[5]-input_bounds[4]) bmax=input_bounds[5]-input_bounds[4]; - this->GetRenderer()->ResetCamera(); - this->GetRenderer()->GetActiveCamera()->SetParallelScale(bmax/2); - } + if (this->GetInput()) { + double* input_bounds=this->GetInput()->GetBounds(); + double bmax=input_bounds[1]-input_bounds[0]; + if (bmax < input_bounds[3]-input_bounds[2]) bmax=input_bounds[3]-input_bounds[2]; + if (bmax < input_bounds[5]-input_bounds[4]) bmax=input_bounds[5]-input_bounds[4]; + this->GetRenderer()->ResetCamera(); + this->GetRenderer()->GetActiveCamera()->SetParallelScale(bmax/2); + } } //---------------------------------------------------------------------------- @@ -1127,26 +1082,24 @@ void vvSlicer::SetDisplayMode(bool i) void vvSlicer::FlipHorizontalView() { vtkCamera *cam = this->Renderer ? this->Renderer->GetActiveCamera() : NULL; - if (cam) - { - double *position = cam->GetPosition(); - switch (this->SliceOrientation) - { - case vtkImageViewer2::SLICE_ORIENTATION_XY: - cam->SetPosition(position[0],position[1],-position[2]); - break; - - case vtkImageViewer2::SLICE_ORIENTATION_XZ: - cam->SetPosition(position[0],-position[1],position[2]); - break; - - case vtkImageViewer2::SLICE_ORIENTATION_YZ: - cam->SetPosition(-position[0],position[1],position[2]); - break; - } - this->Renderer->ResetCameraClippingRange(); - this->UpdateDisplayExtent(); + if (cam) { + double *position = cam->GetPosition(); + switch (this->SliceOrientation) { + case vtkImageViewer2::SLICE_ORIENTATION_XY: + cam->SetPosition(position[0],position[1],-position[2]); + break; + + case vtkImageViewer2::SLICE_ORIENTATION_XZ: + cam->SetPosition(position[0],-position[1],position[2]); + break; + + case vtkImageViewer2::SLICE_ORIENTATION_YZ: + cam->SetPosition(-position[0],position[1],position[2]); + break; } + this->Renderer->ResetCameraClippingRange(); + this->UpdateDisplayExtent(); + } } //---------------------------------------------------------------------------- @@ -1155,13 +1108,12 @@ void vvSlicer::FlipHorizontalView() void vvSlicer::FlipVerticalView() { vtkCamera *cam = this->Renderer ? this->Renderer->GetActiveCamera() : NULL; - if (cam) - { - FlipHorizontalView(); - double *viewup = cam->GetViewUp(); - cam->SetViewUp(-viewup[0],-viewup[1],-viewup[2]); - this->UpdateDisplayExtent(); - } + if (cam) { + FlipHorizontalView(); + double *viewup = cam->GetViewUp(); + cam->SetViewUp(-viewup[0],-viewup[1],-viewup[2]); + this->UpdateDisplayExtent(); + } } //---------------------------------------------------------------------------- @@ -1170,12 +1122,11 @@ void vvSlicer::FlipVerticalView() void vvSlicer::SetColorWindow(double window) { vtkLookupTable* LUT = static_cast(this->GetWindowLevel()->GetLookupTable()); - if ( LUT ) - { - double level = this->GetWindowLevel()->GetLevel(); - LUT->SetTableRange(level-fabs(window)/4,level+fabs(window)/4); - LUT->Build(); - } + if ( LUT ) { + double level = this->GetWindowLevel()->GetLevel(); + LUT->SetTableRange(level-fabs(window)/4,level+fabs(window)/4); + LUT->Build(); + } this->vtkImageViewer2::SetColorWindow(window); } //---------------------------------------------------------------------------- @@ -1185,12 +1136,11 @@ void vvSlicer::SetColorWindow(double window) void vvSlicer::SetColorLevel(double level) { vtkLookupTable* LUT = static_cast(this->GetWindowLevel()->GetLookupTable()); - if ( LUT ) - { - double window = this->GetWindowLevel()->GetWindow(); - LUT->SetTableRange(level-fabs(window)/4,level+fabs(window)/4); - LUT->Build(); - } + if ( LUT ) { + double window = this->GetWindowLevel()->GetWindow(); + LUT->SetTableRange(level-fabs(window)/4,level+fabs(window)/4); + LUT->Build(); + } this->vtkImageViewer2::SetColorLevel(level); } //---------------------------------------------------------------------------- @@ -1201,53 +1151,48 @@ void vvSlicer::GetExtremasAroundMousePointer(double & min, double & max) { //Get mouse pointer position in view coordinates double fLocalExtents[6]; - for(int i=0; i<3; i++) - { - fLocalExtents[i*2 ] = mCurrent[i]; - fLocalExtents[i*2+1] = mCurrent[i]; - } + for(int i=0; i<3; i++) { + fLocalExtents[i*2 ] = mCurrent[i]; + fLocalExtents[i*2+1] = mCurrent[i]; + } this->Renderer->WorldToView(fLocalExtents[0], fLocalExtents[2], fLocalExtents[4]); this->Renderer->WorldToView(fLocalExtents[1], fLocalExtents[3], fLocalExtents[5]); - for(int i=0; i<3; i++) - { - if (i!=SliceOrientation) //SR: assumes that SliceOrientation is valid in ViewCoordinates (???) - { - fLocalExtents[i*2 ] -= 0.2; - fLocalExtents[i*2+1] += 0.2; - } + for(int i=0; i<3; i++) { + if (i!=SliceOrientation) { //SR: assumes that SliceOrientation is valid in ViewCoordinates (???) + fLocalExtents[i*2 ] -= 0.2; + fLocalExtents[i*2+1] += 0.2; } + } this->Renderer->ViewToWorld(fLocalExtents[0], fLocalExtents[2], fLocalExtents[4]); this->Renderer->ViewToWorld(fLocalExtents[1], fLocalExtents[3], fLocalExtents[5]); //Convert to image pixel coordinates (rounded) int iLocalExtents[6]; - for(int i=0; i<3; i++) - { - fLocalExtents[i*2 ] = (fLocalExtents[i*2 ] - this->GetInput()->GetOrigin()[i])/this->GetInput()->GetSpacing()[i]; - fLocalExtents[i*2+1] = (fLocalExtents[i*2+1] - this->GetInput()->GetOrigin()[i])/this->GetInput()->GetSpacing()[i]; - - iLocalExtents[i*2 ] = lrint(fLocalExtents[i*2 ]); - iLocalExtents[i*2+1] = lrint(fLocalExtents[i*2+1]); - - if(iLocalExtents[i*2 ]>iLocalExtents[i*2+1]) - std::swap(iLocalExtents[i*2], iLocalExtents[i*2+1]); - } + for(int i=0; i<3; i++) { + fLocalExtents[i*2 ] = (fLocalExtents[i*2 ] - this->GetInput()->GetOrigin()[i])/this->GetInput()->GetSpacing()[i]; + fLocalExtents[i*2+1] = (fLocalExtents[i*2+1] - this->GetInput()->GetOrigin()[i])/this->GetInput()->GetSpacing()[i]; + + iLocalExtents[i*2 ] = lrint(fLocalExtents[i*2 ]); + iLocalExtents[i*2+1] = lrint(fLocalExtents[i*2+1]); + + if(iLocalExtents[i*2 ]>iLocalExtents[i*2+1]) + std::swap(iLocalExtents[i*2], iLocalExtents[i*2+1]); + } vtkSmartPointer voiFilter = vtkExtractVOI::New(); voiFilter->SetInput(this->GetInput()); voiFilter->SetVOI(iLocalExtents); voiFilter->Update(); - if (!voiFilter->GetOutput()->GetNumberOfPoints()) - { - min = 0; - max = 0; - return; - } + if (!voiFilter->GetOutput()->GetNumberOfPoints()) { + min = 0; + max = 0; + return; + } vtkSmartPointer accFilter = vtkImageAccumulate::New(); accFilter->SetInput(voiFilter->GetOutput()); accFilter->Update(); - + min = *(accFilter->GetMin()); max = *(accFilter->GetMax()); } @@ -1258,90 +1203,82 @@ void vvSlicer::Render() { // DD("vvSlicer::Render"); // DD(SliceOrientation); - if (this->GetWindowLevel()->GetLookupTable() && !this->mOverlay && !this->mFusion) - { - legend->SetLookupTable(this->GetWindowLevel()->GetLookupTable()); - legend->SetVisibility(1); - } - else legend->SetVisibility(0); - - if (ca->GetVisibility()) - { - std::string worldPos = ""; - std::stringstream world1; - std::stringstream world2; - std::stringstream world3; - world1 << (int)mCurrent[0]; - world2 << (int)mCurrent[1]; - world3 << (int)mCurrent[2]; - double X = (mCurrent[0] - this->GetInput()->GetOrigin()[0])/this->GetInput()->GetSpacing()[0]; - double Y = (mCurrent[1] - this->GetInput()->GetOrigin()[1])/this->GetInput()->GetSpacing()[1]; - double Z = (mCurrent[2] - this->GetInput()->GetOrigin()[2])/this->GetInput()->GetSpacing()[2]; - - if (pdmA->GetVisibility()) - { - double x = mCursor[0]; - double y = mCursor[1]; - double z = mCursor[2]; - double xCursor = (x - this->GetInput()->GetOrigin()[0])/this->GetInput()->GetSpacing()[0]; - double yCursor = (y - this->GetInput()->GetOrigin()[1])/this->GetInput()->GetSpacing()[1]; - double zCursor = (z - this->GetInput()->GetOrigin()[2])/this->GetInput()->GetSpacing()[2]; - - if (xCursor >= this->GetImageActor()->GetDisplayExtent()[0] && - xCursor < this->GetImageActor()->GetDisplayExtent()[1]+1 && - yCursor >= this->GetImageActor()->GetDisplayExtent()[2] && - yCursor < this->GetImageActor()->GetDisplayExtent()[3]+1 && - zCursor >= this->GetImageActor()->GetDisplayExtent()[4] && - zCursor < this->GetImageActor()->GetDisplayExtent()[5]+1 ) - { - vtkRenderer * renderer = this->Renderer; - - renderer->WorldToView(x,y,z); - renderer->ViewToNormalizedViewport(x,y,z); - renderer->NormalizedViewportToViewport(x,y); - renderer->ViewportToNormalizedDisplay(x,y); - renderer->NormalizedDisplayToDisplay(x,y); - crossCursor->SetFocalPoint(x,y,z); - } - else - crossCursor->SetFocalPoint(-1,-1,z); - } - - if (X >= this->GetInput()->GetWholeExtent()[0] && - X <= this->GetInput()->GetWholeExtent()[1] && - Y >= this->GetInput()->GetWholeExtent()[2] && - Y <= this->GetInput()->GetWholeExtent()[3] && - Z >= this->GetInput()->GetWholeExtent()[4] && - Z <= this->GetInput()->GetWholeExtent()[5]) - { - std::stringstream pixel1; - std::stringstream pixel2; - std::stringstream pixel3; - std::stringstream temps; - pixel1 << (int)X; - pixel2 << (int)Y; - pixel3 << (int)Z; - temps << mCurrentTSlice; - double value = this->GetInput()->GetScalarComponentAsDouble(lrint(X), - lrint(Y), - lrint(Z),0); - - std::stringstream val; - val << value; - worldPos += "data value : " + val.str(); - worldPos += "\n mm : " + world1.str() + " " + world2.str() + " " + - world3.str() + " " + temps.str(); - worldPos += "\n pixel : " + pixel1.str() + " " + pixel2.str() + " " + - pixel3.str() + " " + temps.str(); - } - ca->SetText(1,worldPos.c_str()); + if (this->GetWindowLevel()->GetLookupTable() && !this->mOverlay && !this->mFusion) { + legend->SetLookupTable(this->GetWindowLevel()->GetLookupTable()); + legend->SetVisibility(1); + } else legend->SetVisibility(0); + + if (ca->GetVisibility()) { + std::string worldPos = ""; + std::stringstream world1; + std::stringstream world2; + std::stringstream world3; + world1 << (int)mCurrent[0]; + world2 << (int)mCurrent[1]; + world3 << (int)mCurrent[2]; + double X = (mCurrent[0] - this->GetInput()->GetOrigin()[0])/this->GetInput()->GetSpacing()[0]; + double Y = (mCurrent[1] - this->GetInput()->GetOrigin()[1])/this->GetInput()->GetSpacing()[1]; + double Z = (mCurrent[2] - this->GetInput()->GetOrigin()[2])/this->GetInput()->GetSpacing()[2]; + + if (pdmA->GetVisibility()) { + double x = mCursor[0]; + double y = mCursor[1]; + double z = mCursor[2]; + double xCursor = (x - this->GetInput()->GetOrigin()[0])/this->GetInput()->GetSpacing()[0]; + double yCursor = (y - this->GetInput()->GetOrigin()[1])/this->GetInput()->GetSpacing()[1]; + double zCursor = (z - this->GetInput()->GetOrigin()[2])/this->GetInput()->GetSpacing()[2]; + + if (xCursor >= this->GetImageActor()->GetDisplayExtent()[0] && + xCursor < this->GetImageActor()->GetDisplayExtent()[1]+1 && + yCursor >= this->GetImageActor()->GetDisplayExtent()[2] && + yCursor < this->GetImageActor()->GetDisplayExtent()[3]+1 && + zCursor >= this->GetImageActor()->GetDisplayExtent()[4] && + zCursor < this->GetImageActor()->GetDisplayExtent()[5]+1 ) { + vtkRenderer * renderer = this->Renderer; + + renderer->WorldToView(x,y,z); + renderer->ViewToNormalizedViewport(x,y,z); + renderer->NormalizedViewportToViewport(x,y); + renderer->ViewportToNormalizedDisplay(x,y); + renderer->NormalizedDisplayToDisplay(x,y); + crossCursor->SetFocalPoint(x,y,z); + } else + crossCursor->SetFocalPoint(-1,-1,z); } - if (mOverlay && mOverlayActor->GetVisibility()) - { - mOverlayMapper->SetWindow(this->GetColorWindow()); - mOverlayMapper->SetLevel(this->GetColorLevel()); - mOverlayMapper->Update(); + + if (X >= this->GetInput()->GetWholeExtent()[0] && + X <= this->GetInput()->GetWholeExtent()[1] && + Y >= this->GetInput()->GetWholeExtent()[2] && + Y <= this->GetInput()->GetWholeExtent()[3] && + Z >= this->GetInput()->GetWholeExtent()[4] && + Z <= this->GetInput()->GetWholeExtent()[5]) { + std::stringstream pixel1; + std::stringstream pixel2; + std::stringstream pixel3; + std::stringstream temps; + pixel1 << (int)X; + pixel2 << (int)Y; + pixel3 << (int)Z; + temps << mCurrentTSlice; + double value = this->GetInput()->GetScalarComponentAsDouble(lrint(X), + lrint(Y), + lrint(Z),0); + + std::stringstream val; + val << value; + worldPos += "data value : " + val.str(); + worldPos += "\n mm : " + world1.str() + " " + world2.str() + " " + + world3.str() + " " + temps.str(); + worldPos += "\n pixel : " + pixel1.str() + " " + pixel2.str() + " " + + pixel3.str() + " " + temps.str(); } + ca->SetText(1,worldPos.c_str()); + } + if (mOverlay && mOverlayActor->GetVisibility()) { + mOverlayMapper->SetWindow(this->GetColorWindow()); + mOverlayMapper->SetLevel(this->GetColorLevel()); + mOverlayMapper->Update(); + } if (mLandMapper) UpdateLandmarks(); //this->Superclass::Render(); @@ -1353,14 +1290,13 @@ void vvSlicer::Render() //---------------------------------------------------------------------------- void vvSlicer::UpdateCursorPosition() { - if (this->GetImageActor()->GetVisibility()) - { - pdmA->SetVisibility(true); - mCursor[0] = mCurrent[0]; - mCursor[1] = mCurrent[1]; - mCursor[2] = mCurrent[2]; - mCursor[3] = mCurrentTSlice; - } + if (this->GetImageActor()->GetVisibility()) { + pdmA->SetVisibility(true); + mCursor[0] = mCurrent[0]; + mCursor[1] = mCurrent[1]; + mCursor[2] = mCurrent[2]; + mCursor[3] = mCurrentTSlice; + } } //---------------------------------------------------------------------------- @@ -1369,16 +1305,15 @@ void vvSlicer::UpdateCursorPosition() void vvSlicer::UpdateLandmarks() { vtkPolyData *pd = static_cast(mLandClipper->GetInput()); - if (pd->GetPoints()) - { - mLandGlyph->SetRange(0,1); - mLandGlyph->Modified(); - mLandGlyph->Update(); - - mClipBox->Modified(); - mLandClipper->Update(); - mLandMapper->Update(); - } + if (pd->GetPoints()) { + mLandGlyph->SetRange(0,1); + mLandGlyph->Modified(); + mLandGlyph->Update(); + + mClipBox->Modified(); + mLandClipper->Update(); + mLandMapper->Update(); + } } //---------------------------------------------------------------------------- @@ -1388,22 +1323,17 @@ void vvSlicer::UpdateLandmarks() void vvSlicer::SetSlice(int slice) { int *range = this->GetSliceRange(); - if (range) - { - if (slice < range[0]) - { - slice = range[0]; - } - else if (slice > range[1]) - { - slice = range[1]; - } + if (range) { + if (slice < range[0]) { + slice = range[0]; + } else if (slice > range[1]) { + slice = range[1]; } + } - if (this->Slice == slice) - { - return; - } + if (this->Slice == slice) { + return; + } this->Slice = slice; SetContourSlice(); @@ -1423,7 +1353,7 @@ void vvSlicer::SetContourSlice() { if (mSurfaceCutActors.size() > 0) for (std::vector::iterator i=mSurfaceCutActors.begin(); - i!=mSurfaceCutActors.end();i++) + i!=mSurfaceCutActors.end(); i++) (*i)->SetCutSlice((this->Slice)*this->GetImage()->GetSpacing()[this->SliceOrientation]+ this->GetImage()->GetOrigin()[this->SliceOrientation]); } @@ -1454,8 +1384,8 @@ void vvSlicer::PrintSelf(ostream& os, vtkIndent indent) //---------------------------------------------------------------------------- - - + + diff --git a/vv/vvSlicerManager.cxx b/vv/vvSlicerManager.cxx index 4ba327b..2bc9810 100644 --- a/vv/vvSlicerManager.cxx +++ b/vv/vvSlicerManager.cxx @@ -1,20 +1,20 @@ - /*========================================================================= - Program: vv http://www.creatis.insa-lyon.fr/rio/vv +/*========================================================================= +Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: - - University of LYON http://www.universite-lyon.fr/ - - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr +Authors belong to: +- University of LYON http://www.universite-lyon.fr/ +- Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr +- CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the copyright notices for more information. +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the copyright notices for more information. - It is distributed under dual licence +It is distributed under dual licence - - BSD See included LICENSE.txt file - - CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html - ======================================================================-====*/ +- BSD See included LICENSE.txt file +- CeCILL-B http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html +======================================================================-====*/ #include "vvSlicerManager.h" #include "vvSlicer.h" @@ -83,27 +83,22 @@ vvSlicerManager::vvSlicerManager(int numberOfSlicers) //---------------------------------------------------------------------------- vvSlicerManager::~vvSlicerManager() { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - if (mSlicers[i] != NULL) - mSlicers[i]->Delete(); - } - if (mReader) - { - delete mReader; - } - if (mVectorReader) - { - delete mVectorReader; - } - if (mOverlayReader) - { - delete mOverlayReader; - } - if (mFusionReader) - { - delete mFusionReader; - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + if (mSlicers[i] != NULL) + mSlicers[i]->Delete(); + } + if (mReader) { + delete mReader; + } + if (mVectorReader) { + delete mVectorReader; + } + if (mOverlayReader) { + delete mOverlayReader; + } + if (mFusionReader) { + delete mFusionReader; + } if (mLandmarks) delete mLandmarks; } @@ -111,7 +106,8 @@ vvSlicerManager::~vvSlicerManager() //------------------------------------------------------------------------------ -void vvSlicerManager::SetFilename(std::string f) { +void vvSlicerManager::SetFilename(std::string f) +{ mFileName = f; for(unsigned int i=0; iSetFileName(f); @@ -123,10 +119,9 @@ void vvSlicerManager::SetFilename(std::string f) { //---------------------------------------------------------------------------- void vvSlicerManager::AddContour(vvMesh::Pointer contour,bool propagate) { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->AddContour(contour,propagate); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->AddContour(contour,propagate); + } } //---------------------------------------------------------------------------- @@ -157,21 +152,17 @@ bool vvSlicerManager::SetImage(std::string filename, LoadedImageType type, int n // DD(mBaseFileName); mBaseFileNameNumber = n; - if (mReader->GetLastError().size() == 0) - { - mImage=mReader->GetOutput(); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetFileName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename)); - mSlicers[i]->SetImage(mReader->GetOutput()); - // DD(mSlicers[i]->GetFileName()); - } - } - else - { - mLastError = mReader->GetLastError(); - return false; + if (mReader->GetLastError().size() == 0) { + mImage=mReader->GetOutput(); + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetFileName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename)); + mSlicers[i]->SetImage(mReader->GetOutput()); + // DD(mSlicers[i]->GetFileName()); } + } else { + mLastError = mReader->GetLastError(); + return false; + } if (n!=0) { // DD(mFileName); mFileName.append("_"+clitk::toString(n)); @@ -185,10 +176,9 @@ bool vvSlicerManager::SetImage(std::string filename, LoadedImageType type, int n void vvSlicerManager::SetImage(vvImage::Pointer image) { mImage=image; - for (unsigned int i = 0; i < mSlicers.size();i++) - { - mSlicers[i]->SetImage(image); - } + for (unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetImage(image); + } } //---------------------------------------------------------------------------- @@ -216,20 +206,16 @@ bool vvSlicerManager::SetImages(std::vector filenames,LoadedImageTy // DD(mBaseFileName); mBaseFileNameNumber = n; - if (mReader->GetLastError().size() == 0) - { - mImage=mReader->GetOutput(); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetFileName(fileWithoutExtension); - mSlicers[i]->SetImage(mReader->GetOutput()); - } - } - else - { - mLastError = mReader->GetLastError(); - return false; + if (mReader->GetLastError().size() == 0) { + mImage=mReader->GetOutput(); + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetFileName(fileWithoutExtension); + mSlicers[i]->SetImage(mReader->GetOutput()); } + } else { + mLastError = mReader->GetLastError(); + return false; + } if (n!=0) { // DD(mFileName); mFileName.append("_"+clitk::toString(n)); @@ -245,29 +231,24 @@ bool vvSlicerManager::SetOverlay(std::string filename,int dim, std::string compo { mOverlayName = filename; mOverlayComponent = component; - if (dim > mImage->GetNumberOfDimensions()) - { - mLastError = " Overlay dimension cannot be greater then reference image!"; - return false; - } + if (dim > mImage->GetNumberOfDimensions()) { + mLastError = " Overlay dimension cannot be greater then reference image!"; + return false; + } if (mOverlayReader == NULL) mOverlayReader = new vvImageReader; std::vector filenames; filenames.push_back(filename); mOverlayReader->SetInputFilenames(filenames); mOverlayReader->Update(mImage->GetNumberOfDimensions(),component.c_str(),mType); - if (mOverlayReader->GetLastError().size() == 0) - { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetOverlay(mOverlayReader->GetOutput()); - } - } - else - { - mLastError = mOverlayReader->GetLastError(); - return false; + if (mOverlayReader->GetLastError().size() == 0) { + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetOverlay(mOverlayReader->GetOutput()); } + } else { + mLastError = mOverlayReader->GetLastError(); + return false; + } return true; } //---------------------------------------------------------------------------- @@ -278,29 +259,24 @@ bool vvSlicerManager::SetFusion(std::string filename,int dim, std::string compon { mFusionName = filename; mFusionComponent = component; - if (dim > mImage->GetNumberOfDimensions()) - { - mLastError = " Overlay dimension cannot be greater then reference image!"; - return false; - } + if (dim > mImage->GetNumberOfDimensions()) { + mLastError = " Overlay dimension cannot be greater then reference image!"; + return false; + } if (mFusionReader == NULL) mFusionReader = new vvImageReader; std::vector filenames; filenames.push_back(filename); mFusionReader->SetInputFilenames(filenames); mFusionReader->Update(mImage->GetNumberOfDimensions(),component.c_str(),mType); - if (mFusionReader->GetLastError().size() == 0) - { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetFusion(mFusionReader->GetOutput()); - } - } - else - { - mLastError = mFusionReader->GetLastError(); - return false; + if (mFusionReader->GetLastError().size() == 0) { + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetFusion(mFusionReader->GetOutput()); } + } else { + mLastError = mFusionReader->GetLastError(); + return false; + } double *fusRange = mFusionReader->GetOutput()->GetVTKImages()[0]->GetScalarRange(); mFusionLevel = (fusRange[0]+fusRange[1])/2; mFusionWindow = fusRange[1]-fusRange[0]; @@ -316,12 +292,10 @@ bool vvSlicerManager::SetVF(std::string filename) mVectorReader = new vvImageReader; mVectorReader->SetInputFilename(filename); mVectorReader->Update(VECTORFIELD); - if (mVectorReader->GetLastError().size() != 0) - { - mLastError = mVectorReader->GetLastError(); - return false; - } - else + if (mVectorReader->GetLastError().size() != 0) { + mLastError = mVectorReader->GetLastError(); + return false; + } else return SetVF(mVectorReader->GetOutput(),filename); } //---------------------------------------------------------------------------- @@ -338,7 +312,7 @@ bool vvSlicerManager::SetVF(vvImage::Pointer vf,std::string filename) // DD(vf->GetSpacing()[3]); // DD(mImage->GetSpacing()[3]); // DD(vf->GetOrigin()[3]); - // DD(mImage->GetOrigin()[3]); + // DD(mImage->GetOrigin()[3]); if (vf->GetSpacing()[3] != mImage->GetSpacing()[3]) { mLastError = "Sorry, vector field time spacing cannot be different from time spacing of the reference image."; return false; @@ -363,31 +337,26 @@ void vvSlicerManager::SetExtractedImage(std::string filename,vvImage::Pointer im { mFileName = filename; mImage = vvImage::New(); - if (image->GetNumberOfDimensions() == 4) - { - mImage->AddImage(image->GetVTKImages()[slice]); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetFileName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename)); - mSlicers[i]->SetImage(mImage); - } + if (image->GetNumberOfDimensions() == 4) { + mImage->AddImage(image->GetVTKImages()[slice]); + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetFileName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename)); + mSlicers[i]->SetImage(mImage); } - else - { - vtkImageClip* clipper = vtkImageClip::New(); - int extent[6]; - image->GetVTKImages()[0]->GetWholeExtent(extent); - clipper->SetInput(image->GetVTKImages()[0]); - clipper->SetOutputWholeExtent(extent[0],extent[1],extent[2],extent[3],slice,slice); - clipper->Update(); - mImage->AddImage(clipper->GetOutput()); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetFileName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename)); - mSlicers[i]->SetImage(mImage); - } - clipper->Delete(); + } else { + vtkImageClip* clipper = vtkImageClip::New(); + int extent[6]; + image->GetVTKImages()[0]->GetWholeExtent(extent); + clipper->SetInput(image->GetVTKImages()[0]); + clipper->SetOutputWholeExtent(extent[0],extent[1],extent[2],extent[3],slice,slice); + clipper->Update(); + mImage->AddImage(clipper->GetOutput()); + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetFileName(vtksys::SystemTools::GetFilenameWithoutLastExtension(filename)); + mSlicers[i]->SetImage(mImage); } + clipper->Delete(); + } } //---------------------------------------------------------------------------- @@ -426,36 +395,37 @@ void vvSlicerManager::SetInteractorStyleNavigator(int i, vtkInteractorStyle* sty mSlicers[i]->GetRenderWindow()->GetInteractor()->SetInteractorStyle(style); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::KeyPressEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::KeyPressEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::WindowLevelEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::WindowLevelEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::EndWindowLevelEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::EndWindowLevelEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::StartWindowLevelEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::StartWindowLevelEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::PickEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::PickEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::StartPickEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::StartPickEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::LeaveEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::LeaveEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::UserEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::UserEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::MouseWheelForwardEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::MouseWheelForwardEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::MouseWheelBackwardEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::MouseWheelBackwardEvent, smc); // mSlicers[i]->GetRenderWindow()->GetInteractor()-> // GetInteractorStyle()->AddObserver(vtkCommand::LeftButtonReleaseEvent, smc); mSlicers[i]->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::EndPickEvent, smc); + GetInteractorStyle()->AddObserver(vtkCommand::EndPickEvent, smc); smc->Delete(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- -void vvSlicerManager::LeftButtonReleaseEvent(int slicer) { +void vvSlicerManager::LeftButtonReleaseEvent(int slicer) +{ emit LeftButtonReleaseSignal(slicer); } //---------------------------------------------------------------------------- @@ -470,14 +440,13 @@ void vvSlicerManager::SetTSlice(int slice) slice = mSlicers[0]->GetTMax(); if (mLandmarks) mLandmarks->SetTime(slice); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - if (slice != mSlicers[i]->GetTSlice()) { - mSlicers[i]->SetTSlice(slice); - if (mSlicers[i]->GetImageActor()->GetVisibility()) - UpdateTSlice(i); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + if (slice != mSlicers[i]->GetTSlice()) { + mSlicers[i]->SetTSlice(slice); + if (mSlicers[i]->GetImageActor()->GetVisibility()) + UpdateTSlice(i); } + } } //---------------------------------------------------------------------------- @@ -513,10 +482,9 @@ void vvSlicerManager::SetPreviousTSlice(int originating_slicer) void vvSlicerManager::ToggleInterpolation() { bool interpolate=!(mSlicers[0]->GetImageActor()->GetInterpolate()); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->GetImageActor()->SetInterpolate(interpolate); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->GetImageActor()->SetInterpolate(interpolate); + } } //---------------------------------------------------------------------------- @@ -543,10 +511,9 @@ void vvSlicerManager::SetTSliceInSlicer(int tslice, int slicer) //---------------------------------------------------------------------------- void vvSlicerManager::SetColorWindow(double s) { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetColorWindow(s); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetColorWindow(s); + } } //---------------------------------------------------------------------------- @@ -554,20 +521,18 @@ void vvSlicerManager::SetColorWindow(double s) //---------------------------------------------------------------------------- void vvSlicerManager::SetColorLevel(double s) { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetColorLevel(s); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetColorLevel(s); + } } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- void vvSlicerManager::SetCursorVisibility(int s) { - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetCursorVisibility(s); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetCursorVisibility(s); + } } //---------------------------------------------------------------------------- @@ -588,97 +553,89 @@ void vvSlicerManager::UpdateViews(int current,int slicer) // DD(slicer); double x = (mSlicers[slicer]->GetCurrentPosition()[0] - mSlicers[slicer]->GetInput()->GetOrigin()[0]) - /mSlicers[slicer]->GetInput()->GetSpacing()[0]; + /mSlicers[slicer]->GetInput()->GetSpacing()[0]; double y = (mSlicers[slicer]->GetCurrentPosition()[1] - mSlicers[slicer]->GetInput()->GetOrigin()[1]) - /mSlicers[slicer]->GetInput()->GetSpacing()[1]; + /mSlicers[slicer]->GetInput()->GetSpacing()[1]; double z = (mSlicers[slicer]->GetCurrentPosition()[2] - mSlicers[slicer]->GetInput()->GetOrigin()[2]) - /mSlicers[slicer]->GetInput()->GetSpacing()[2]; + /mSlicers[slicer]->GetInput()->GetSpacing()[2]; if (x >= mSlicers[slicer]->GetInput()->GetWholeExtent()[0] && x <= mSlicers[slicer]->GetInput()->GetWholeExtent()[1] && y >= mSlicers[slicer]->GetInput()->GetWholeExtent()[2] && y <= mSlicers[slicer]->GetInput()->GetWholeExtent()[3] && z >= mSlicers[slicer]->GetInput()->GetWholeExtent()[4] && - z <= mSlicers[slicer]->GetInput()->GetWholeExtent()[5]) - { - mSlicers[slicer]->UpdateCursorPosition(); - mSlicers[slicer]->SetCursorColor(10,212,255); + z <= mSlicers[slicer]->GetInput()->GetWholeExtent()[5]) { + mSlicers[slicer]->UpdateCursorPosition(); + mSlicers[slicer]->SetCursorColor(10,212,255); + + switch (mSlicers[slicer]->GetSliceOrientation()) { + case vtkImageViewer2::SLICE_ORIENTATION_XY: + if (mSlicers[slicer]->GetSlice() == (int)floor(z)) + mSlicers[slicer]->Render(); + else + mSlicers[slicer]->SetSlice((int)floor(z)); + break; + + case vtkImageViewer2::SLICE_ORIENTATION_XZ: + if (mSlicers[slicer]->GetSlice() == (int)floor(y)) + mSlicers[slicer]->Render(); + else + mSlicers[slicer]->SetSlice((int)floor(y)); + break; - switch (mSlicers[slicer]->GetSliceOrientation()) - { + case vtkImageViewer2::SLICE_ORIENTATION_YZ: + if (mSlicers[slicer]->GetSlice() == (int)floor(x)) + mSlicers[slicer]->Render(); + else + mSlicers[slicer]->SetSlice((int)floor(x)); + break; + } + + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + if (i != (unsigned int)slicer && mSlicers[i]->GetImageActor()->GetVisibility() + && mSlicers[i]->GetRenderWindow()->GetSize()[0] > 2 + && mSlicers[i]->GetRenderWindow()->GetSize()[1] > 2) { + mSlicers[i]->SetCurrentPosition(mSlicers[slicer]->GetCurrentPosition()[0], + mSlicers[slicer]->GetCurrentPosition()[1], + mSlicers[slicer]->GetCurrentPosition()[2], + mSlicers[slicer]->GetTSlice()); + mSlicers[i]->UpdateCursorPosition(); + if (current) { //do not display corner annotation if image is the one picked + mSlicers[i]->SetCurrentPosition(-VTK_DOUBLE_MAX,-VTK_DOUBLE_MAX, + -VTK_DOUBLE_MAX, mSlicers[slicer]->GetTSlice()); + mSlicers[i]->SetCursorColor(255,10,212); + } else { + mSlicers[i]->SetCursorColor(150,10,282); + } + switch (mSlicers[i]->GetSliceOrientation()) { case vtkImageViewer2::SLICE_ORIENTATION_XY: - if (mSlicers[slicer]->GetSlice() == (int)floor(z)) - mSlicers[slicer]->Render(); - else - mSlicers[slicer]->SetSlice((int)floor(z)); - break; + if (mSlicers[i]->GetSlice() == (int)floor(z)) + mSlicers[i]->Render(); + else + mSlicers[i]->SetSlice((int)floor(z)); + break; case vtkImageViewer2::SLICE_ORIENTATION_XZ: - if (mSlicers[slicer]->GetSlice() == (int)floor(y)) - mSlicers[slicer]->Render(); - else - mSlicers[slicer]->SetSlice((int)floor(y)); - break; + if (mSlicers[i]->GetSlice() == (int)floor(y)) + mSlicers[i]->Render(); + else + mSlicers[i]->SetSlice((int)floor(y)); + break; case vtkImageViewer2::SLICE_ORIENTATION_YZ: - if (mSlicers[slicer]->GetSlice() == (int)floor(x)) - mSlicers[slicer]->Render(); - else - mSlicers[slicer]->SetSlice((int)floor(x)); - break; - } - - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - if (i != (unsigned int)slicer && mSlicers[i]->GetImageActor()->GetVisibility() - && mSlicers[i]->GetRenderWindow()->GetSize()[0] > 2 - && mSlicers[i]->GetRenderWindow()->GetSize()[1] > 2) - { - mSlicers[i]->SetCurrentPosition(mSlicers[slicer]->GetCurrentPosition()[0], - mSlicers[slicer]->GetCurrentPosition()[1], - mSlicers[slicer]->GetCurrentPosition()[2], - mSlicers[slicer]->GetTSlice()); - mSlicers[i]->UpdateCursorPosition(); - if (current) //do not display corner annotation if image is the one picked - { - mSlicers[i]->SetCurrentPosition(-VTK_DOUBLE_MAX,-VTK_DOUBLE_MAX, - -VTK_DOUBLE_MAX, mSlicers[slicer]->GetTSlice()); - mSlicers[i]->SetCursorColor(255,10,212); - } - else - { - mSlicers[i]->SetCursorColor(150,10,282); - } - switch (mSlicers[i]->GetSliceOrientation()) - { - case vtkImageViewer2::SLICE_ORIENTATION_XY: - if (mSlicers[i]->GetSlice() == (int)floor(z)) - mSlicers[i]->Render(); - else - mSlicers[i]->SetSlice((int)floor(z)); - break; - - case vtkImageViewer2::SLICE_ORIENTATION_XZ: - if (mSlicers[i]->GetSlice() == (int)floor(y)) - mSlicers[i]->Render(); - else - mSlicers[i]->SetSlice((int)floor(y)); - break; - - case vtkImageViewer2::SLICE_ORIENTATION_YZ: - if (mSlicers[i]->GetSlice() == (int)floor(x)) - mSlicers[i]->Render(); - else - mSlicers[i]->SetSlice((int)floor(x)); - break; - } - // DD("UpdateViews::"); - // DD(i); - UpdateSlice(i); - UpdateTSlice(i); - } + if (mSlicers[i]->GetSlice() == (int)floor(x)) + mSlicers[i]->Render(); + else + mSlicers[i]->SetSlice((int)floor(x)); + break; } + // DD("UpdateViews::"); + // DD(i); + UpdateSlice(i); + UpdateTSlice(i); + } } + } } //---------------------------------------------------------------------------- @@ -687,26 +644,24 @@ void vvSlicerManager::UpdateViews(int current,int slicer) void vvSlicerManager::UpdateLinked(int slicer) { double x = (mSlicers[slicer]->GetCurrentPosition()[0] - mSlicers[slicer]->GetInput()->GetOrigin()[0]) - /mSlicers[slicer]->GetInput()->GetSpacing()[0]; + /mSlicers[slicer]->GetInput()->GetSpacing()[0]; double y = (mSlicers[slicer]->GetCurrentPosition()[1] - mSlicers[slicer]->GetInput()->GetOrigin()[1]) - /mSlicers[slicer]->GetInput()->GetSpacing()[1]; + /mSlicers[slicer]->GetInput()->GetSpacing()[1]; double z = (mSlicers[slicer]->GetCurrentPosition()[2] - mSlicers[slicer]->GetInput()->GetOrigin()[2]) - /mSlicers[slicer]->GetInput()->GetSpacing()[2]; + /mSlicers[slicer]->GetInput()->GetSpacing()[2]; if (x >= mSlicers[slicer]->GetInput()->GetWholeExtent()[0] && x <= mSlicers[slicer]->GetInput()->GetWholeExtent()[1] && y >= mSlicers[slicer]->GetInput()->GetWholeExtent()[2] && y <= mSlicers[slicer]->GetInput()->GetWholeExtent()[3] && z >= mSlicers[slicer]->GetInput()->GetWholeExtent()[4] && - z <= mSlicers[slicer]->GetInput()->GetWholeExtent()[5]) - { - for (std::list::const_iterator i = mLinkedId.begin(); i != mLinkedId.end(); i++) - { - emit UpdateLinkManager(*i, slicer,mSlicers[slicer]->GetCurrentPosition()[0], - mSlicers[slicer]->GetCurrentPosition()[1], - mSlicers[slicer]->GetCurrentPosition()[2],mSlicers[slicer]->GetTSlice()); - } + z <= mSlicers[slicer]->GetInput()->GetWholeExtent()[5]) { + for (std::list::const_iterator i = mLinkedId.begin(); i != mLinkedId.end(); i++) { + emit UpdateLinkManager(*i, slicer,mSlicers[slicer]->GetCurrentPosition()[0], + mSlicers[slicer]->GetCurrentPosition()[1], + mSlicers[slicer]->GetCurrentPosition()[2],mSlicers[slicer]->GetTSlice()); } + } } //---------------------------------------------------------------------------- @@ -735,11 +690,10 @@ double vvSlicerManager::GetColorLevel() void vvSlicerManager::Render() { // DD("vvSlicerManager::Render"); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - // DD(i); - mSlicers[i]->Render(); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + // DD(i); + mSlicers[i]->Render(); + } } //---------------------------------------------------------------------------- @@ -758,10 +712,9 @@ void vvSlicerManager::Reload() { mReader->Update(mType); mImage=mReader->GetOutput(); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetImage(mImage); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetImage(mImage); + } } //---------------------------------------------------------------------------- @@ -770,11 +723,10 @@ void vvSlicerManager::Reload() void vvSlicerManager::ReloadFusion() { mFusionReader->Update(); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetFusion(mFusionReader->GetOutput()); - mSlicers[i]->Render(); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetFusion(mFusionReader->GetOutput()); + mSlicers[i]->Render(); + } } //---------------------------------------------------------------------------- @@ -783,11 +735,10 @@ void vvSlicerManager::ReloadFusion() void vvSlicerManager::ReloadOverlay() { mOverlayReader->Update(); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetOverlay(mOverlayReader->GetOutput()); - mSlicers[i]->Render(); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetOverlay(mOverlayReader->GetOutput()); + mSlicers[i]->Render(); + } } //---------------------------------------------------------------------------- @@ -797,11 +748,10 @@ void vvSlicerManager::ReloadVF() { mVectorReader->Update(VECTORFIELD); //deletes the old images through the VF::Init() function mVF=mVectorReader->GetOutput(); - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetVF(mVF); - mSlicers[i]->Render(); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetVF(mVF); + mSlicers[i]->Render(); + } } //---------------------------------------------------------------------------- @@ -809,18 +759,16 @@ void vvSlicerManager::ReloadVF() //---------------------------------------------------------------------------- void vvSlicerManager::RemoveActor(const std::string& actor_type, int overlay_index) { - for (unsigned int i = 0; i < mSlicers.size();i++) - { - mSlicers[i]->RemoveActor(actor_type,overlay_index); - } - if (actor_type=="vector") - { - mVF=NULL; - if (mVectorReader) { - delete mVectorReader; - mVectorReader=NULL; - } + for (unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->RemoveActor(actor_type,overlay_index); + } + if (actor_type=="vector") { + mVF=NULL; + if (mVectorReader) { + delete mVectorReader; + mVectorReader=NULL; } + } } //---------------------------------------------------------------------------- @@ -829,11 +777,10 @@ void vvSlicerManager::RemoveActor(const std::string& actor_type, int overlay_ind void vvSlicerManager::RemoveActors() { ///This method leaks a few objects. See RemoveActor for what a correct implementation would look like - for ( unsigned int i = 0; i < mSlicers.size(); i++) - { - mSlicers[i]->SetDisplayMode(0); - mSlicers[i]->GetRenderer()->RemoveActor(mSlicers[i]->GetImageActor()); - } + for ( unsigned int i = 0; i < mSlicers.size(); i++) { + mSlicers[i]->SetDisplayMode(0); + mSlicers[i]->GetRenderer()->RemoveActor(mSlicers[i]->GetImageActor()); + } } //---------------------------------------------------------------------------- @@ -847,11 +794,11 @@ void vvSlicerManager::UpdateInfoOnCursorPosition(int slicer) double y = mSlicers[slicer]->GetCursorPosition()[1]; double z = mSlicers[slicer]->GetCursorPosition()[2]; double X = (x - mSlicers[slicer]->GetInput()->GetOrigin()[0])/ - mSlicers[slicer]->GetInput()->GetSpacing()[0]; + mSlicers[slicer]->GetInput()->GetSpacing()[0]; double Y = (y - mSlicers[slicer]->GetInput()->GetOrigin()[1])/ - mSlicers[slicer]->GetInput()->GetSpacing()[1]; + mSlicers[slicer]->GetInput()->GetSpacing()[1]; double Z = (z - mSlicers[slicer]->GetInput()->GetOrigin()[2])/ - mSlicers[slicer]->GetInput()->GetSpacing()[2]; + mSlicers[slicer]->GetInput()->GetSpacing()[2]; double value = -VTK_DOUBLE_MAX; int displayVec = 0; double xVec=0, yVec=0, zVec=0, valueVec=0; @@ -863,93 +810,85 @@ void vvSlicerManager::UpdateInfoOnCursorPosition(int slicer) Y >= mSlicers[slicer]->GetInput()->GetWholeExtent()[2] && Y <= mSlicers[slicer]->GetInput()->GetWholeExtent()[3] && Z >= mSlicers[slicer]->GetInput()->GetWholeExtent()[4] && - Z <= mSlicers[slicer]->GetInput()->GetWholeExtent()[5]) - { - value = mSlicers[slicer]->GetInput()->GetScalarComponentAsDouble( - (int)floor(X), - (int)floor(Y), - (int)floor(Z),0); - if (mSlicers[slicer]->GetVFActor() && mSlicers[slicer]->GetVFActor()->GetVisibility()) - { - displayVec = 1; - unsigned int currentTime = mSlicers[slicer]->GetTSlice(); - vtkImageData *vf = NULL; - - if (mSlicers[slicer]->GetVF()->GetVTKImages().size() > currentTime) - vf = mSlicers[slicer]->GetVF()->GetVTKImages()[currentTime]; - else - vf = mSlicers[slicer]->GetVF()->GetVTKImages()[0]; - - if (vf) - { - double Xvf = (x - vf->GetOrigin()[0])/ vf->GetSpacing()[0]; - double Yvf = (y - vf->GetOrigin()[1])/ vf->GetSpacing()[1]; - double Zvf = (z - vf->GetOrigin()[2])/ vf->GetSpacing()[2]; - xVec = vf->GetScalarComponentAsDouble( (int)floor(Xvf), (int)floor(Yvf), (int)floor(Zvf),0); - yVec = vf->GetScalarComponentAsDouble( (int)floor(Xvf), (int)floor(Yvf), (int)floor(Zvf),1); - zVec = vf->GetScalarComponentAsDouble( (int)floor(Xvf), (int)floor(Yvf), (int)floor(Zvf),2); - valueVec = sqrt(xVec*xVec + yVec*yVec + zVec*zVec); - } - } - if (mSlicers[slicer]->GetOverlayActor() && mSlicers[slicer]->GetOverlayActor()->GetVisibility()) - { - displayOver = 1; - double Xover = (x - mSlicers[slicer]->GetOverlay()->GetOrigin()[0]) - /mSlicers[slicer]->GetOverlay()->GetSpacing()[0]; - double Yover = (y - mSlicers[slicer]->GetOverlay()->GetOrigin()[1]) - /mSlicers[slicer]->GetOverlay()->GetSpacing()[1]; - double Zover = (z - mSlicers[slicer]->GetOverlay()->GetOrigin()[2]) - /mSlicers[slicer]->GetOverlay()->GetSpacing()[2]; - if (Xover >= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[0] && - Xover <= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[1] && - Yover >= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[2] && - Yover <= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[3] && - Zover >= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[4] && - Zover <= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[5]) - { - valueOver = static_cast(mSlicers[slicer]->GetOverlayMapper()->GetInput())-> - GetScalarComponentAsDouble( - (int)floor(Xover), - (int)floor(Yover), - (int)floor(Zover),0); - } - } - if (mSlicers[slicer]->GetFusionActor() && mSlicers[slicer]->GetFusionActor()->GetVisibility()) - { - displayFus = 1; - double Xfus = (x - mSlicers[slicer]->GetFusion()->GetOrigin()[0]) - /mSlicers[slicer]->GetFusion()->GetSpacing()[0]; - double Yfus = (y - mSlicers[slicer]->GetFusion()->GetOrigin()[1]) - /mSlicers[slicer]->GetFusion()->GetSpacing()[1]; - double Zfus = (z - mSlicers[slicer]->GetFusion()->GetOrigin()[2]) - /mSlicers[slicer]->GetFusion()->GetSpacing()[2]; - if (Xfus >= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[0] && - Xfus <= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[1] && - Yfus >= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[2] && - Yfus <= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[3] && - Zfus >= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[4] && - Zfus <= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[5]) - { - valueFus = static_cast(mSlicers[slicer]->GetFusionMapper()->GetInput())-> - GetScalarComponentAsDouble( - (int)floor(Xfus), - (int)floor(Yfus), - (int)floor(Zfus),0); - } - } - emit UpdatePosition(mSlicers[slicer]->GetCursorVisibility(), - x,y,z,X,Y,Z,value); - emit UpdateVector(displayVec,xVec, yVec, zVec, valueVec); - emit UpdateOverlay(displayOver,valueOver,value); - emit UpdateFusion(displayFus,valueFus); - for (unsigned int i = 0; i < mSlicers.size(); i++) - { - if (mSlicers[i]->GetImageActor()->GetVisibility() == 1) - emit UpdateWindows(i,mSlicers[i]->GetSliceOrientation(),mSlicers[i]->GetSlice()); - else - emit UpdateWindows(i,-1,-1); - } + Z <= mSlicers[slicer]->GetInput()->GetWholeExtent()[5]) { + value = mSlicers[slicer]->GetInput()->GetScalarComponentAsDouble( + (int)floor(X), + (int)floor(Y), + (int)floor(Z),0); + if (mSlicers[slicer]->GetVFActor() && mSlicers[slicer]->GetVFActor()->GetVisibility()) { + displayVec = 1; + unsigned int currentTime = mSlicers[slicer]->GetTSlice(); + vtkImageData *vf = NULL; + + if (mSlicers[slicer]->GetVF()->GetVTKImages().size() > currentTime) + vf = mSlicers[slicer]->GetVF()->GetVTKImages()[currentTime]; + else + vf = mSlicers[slicer]->GetVF()->GetVTKImages()[0]; + + if (vf) { + double Xvf = (x - vf->GetOrigin()[0])/ vf->GetSpacing()[0]; + double Yvf = (y - vf->GetOrigin()[1])/ vf->GetSpacing()[1]; + double Zvf = (z - vf->GetOrigin()[2])/ vf->GetSpacing()[2]; + xVec = vf->GetScalarComponentAsDouble( (int)floor(Xvf), (int)floor(Yvf), (int)floor(Zvf),0); + yVec = vf->GetScalarComponentAsDouble( (int)floor(Xvf), (int)floor(Yvf), (int)floor(Zvf),1); + zVec = vf->GetScalarComponentAsDouble( (int)floor(Xvf), (int)floor(Yvf), (int)floor(Zvf),2); + valueVec = sqrt(xVec*xVec + yVec*yVec + zVec*zVec); + } } + if (mSlicers[slicer]->GetOverlayActor() && mSlicers[slicer]->GetOverlayActor()->GetVisibility()) { + displayOver = 1; + double Xover = (x - mSlicers[slicer]->GetOverlay()->GetOrigin()[0]) + /mSlicers[slicer]->GetOverlay()->GetSpacing()[0]; + double Yover = (y - mSlicers[slicer]->GetOverlay()->GetOrigin()[1]) + /mSlicers[slicer]->GetOverlay()->GetSpacing()[1]; + double Zover = (z - mSlicers[slicer]->GetOverlay()->GetOrigin()[2]) + /mSlicers[slicer]->GetOverlay()->GetSpacing()[2]; + if (Xover >= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[0] && + Xover <= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[1] && + Yover >= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[2] && + Yover <= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[3] && + Zover >= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[4] && + Zover <= mSlicers[slicer]->GetOverlayMapper()->GetInput()->GetWholeExtent()[5]) { + valueOver = static_cast(mSlicers[slicer]->GetOverlayMapper()->GetInput())-> + GetScalarComponentAsDouble( + (int)floor(Xover), + (int)floor(Yover), + (int)floor(Zover),0); + } + } + if (mSlicers[slicer]->GetFusionActor() && mSlicers[slicer]->GetFusionActor()->GetVisibility()) { + displayFus = 1; + double Xfus = (x - mSlicers[slicer]->GetFusion()->GetOrigin()[0]) + /mSlicers[slicer]->GetFusion()->GetSpacing()[0]; + double Yfus = (y - mSlicers[slicer]->GetFusion()->GetOrigin()[1]) + /mSlicers[slicer]->GetFusion()->GetSpacing()[1]; + double Zfus = (z - mSlicers[slicer]->GetFusion()->GetOrigin()[2]) + /mSlicers[slicer]->GetFusion()->GetSpacing()[2]; + if (Xfus >= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[0] && + Xfus <= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[1] && + Yfus >= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[2] && + Yfus <= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[3] && + Zfus >= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[4] && + Zfus <= mSlicers[slicer]->GetFusionMapper()->GetInput()->GetWholeExtent()[5]) { + valueFus = static_cast(mSlicers[slicer]->GetFusionMapper()->GetInput())-> + GetScalarComponentAsDouble( + (int)floor(Xfus), + (int)floor(Yfus), + (int)floor(Zfus),0); + } + } + emit UpdatePosition(mSlicers[slicer]->GetCursorVisibility(), + x,y,z,X,Y,Z,value); + emit UpdateVector(displayVec,xVec, yVec, zVec, valueVec); + emit UpdateOverlay(displayOver,valueOver,value); + emit UpdateFusion(displayFus,valueFus); + for (unsigned int i = 0; i < mSlicers.size(); i++) { + if (mSlicers[i]->GetImageActor()->GetVisibility() == 1) + emit UpdateWindows(i,mSlicers[i]->GetSliceOrientation(),mSlicers[i]->GetSlice()); + else + emit UpdateWindows(i,-1,-1); + } + } } //---------------------------------------------------------------------------- @@ -1002,7 +941,7 @@ void vvSlicerManager::UpdateTSlice(int slicer) } mPreviousSlice[slicer] = mSlicers[slicer]->GetSlice(); mPreviousTSlice[slicer] = mSlicers[slicer]->GetTSlice(); - emit UpdateTSlice(slicer,mSlicers[slicer]->GetTSlice()); + emit UpdateTSlice(slicer,mSlicers[slicer]->GetTSlice()); } //---------------------------------------------------------------------------- @@ -1011,8 +950,8 @@ void vvSlicerManager::UpdateTSlice(int slicer) void vvSlicerManager::UpdateSliceRange(int slicer) { emit UpdateSliceRange(slicer, - mSlicers[slicer]->GetSliceRange()[0], mSlicers[slicer]->GetSliceRange()[1], - 0,mSlicers[slicer]->GetTMax()); + mSlicers[slicer]->GetSliceRange()[0], mSlicers[slicer]->GetSliceRange()[1], + 0,mSlicers[slicer]->GetTMax()); } //---------------------------------------------------------------------------- @@ -1025,54 +964,48 @@ void vvSlicerManager::SetPreset(int preset) double level = mSlicers[0]->GetColorLevel(); std::string component_type=mImage->GetScalarTypeAsString(); - switch (preset) - { - case 0: - if (component_type == "unsigned_char") - { - window = 255; - level = 127; - } - else if (component_type == "short") - { - window = 2000; - level = 0; - } - else - { - double range[2]; - mImage->GetScalarRange(range); - window = range[1] - range[0]; - level = (range[1] + range[0])* 0.5; - } - break; - case 1: + switch (preset) { + case 0: + if (component_type == "unsigned_char") { + window = 255; + level = 127; + } else if (component_type == "short") { window = 2000; level = 0; - break; - case 2: - window = 350; - level = 60; - break; - case 3: - window = 1500; - level = -500; - break; - case 4: - window = 1000; - level = 500; - break; - case 5: - window = 1; - level = 0.5; - break; - case 6: - break; - case 7: - window=1.; - level=0.; - break; + } else { + double range[2]; + mImage->GetScalarRange(range); + window = range[1] - range[0]; + level = (range[1] + range[0])* 0.5; } + break; + case 1: + window = 2000; + level = 0; + break; + case 2: + window = 350; + level = 60; + break; + case 3: + window = 1500; + level = -500; + break; + case 4: + window = 1000; + level = 500; + break; + case 5: + window = 1; + level = 0.5; + break; + case 6: + break; + case 7: + window=1.; + level=0.; + break; + } mPreset = preset; this->SetColorWindow(window); this->SetColorLevel(level); @@ -1117,68 +1050,65 @@ void vvSlicerManager::SetColorMap(int colormap) double level = mSlicers[0]->GetWindowLevel()->GetLevel(); vtkLookupTable* LUT = static_cast(mSlicers[0]->GetWindowLevel()->GetLookupTable()); - switch (colormap) - { - case -1: - break; - case 0: - LUT = NULL; - break; - case 1: - if (LUT == NULL) - LUT = vtkLookupTable::New(); - LUT->SetValueRange(0,1); - LUT->SetSaturationRange(1,1); - LUT->SetHueRange(0,0.18); - break; - case 2: - if (LUT == NULL) - LUT = vtkLookupTable::New(); - LUT->SetValueRange(0,1); - LUT->SetSaturationRange(1,1); - LUT->SetHueRange(0.4,0.80); - break; - case 3: - if (LUT == NULL) - LUT = vtkLookupTable::New(); - LUT->SetValueRange(0,1); - LUT->SetSaturationRange(1,1); - LUT->SetHueRange(0,1); - break; - case 5: - if (LUT == NULL) - LUT = vtkLookupTable::New(); - LUT->SetValueRange(0.,1); - LUT->SetSaturationRange(1,1); - LUT->SetHueRange(1,0.1); - //LUT->SetRampToLinear(); - break; - } - if (LUT) - { - LUT->SetTableRange(level-fabs(window)/4,level+fabs(window)/4); - LUT->Build(); - } + switch (colormap) { + case -1: + break; + case 0: + LUT = NULL; + break; + case 1: + if (LUT == NULL) + LUT = vtkLookupTable::New(); + LUT->SetValueRange(0,1); + LUT->SetSaturationRange(1,1); + LUT->SetHueRange(0,0.18); + break; + case 2: + if (LUT == NULL) + LUT = vtkLookupTable::New(); + LUT->SetValueRange(0,1); + LUT->SetSaturationRange(1,1); + LUT->SetHueRange(0.4,0.80); + break; + case 3: + if (LUT == NULL) + LUT = vtkLookupTable::New(); + LUT->SetValueRange(0,1); + LUT->SetSaturationRange(1,1); + LUT->SetHueRange(0,1); + break; + case 5: + if (LUT == NULL) + LUT = vtkLookupTable::New(); + LUT->SetValueRange(0.,1); + LUT->SetSaturationRange(1,1); + LUT->SetHueRange(1,0.1); + //LUT->SetRampToLinear(); + break; + } + if (LUT) { + LUT->SetTableRange(level-fabs(window)/4,level+fabs(window)/4); + LUT->Build(); + } vtkLookupTable* fusLUT = NULL; - if (mSlicers[0]->GetFusion()) - { - fusLUT = vtkLookupTable::New(); - double fusRange [2]; - fusRange[0] = mFusionLevel - mFusionWindow/2; - fusRange[1] = mFusionLevel + mFusionWindow/2; - fusLUT->SetTableRange(fusRange[0],fusRange[1]); - fusLUT->SetValueRange(1,1); - fusLUT->SetSaturationRange(1,1); - if (mFusionColorMap == 1) - fusLUT->SetHueRange(0,0.18); - else if (mFusionColorMap == 2) - fusLUT->SetHueRange(0.4,0.80); - else if (mFusionColorMap == 3) - fusLUT->SetHueRange(0,1); - fusLUT->Build(); - if (mFusionColorMap == 0) - fusLUT = NULL; - } + if (mSlicers[0]->GetFusion()) { + fusLUT = vtkLookupTable::New(); + double fusRange [2]; + fusRange[0] = mFusionLevel - mFusionWindow/2; + fusRange[1] = mFusionLevel + mFusionWindow/2; + fusLUT->SetTableRange(fusRange[0],fusRange[1]); + fusLUT->SetValueRange(1,1); + fusLUT->SetSaturationRange(1,1); + if (mFusionColorMap == 1) + fusLUT->SetHueRange(0,0.18); + else if (mFusionColorMap == 2) + fusLUT->SetHueRange(0.4,0.80); + else if (mFusionColorMap == 3) + fusLUT->SetHueRange(0,1); + fusLUT->Build(); + if (mFusionColorMap == 0) + fusLUT = NULL; + } for ( unsigned int i = 0; i < mSlicers.size(); i++) { if (mSlicers[i]->GetOverlay() && mSlicers[i]->GetOverlayActor()->GetVisibility()) { vtkLookupTable* supLUT = vtkLookupTable::New(); @@ -1194,27 +1124,22 @@ void vvSlicerManager::SetColorMap(int colormap) invLUT->SetHueRange(double((mOverlayColor+180)%360)/360,double((mOverlayColor+180)%360)/360); invLUT->Build(); dynamic_cast(mSlicers[i]->GetWindowLevel()) - ->SetWindowLevelMode(true); + ->SetWindowLevelMode(true); mSlicers[i]->GetWindowLevel()->SetLookupTable(supLUT); mSlicers[i]->GetOverlayMapper()->SetLookupTable(invLUT); invLUT->Delete(); supLUT->Delete(); + } else if (mSlicers[i]->GetOverlay()) { + //dynamic_cast(mSlicers[i]->GetWindowLevel()) + //->SetWindowLevelMode(false); + mSlicers[i]->GetWindowLevel()->SetLookupTable(LUT); + } else { + mSlicers[i]->GetWindowLevel()->SetLookupTable(LUT); + } + if (mSlicers[i]->GetFusion() && mSlicers[i]->GetFusionActor()->GetVisibility()) { + mSlicers[i]->GetFusionActor()->SetOpacity(double(mFusionOpacity)/100); + mSlicers[i]->GetFusionMapper()->SetLookupTable(fusLUT); } - else if (mSlicers[i]->GetOverlay()) - { - //dynamic_cast(mSlicers[i]->GetWindowLevel()) - //->SetWindowLevelMode(false); - mSlicers[i]->GetWindowLevel()->SetLookupTable(LUT); - } - else - { - mSlicers[i]->GetWindowLevel()->SetLookupTable(LUT); - } - if (mSlicers[i]->GetFusion() && mSlicers[i]->GetFusionActor()->GetVisibility()) - { - mSlicers[i]->GetFusionActor()->SetOpacity(double(mFusionOpacity)/100); - mSlicers[i]->GetFusionMapper()->SetLookupTable(fusLUT); - } } if (fusLUT) fusLUT->Delete(); @@ -1227,12 +1152,11 @@ void vvSlicerManager::SetColorMap(int colormap) //---------------------------------------------------------------------------- vvLandmarks* vvSlicerManager::GetLandmarks() { - if (mLandmarks == NULL) - { - mLandmarks = new vvLandmarks(mSlicers[0]->GetTMax()+1); - for (unsigned int i = 0; i < mSlicers.size(); i++) - mSlicers[i]->SetLandmarks(mLandmarks); - } + if (mLandmarks == NULL) { + mLandmarks = new vvLandmarks(mSlicers[0]->GetTMax()+1); + for (unsigned int i = 0; i < mSlicers.size(); i++) + mSlicers[i]->SetLandmarks(mLandmarks); + } return mLandmarks; } //---------------------------------------------------------------------------- @@ -1245,9 +1169,9 @@ void vvSlicerManager::AddLandmark(float x,float y,float z,float t) double y_index = (y - mSlicers[0]->GetInput()->GetOrigin()[1])/mSlicers[0]->GetInput()->GetSpacing()[1]; double z_index = (z - mSlicers[0]->GetInput()->GetOrigin()[2])/mSlicers[0]->GetInput()->GetSpacing()[2]; double value = mSlicers[0]->GetInput()->GetScalarComponentAsDouble( - (int)x_index, - (int)y_index, - (int)z_index,0); + (int)x_index, + (int)y_index, + (int)z_index,0); this->GetLandmarks()->AddLandmark(x,y,z,t,value); emit LandmarkAdded(); } @@ -1270,8 +1194,9 @@ void vvSlicerManager::NextImage(int slicer) //---------------------------------------------------------------------------- -void vvSlicerManager::VerticalSliderHasChanged(int slicer, int slice) { +void vvSlicerManager::VerticalSliderHasChanged(int slicer, int slice) +{ emit AVerticalSliderHasChanged(slicer, slice); } - + //---------------------------------------------------------------------------- diff --git a/vv/vvSlicerManagerCommand.cxx b/vv/vvSlicerManagerCommand.cxx index f29263b..5d25204 100644 --- a/vv/vvSlicerManagerCommand.cxx +++ b/vv/vvSlicerManagerCommand.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -42,8 +42,8 @@ //------------------------------------------------------------------------------ vvSlicerManagerCommand::vvSlicerManagerCommand() { - mStartSlicer = -1; - mSlicerNumber=-1; + mStartSlicer = -1; + mSlicerNumber=-1; } //------------------------------------------------------------------------------ @@ -52,13 +52,13 @@ vvSlicerManagerCommand::vvSlicerManagerCommand() //return the num of the current slicer if visible (-1 else) int vvSlicerManagerCommand::FindSlicerNumber(vtkRenderWindow* renwin) { - int rvalue; - if (renwin != SM->GetSlicer(mSlicerNumber)->GetRenderWindow() || - !SM->GetSlicer(mSlicerNumber)->GetRenderer()->GetDraw()) - rvalue = -1; - else rvalue = mSlicerNumber; - //std::cerr << this << ":" << mSlicerNumber << ": " << rvalue << endl; - return rvalue; + int rvalue; + if (renwin != SM->GetSlicer(mSlicerNumber)->GetRenderWindow() || + !SM->GetSlicer(mSlicerNumber)->GetRenderer()->GetDraw()) + rvalue = -1; + else rvalue = mSlicerNumber; + //std::cerr << this << ":" << mSlicerNumber << ": " << rvalue << endl; + return rvalue; } //------------------------------------------------------------------------------ @@ -68,534 +68,472 @@ void vvSlicerManagerCommand::Execute(vtkObject *caller, unsigned long event, void *vtkNotUsed(callData)) { - //KeyPress event - vvInteractorStyleNavigator *isi = - dynamic_cast(caller); - if (isi) - { - double x = isi->GetInteractor()->GetEventPosition()[0]; - double y = isi->GetInteractor()->GetEventPosition()[1]; - double z; - - int VisibleInWindow = this->FindSlicerNumber(isi->GetInteractor()->GetRenderWindow()); - vtkRenderer* renderer=NULL; - if (VisibleInWindow>-1) - renderer=this->SM->GetSlicer(VisibleInWindow)->GetRenderer(); - newLandmark = false; - - - - if (event == vtkCommand::StartPickEvent && VisibleInWindow == -1) - { - for (int i = 0; i < this->SM->NumberOfSlicers(); i++) - { - if (this->SM->GetSlicer(i)->GetCursorVisibility()) - { - this->SM->GetSlicer(i)->SetCursorVisibility(0); - this->SM->GetSlicer(i)->Render(); - } - } - } - if ( VisibleInWindow > -1 ) - { - if (event == vtkCommand::KeyPressEvent) - { - std::string KeyPress = isi->GetInteractor()->GetKeySym(); - if (KeyPress == "Tab") - { - if(isi->GetInteractor()->GetShiftKey()) - this->SM->PrevImage(VisibleInWindow); - else - this->SM->NextImage(VisibleInWindow); - return; - } - if (KeyPress == "f" || KeyPress == "F") - { - FlyToPosition(isi->GetInteractor(),this->SM->GetSlicer(VisibleInWindow)); - return; - } - if (KeyPress == "w") - { - this->SM->SetLocalColorWindowing(VisibleInWindow); - return; - } - if (KeyPress == "0") - { - this->SM->SetPreset(0); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "1") - { - this->SM->SetPreset(1); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "2") - { - this->SM->SetPreset(2); - this->SM->UpdateWindowLevel(); - - return; - } - if (KeyPress == "3") - { - this->SM->SetPreset(3); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "4") - { - this->SM->SetPreset(4); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "5") - { - this->SM->SetPreset(5); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "6") - { - this->SM->SetColorMap(0); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "7") - { - this->SM->SetColorMap(1); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "8") - { - this->SM->SetColorMap(2); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "9") - { - this->SM->SetColorMap(3); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "equal") //keycodes are in vtkWin32RenderWindowInteractor - { - this->SM->SetPreset(7); - //this->SM->SetColorMap(1); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "minus") - { - this->SM->SetColorWindow(-this->SM->GetColorWindow()); - this->SM->SetColorMap(-1); - this->SM->UpdateWindowLevel(); - return; - } - if (KeyPress == "c") - { - this->SM->ToggleContourSuperposition(); - this->SM->Render(); - return; - } - if (KeyPress == "l") - { - this->SM->ToggleInterpolation(); - this->SM->Render(); - return; - } - if (KeyPress == "h") - { - this->SM->SetCursorVisibility(0); - this->SM->Render(); - return; - } - if (KeyPress == "u") - { - this->SM->Reload(); - this->SM->Render(); - return; - } - if (KeyPress == "r" || KeyPress=="R") - { - this->SM->GetSlicer(VisibleInWindow)->ResetCamera(); - this->SM->GetSlicer(VisibleInWindow)->Render(); - return; - } - if (KeyPress == "g") - { - double* cursorPos = this->SM->GetSlicer(VisibleInWindow)->GetCursorPosition(); - this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition( - cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]); - this->SM->UpdateViews(1,VisibleInWindow); - this->SM->UpdateLinked(VisibleInWindow); - return; - } - if (KeyPress == "F5") - { - this->SM->GetSlicer(VisibleInWindow)->FlipHorizontalView(); - this->SM->GetSlicer(VisibleInWindow)->Render(); - return; - } - if (KeyPress == "F6") - { - this->SM->GetSlicer(VisibleInWindow)->FlipVerticalView(); - this->SM->GetSlicer(VisibleInWindow)->Render(); - return; - } - if (KeyPress == "Up") - { - DD("------------ up"); - this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()+1); - DD("------------ after set slice"); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - DD("------------ after UpdateInfoOnCursorPosition"); - this->SM->UpdateSlice(VisibleInWindow); - DD("------------ after updateslice"); - } - if (KeyPress == "Down") - { - this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()-1); - this->SM->UpdateSlice(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - if (KeyPress == "space") - { - newLandmark = true; - } - if (KeyPress == "Left") - this->SM->SetPreviousTSlice(VisibleInWindow); - if (KeyPress == "Right") - this->SM->SetNextTSlice(VisibleInWindow); - - if (KeyPress == "F2") - { - this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetText(2,"Sagital\n"); - this->SM->GetSlicer(VisibleInWindow)->SetSliceOrientation(0); - this->SM->UpdateSliceRange(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - if (KeyPress == "F3") - { - this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetText(2,"Coronal\n"); - this->SM->GetSlicer(VisibleInWindow)->SetSliceOrientation(1); - this->SM->UpdateSliceRange(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - if (KeyPress == "F4") - { - this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetText(2,"Axial\n"); - this->SM->GetSlicer(VisibleInWindow)->SetSliceOrientation(2); - this->SM->UpdateSliceRange(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - - } - - //All type of mouse events - if (event == vtkCommand::LeaveEvent) - { - this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition(-VTK_DOUBLE_MAX,-VTK_DOUBLE_MAX, - -VTK_DOUBLE_MAX,this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); - this->SM->GetSlicer(VisibleInWindow)->Render(); - return; - } - - //DD(event); - // Mouse release HERE - if (event == vtkCommand::EndPickEvent) { - // DD(VisibleInWindow); - if (VisibleInWindow > -1) - this->SM->LeftButtonReleaseEvent(VisibleInWindow); - return; // no return !!!! ??? - } - - if (event == vtkCommand::StartWindowLevelEvent) - { - mStartSlicer = -1; - this->InitialWindow = this->SM->GetColorWindow(); - this->InitialLevel = this->SM->GetColorLevel(); - - if (VisibleInWindow > -1) - { - mStartSlicer = VisibleInWindow; - } - return; - } - - if (event == vtkCommand::EndWindowLevelEvent) - { - mStartSlicer = -1; - } + //KeyPress event + vvInteractorStyleNavigator *isi = + dynamic_cast(caller); + if (isi) { + double x = isi->GetInteractor()->GetEventPosition()[0]; + double y = isi->GetInteractor()->GetEventPosition()[1]; + double z; + + int VisibleInWindow = this->FindSlicerNumber(isi->GetInteractor()->GetRenderWindow()); + vtkRenderer* renderer=NULL; + if (VisibleInWindow>-1) + renderer=this->SM->GetSlicer(VisibleInWindow)->GetRenderer(); + newLandmark = false; + + + if (event == vtkCommand::StartPickEvent && VisibleInWindow == -1) { + for (int i = 0; i < this->SM->NumberOfSlicers(); i++) { + if (this->SM->GetSlicer(i)->GetCursorVisibility()) { + this->SM->GetSlicer(i)->SetCursorVisibility(0); + this->SM->GetSlicer(i)->Render(); } - if (VisibleInWindow > -1) - { - this->SM->Activated(); - //if(!this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->GetVisibility()) - this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetVisibility(1); - - if (event == vtkCommand::MouseWheelForwardEvent && !isi->GetInteractor()->GetControlKey()) - { - this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()+1); - this->SM->UpdateSlice(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - else if (event == vtkCommand::MouseWheelForwardEvent && isi->GetInteractor()->GetControlKey()) - { - double factor = 2; - this->Dolly(pow((double)1.1, factor),isi->GetInteractor()); - } - else if (event == vtkCommand::MouseWheelBackwardEvent && !isi->GetInteractor()->GetControlKey()) - { - this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()-1); - this->SM->UpdateSlice(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - else if (event == vtkCommand::MouseWheelBackwardEvent && isi->GetInteractor()->GetControlKey()) - { - double factor = -2; - this->Dolly(pow((double)1.1, factor),isi->GetInteractor()); - } - double xWorld=0; double yWorld=0; double zWorld=0; - - //Move into World Coordinate - renderer->DisplayToNormalizedDisplay(x,y); - renderer->NormalizedDisplayToViewport(x,y); - renderer->ViewportToNormalizedViewport(x,y); - renderer->NormalizedViewportToView(x,y,z); - renderer->ViewToWorld(x,y,z); - switch (this->SM->GetSlicer(VisibleInWindow)->GetSliceOrientation()) - { - case vtkImageViewer2::SLICE_ORIENTATION_XY: - xWorld = x; - yWorld = y; - zWorld = this->SM->GetSlicer(VisibleInWindow)->GetSlice()* - this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetSpacing()[2] + - this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetOrigin()[2]; - break; - - case vtkImageViewer2::SLICE_ORIENTATION_XZ: - xWorld = x; - yWorld = this->SM->GetSlicer(VisibleInWindow)->GetSlice()* - this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetSpacing()[1] + - this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetOrigin()[1]; - zWorld = z; - break; - - case vtkImageViewer2::SLICE_ORIENTATION_YZ: - xWorld = this->SM->GetSlicer(VisibleInWindow)->GetSlice()* - this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetSpacing()[0] + - this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetOrigin()[0]; - yWorld = y; - zWorld = z; - break; - } - this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition(xWorld,yWorld,zWorld, - this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); - if (newLandmark) - { - this->SM->AddLandmark(xWorld,yWorld,zWorld, - this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); - this->SM->GetSlicer(VisibleInWindow)->UpdateLandmarks(); - this->SM->Render(); - } - if (event == vtkCommand::PickEvent || event == vtkCommand::StartPickEvent) - { - this->SM->UpdateViews(1,VisibleInWindow); - this->SM->UpdateLinked(VisibleInWindow); - this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); - } - else - { - this->SM->GetSlicer(VisibleInWindow)->Render(); - } - //this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition(-VTK_DOUBLE_MAX,-VTK_DOUBLE_MAX, - //-VTK_DOUBLE_MAX,this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); - //this->SM->GetSlicer(VisibleInWindow)->Render(); + } + } + if ( VisibleInWindow > -1 ) { + if (event == vtkCommand::KeyPressEvent) { + std::string KeyPress = isi->GetInteractor()->GetKeySym(); + if (KeyPress == "Tab") { + if(isi->GetInteractor()->GetShiftKey()) + this->SM->PrevImage(VisibleInWindow); + else + this->SM->NextImage(VisibleInWindow); + return; + } + if (KeyPress == "f" || KeyPress == "F") { + FlyToPosition(isi->GetInteractor(),this->SM->GetSlicer(VisibleInWindow)); + return; } + if (KeyPress == "w") { + this->SM->SetLocalColorWindowing(VisibleInWindow); + return; + } + if (KeyPress == "0") { + this->SM->SetPreset(0); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "1") { + this->SM->SetPreset(1); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "2") { + this->SM->SetPreset(2); + this->SM->UpdateWindowLevel(); - if (event == vtkCommand::WindowLevelEvent && mStartSlicer > -1) - { - this->SM->GetSlicer(mStartSlicer)->GetAnnotation()->SetVisibility(1); - // Adjust the window level here - int *size = isi->GetInteractor()->GetRenderWindow()->GetSize(); - double window = this->InitialWindow; - double level = this->InitialLevel; - double range[2]; - this->SM->GetImage()->GetScalarRange(range); - - // Compute normalized delta - double dx = static_cast(isi->GetWindowLevelCurrentPosition()[0] - - isi->GetWindowLevelStartPosition()[0]) / size[0]; - double dy = static_cast(isi->GetWindowLevelStartPosition()[1] - - isi->GetWindowLevelCurrentPosition()[1]) / size[1]; - //Window is exponential in nature, use exponential to avoid falling into negative numbers - dx = std::exp(1.0 * (dx*fabs(dx) + dx)) ; //Quadratic behavior for more reactive interface - dy = 0.15 * (dy*fabs(dy) + dy) * (range[1]-range[0]);//Quadratic behavior for more reactive interface - - this->SM->SetColorWindow(window*dx); - this->SM->SetColorLevel(level-dy); - this->SM->SetPreset(6); - this->SM->UpdateWindowLevel(); - this->SM->Render(); - return; + return; + } + if (KeyPress == "3") { + this->SM->SetPreset(3); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "4") { + this->SM->SetPreset(4); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "5") { + this->SM->SetPreset(5); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "6") { + this->SM->SetColorMap(0); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "7") { + this->SM->SetColorMap(1); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "8") { + this->SM->SetColorMap(2); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "9") { + this->SM->SetColorMap(3); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "equal") { //keycodes are in vtkWin32RenderWindowInteractor + this->SM->SetPreset(7); + //this->SM->SetColorMap(1); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "minus") { + this->SM->SetColorWindow(-this->SM->GetColorWindow()); + this->SM->SetColorMap(-1); + this->SM->UpdateWindowLevel(); + return; + } + if (KeyPress == "c") { + this->SM->ToggleContourSuperposition(); + this->SM->Render(); + return; + } + if (KeyPress == "l") { + this->SM->ToggleInterpolation(); + this->SM->Render(); + return; + } + if (KeyPress == "h") { + this->SM->SetCursorVisibility(0); + this->SM->Render(); + return; + } + if (KeyPress == "u") { + this->SM->Reload(); + this->SM->Render(); + return; + } + if (KeyPress == "r" || KeyPress=="R") { + this->SM->GetSlicer(VisibleInWindow)->ResetCamera(); + this->SM->GetSlicer(VisibleInWindow)->Render(); + return; + } + if (KeyPress == "g") { + double* cursorPos = this->SM->GetSlicer(VisibleInWindow)->GetCursorPosition(); + this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition( + cursorPos[0],cursorPos[1],cursorPos[2],cursorPos[3]); + this->SM->UpdateViews(1,VisibleInWindow); + this->SM->UpdateLinked(VisibleInWindow); + return; + } + if (KeyPress == "F5") { + this->SM->GetSlicer(VisibleInWindow)->FlipHorizontalView(); + this->SM->GetSlicer(VisibleInWindow)->Render(); + return; + } + if (KeyPress == "F6") { + this->SM->GetSlicer(VisibleInWindow)->FlipVerticalView(); + this->SM->GetSlicer(VisibleInWindow)->Render(); + return; + } + if (KeyPress == "Up") { + DD("------------ up"); + this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()+1); + DD("------------ after set slice"); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + DD("------------ after UpdateInfoOnCursorPosition"); + this->SM->UpdateSlice(VisibleInWindow); + DD("------------ after updateslice"); + } + if (KeyPress == "Down") { + this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()-1); + this->SM->UpdateSlice(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + } + if (KeyPress == "space") { + newLandmark = true; + } + if (KeyPress == "Left") + this->SM->SetPreviousTSlice(VisibleInWindow); + if (KeyPress == "Right") + this->SM->SetNextTSlice(VisibleInWindow); + + if (KeyPress == "F2") { + this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetText(2,"Sagital\n"); + this->SM->GetSlicer(VisibleInWindow)->SetSliceOrientation(0); + this->SM->UpdateSliceRange(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + } + if (KeyPress == "F3") { + this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetText(2,"Coronal\n"); + this->SM->GetSlicer(VisibleInWindow)->SetSliceOrientation(1); + this->SM->UpdateSliceRange(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + } + if (KeyPress == "F4") { + this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetText(2,"Axial\n"); + this->SM->GetSlicer(VisibleInWindow)->SetSliceOrientation(2); + this->SM->UpdateSliceRange(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); } - } -} -//------------------------------------------------------------------------------ + } -//------------------------------------------------------------------------------ -void vvSlicerManagerCommand::Dolly(double factor, vtkRenderWindowInteractor *interactor) -{ - int VisibleInWindow = this->FindSlicerNumber(interactor->GetRenderWindow()); - vtkRenderer* renderer; - if (VisibleInWindow>-1) - renderer=this->SM->GetSlicer(VisibleInWindow)->GetRenderer(); - else - { + //All type of mouse events + if (event == vtkCommand::LeaveEvent) { + this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition(-VTK_DOUBLE_MAX,-VTK_DOUBLE_MAX, + -VTK_DOUBLE_MAX,this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); + this->SM->GetSlicer(VisibleInWindow)->Render(); return; - } + } + + //DD(event); + // Mouse release HERE + if (event == vtkCommand::EndPickEvent) { + // DD(VisibleInWindow); + if (VisibleInWindow > -1) + this->SM->LeftButtonReleaseEvent(VisibleInWindow); + return; // no return !!!! ??? + } + + if (event == vtkCommand::StartWindowLevelEvent) { + mStartSlicer = -1; + this->InitialWindow = this->SM->GetColorWindow(); + this->InitialLevel = this->SM->GetColorLevel(); + + if (VisibleInWindow > -1) { + mStartSlicer = VisibleInWindow; + } + return; + } + + if (event == vtkCommand::EndWindowLevelEvent) { + mStartSlicer = -1; + } - double viewFocus[4],viewPoint[4],motionVector[3], focalDepth; - double oldPos[3], newPos[3], distance[2]; - vtkCamera *camera = renderer->GetActiveCamera(); - camera->GetFocalPoint(viewFocus); - - renderer->SetWorldPoint(viewFocus[0], viewFocus[0], viewFocus[0], 1.0); - renderer->WorldToDisplay(); - renderer->GetDisplayPoint(viewFocus); - - focalDepth = viewFocus[2]; - - oldPos[0] = renderer->GetCenter()[0]; - oldPos[1] = renderer->GetCenter()[1]; - oldPos[2] = focalDepth; - - distance[0] = 1/factor* - (interactor->GetEventPosition()[0]-renderer->GetCenter()[0]); - distance[1] = 1/factor* - (interactor->GetEventPosition()[1]-renderer->GetCenter()[1]); - - newPos[0] = interactor->GetEventPosition()[0] - distance[0]; - newPos[1] = interactor->GetEventPosition()[1] - distance[1]; - newPos[2] = focalDepth; - - renderer->DisplayToNormalizedDisplay(oldPos[0],oldPos[1]); - renderer->NormalizedDisplayToViewport(oldPos[0],oldPos[1]); - renderer->ViewportToNormalizedViewport(oldPos[0],oldPos[1]); - renderer->NormalizedViewportToView(oldPos[0],oldPos[1],oldPos[2]); - renderer->ViewToWorld(oldPos[0],oldPos[1],oldPos[2]); - - renderer->DisplayToNormalizedDisplay(newPos[0],newPos[1]); - renderer->NormalizedDisplayToViewport(newPos[0],newPos[1]); - renderer->ViewportToNormalizedViewport(newPos[0],newPos[1]); - renderer->NormalizedViewportToView(newPos[0],newPos[1],newPos[2]); - renderer->ViewToWorld(newPos[0],newPos[1],newPos[2]); - - motionVector[0] = newPos[0] - oldPos[0]; - motionVector[1] = newPos[1] - oldPos[1]; - motionVector[2] = newPos[2] - oldPos[2]; - - camera->GetFocalPoint(viewFocus); - camera->GetPosition(viewPoint); - camera->SetFocalPoint(motionVector[0] + viewFocus[0], - motionVector[1] + viewFocus[1], - motionVector[2] + viewFocus[2]); - - camera->SetPosition(motionVector[0] + viewPoint[0], - motionVector[1] + viewPoint[1], - motionVector[2] + viewPoint[2]); - - if (camera->GetParallelProjection()) - { - camera->SetParallelScale(camera->GetParallelScale() / factor); } - else - { - camera->Dolly(factor); + if (VisibleInWindow > -1) { + this->SM->Activated(); + //if(!this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->GetVisibility()) + this->SM->GetSlicer(VisibleInWindow)->GetAnnotation()->SetVisibility(1); + + if (event == vtkCommand::MouseWheelForwardEvent && !isi->GetInteractor()->GetControlKey()) { + this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()+1); + this->SM->UpdateSlice(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + } else if (event == vtkCommand::MouseWheelForwardEvent && isi->GetInteractor()->GetControlKey()) { + double factor = 2; + this->Dolly(pow((double)1.1, factor),isi->GetInteractor()); + } else if (event == vtkCommand::MouseWheelBackwardEvent && !isi->GetInteractor()->GetControlKey()) { + this->SM->GetSlicer(VisibleInWindow)->SetSlice(this->SM->GetSlicer(VisibleInWindow)->GetSlice()-1); + this->SM->UpdateSlice(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + } else if (event == vtkCommand::MouseWheelBackwardEvent && isi->GetInteractor()->GetControlKey()) { + double factor = -2; + this->Dolly(pow((double)1.1, factor),isi->GetInteractor()); + } + double xWorld=0; + double yWorld=0; + double zWorld=0; + + //Move into World Coordinate + renderer->DisplayToNormalizedDisplay(x,y); + renderer->NormalizedDisplayToViewport(x,y); + renderer->ViewportToNormalizedViewport(x,y); + renderer->NormalizedViewportToView(x,y,z); + renderer->ViewToWorld(x,y,z); + switch (this->SM->GetSlicer(VisibleInWindow)->GetSliceOrientation()) { + case vtkImageViewer2::SLICE_ORIENTATION_XY: + xWorld = x; + yWorld = y; + zWorld = this->SM->GetSlicer(VisibleInWindow)->GetSlice()* + this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetSpacing()[2] + + this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetOrigin()[2]; + break; + + case vtkImageViewer2::SLICE_ORIENTATION_XZ: + xWorld = x; + yWorld = this->SM->GetSlicer(VisibleInWindow)->GetSlice()* + this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetSpacing()[1] + + this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetOrigin()[1]; + zWorld = z; + break; + + case vtkImageViewer2::SLICE_ORIENTATION_YZ: + xWorld = this->SM->GetSlicer(VisibleInWindow)->GetSlice()* + this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetSpacing()[0] + + this->SM->GetSlicer(VisibleInWindow)->GetInput()->GetOrigin()[0]; + yWorld = y; + zWorld = z; + break; + } + this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition(xWorld,yWorld,zWorld, + this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); + if (newLandmark) { + this->SM->AddLandmark(xWorld,yWorld,zWorld, + this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); + this->SM->GetSlicer(VisibleInWindow)->UpdateLandmarks(); + this->SM->Render(); + } + if (event == vtkCommand::PickEvent || event == vtkCommand::StartPickEvent) { + this->SM->UpdateViews(1,VisibleInWindow); + this->SM->UpdateLinked(VisibleInWindow); + this->SM->UpdateInfoOnCursorPosition(VisibleInWindow); + } else { + this->SM->GetSlicer(VisibleInWindow)->Render(); + } + //this->SM->GetSlicer(VisibleInWindow)->SetCurrentPosition(-VTK_DOUBLE_MAX,-VTK_DOUBLE_MAX, + //-VTK_DOUBLE_MAX,this->SM->GetSlicer(VisibleInWindow)->GetTSlice()); + //this->SM->GetSlicer(VisibleInWindow)->Render(); } - if (interactor->GetLightFollowCamera()) - { - renderer->UpdateLightsGeometryToFollowCamera(); + if (event == vtkCommand::WindowLevelEvent && mStartSlicer > -1) { + this->SM->GetSlicer(mStartSlicer)->GetAnnotation()->SetVisibility(1); + // Adjust the window level here + int *size = isi->GetInteractor()->GetRenderWindow()->GetSize(); + double window = this->InitialWindow; + double level = this->InitialLevel; + double range[2]; + this->SM->GetImage()->GetScalarRange(range); + + // Compute normalized delta + double dx = static_cast(isi->GetWindowLevelCurrentPosition()[0] - + isi->GetWindowLevelStartPosition()[0]) / size[0]; + double dy = static_cast(isi->GetWindowLevelStartPosition()[1] - + isi->GetWindowLevelCurrentPosition()[1]) / size[1]; + //Window is exponential in nature, use exponential to avoid falling into negative numbers + dx = std::exp(1.0 * (dx*fabs(dx) + dx)) ; //Quadratic behavior for more reactive interface + dy = 0.15 * (dy*fabs(dy) + dy) * (range[1]-range[0]);//Quadratic behavior for more reactive interface + + this->SM->SetColorWindow(window*dx); + this->SM->SetColorLevel(level-dy); + this->SM->SetPreset(6); + this->SM->UpdateWindowLevel(); + this->SM->Render(); + return; } - renderer->ResetCameraClippingRange(); - //interactor->Render(); + } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvSlicerManagerCommand::FlyToPosition(vtkRenderWindowInteractor *interactor,vvSlicer* slicer) +void vvSlicerManagerCommand::Dolly(double factor, vtkRenderWindowInteractor *interactor) { - double flyFrom[3], flyTo[3]; - double d[3], focalPt[3], position[3], positionFrom[3]; - int i, j; - int VisibleInWindow = this->FindSlicerNumber(interactor->GetRenderWindow()); - vtkRenderer* renderer=NULL; - if (VisibleInWindow>-1) - renderer=this->SM->GetSlicer(VisibleInWindow)->GetRenderer(); - else - return; + int VisibleInWindow = this->FindSlicerNumber(interactor->GetRenderWindow()); + vtkRenderer* renderer; + if (VisibleInWindow>-1) + renderer=this->SM->GetSlicer(VisibleInWindow)->GetRenderer(); + else { + return; + } + + double viewFocus[4],viewPoint[4],motionVector[3], focalDepth; + double oldPos[3], newPos[3], distance[2]; + vtkCamera *camera = renderer->GetActiveCamera(); + camera->GetFocalPoint(viewFocus); + + renderer->SetWorldPoint(viewFocus[0], viewFocus[0], viewFocus[0], 1.0); + renderer->WorldToDisplay(); + renderer->GetDisplayPoint(viewFocus); + + focalDepth = viewFocus[2]; + + oldPos[0] = renderer->GetCenter()[0]; + oldPos[1] = renderer->GetCenter()[1]; + oldPos[2] = focalDepth; + + distance[0] = 1/factor* + (interactor->GetEventPosition()[0]-renderer->GetCenter()[0]); + distance[1] = 1/factor* + (interactor->GetEventPosition()[1]-renderer->GetCenter()[1]); + + newPos[0] = interactor->GetEventPosition()[0] - distance[0]; + newPos[1] = interactor->GetEventPosition()[1] - distance[1]; + newPos[2] = focalDepth; + + renderer->DisplayToNormalizedDisplay(oldPos[0],oldPos[1]); + renderer->NormalizedDisplayToViewport(oldPos[0],oldPos[1]); + renderer->ViewportToNormalizedViewport(oldPos[0],oldPos[1]); + renderer->NormalizedViewportToView(oldPos[0],oldPos[1],oldPos[2]); + renderer->ViewToWorld(oldPos[0],oldPos[1],oldPos[2]); + + renderer->DisplayToNormalizedDisplay(newPos[0],newPos[1]); + renderer->NormalizedDisplayToViewport(newPos[0],newPos[1]); + renderer->ViewportToNormalizedViewport(newPos[0],newPos[1]); + renderer->NormalizedViewportToView(newPos[0],newPos[1],newPos[2]); + renderer->ViewToWorld(newPos[0],newPos[1],newPos[2]); + + motionVector[0] = newPos[0] - oldPos[0]; + motionVector[1] = newPos[1] - oldPos[1]; + motionVector[2] = newPos[2] - oldPos[2]; + + camera->GetFocalPoint(viewFocus); + camera->GetPosition(viewPoint); + camera->SetFocalPoint(motionVector[0] + viewFocus[0], + motionVector[1] + viewFocus[1], + motionVector[2] + viewFocus[2]); + + camera->SetPosition(motionVector[0] + viewPoint[0], + motionVector[1] + viewPoint[1], + motionVector[2] + viewPoint[2]); + + if (camera->GetParallelProjection()) { + camera->SetParallelScale(camera->GetParallelScale() / factor); + } else { + camera->Dolly(factor); + } + + if (interactor->GetLightFollowCamera()) { + renderer->UpdateLightsGeometryToFollowCamera(); + } + renderer->ResetCameraClippingRange(); + //interactor->Render(); +} +//------------------------------------------------------------------------------ - interactor->GetPicker()->Pick(interactor->GetEventPosition()[0], - interactor->GetEventPosition()[1], 0.0, - renderer); - vtkAssemblyPath *path=NULL; - vtkAbstractPropPicker *picker; - if ( (picker=vtkAbstractPropPicker::SafeDownCast(interactor->GetPicker()))) - { - path = picker->GetPath(); +//------------------------------------------------------------------------------ +void vvSlicerManagerCommand::FlyToPosition(vtkRenderWindowInteractor *interactor,vvSlicer* slicer) +{ + double flyFrom[3], flyTo[3]; + double d[3], focalPt[3], position[3], positionFrom[3]; + int i, j; + int VisibleInWindow = this->FindSlicerNumber(interactor->GetRenderWindow()); + vtkRenderer* renderer=NULL; + if (VisibleInWindow>-1) + renderer=this->SM->GetSlicer(VisibleInWindow)->GetRenderer(); + else + return; + + interactor->GetPicker()->Pick(interactor->GetEventPosition()[0], + interactor->GetEventPosition()[1], 0.0, + renderer); + + vtkAssemblyPath *path=NULL; + vtkAbstractPropPicker *picker; + if ( (picker=vtkAbstractPropPicker::SafeDownCast(interactor->GetPicker()))) { + path = picker->GetPath(); + } + if ( path != NULL ) { + flyTo[0] = picker->GetPickPosition()[0]; + flyTo[1] = picker->GetPickPosition()[1]; + flyTo[2] = picker->GetPickPosition()[2]; + renderer->GetActiveCamera()->GetFocalPoint(flyFrom); + renderer->GetActiveCamera()->GetPosition(positionFrom); + + switch (slicer->GetSliceOrientation()) { + case vtkImageViewer2::SLICE_ORIENTATION_XY: + flyTo[2] = flyFrom[2]; + break; + + case vtkImageViewer2::SLICE_ORIENTATION_XZ: + flyTo[1] = flyFrom[1]; + break; + + case vtkImageViewer2::SLICE_ORIENTATION_YZ: + flyTo[0] = flyFrom[0]; + break; } - if ( path != NULL ) - { - flyTo[0] = picker->GetPickPosition()[0]; - flyTo[1] = picker->GetPickPosition()[1]; - flyTo[2] = picker->GetPickPosition()[2]; - renderer->GetActiveCamera()->GetFocalPoint(flyFrom); - renderer->GetActiveCamera()->GetPosition(positionFrom); - - switch (slicer->GetSliceOrientation()) - { - case vtkImageViewer2::SLICE_ORIENTATION_XY: - flyTo[2] = flyFrom[2]; - break; - - case vtkImageViewer2::SLICE_ORIENTATION_XZ: - flyTo[1] = flyFrom[1]; - break; - - case vtkImageViewer2::SLICE_ORIENTATION_YZ: - flyTo[0] = flyFrom[0]; - break; - } - for (i=0; i<3; i++) - { - d[i] = flyTo[i] - flyFrom[i]; - } - double distance = vtkMath::Normalize(d); - double delta = distance/15; - - for (i=1; i<=15; i++) - { - for (j=0; j<3; j++) - { - focalPt[j] = flyFrom[j] + d[j]*i*delta; - position[j] = positionFrom[j] + d[j]*i*delta; - } - renderer->GetActiveCamera()->SetFocalPoint(focalPt); - renderer->GetActiveCamera()->SetPosition(position); - renderer->GetActiveCamera()->Dolly(0.3/15 + 1.0); - renderer->ResetCameraClippingRange(); - interactor->Render(); - } + for (i=0; i<3; i++) { + d[i] = flyTo[i] - flyFrom[i]; + } + double distance = vtkMath::Normalize(d); + double delta = distance/15; + + for (i=1; i<=15; i++) { + for (j=0; j<3; j++) { + focalPt[j] = flyFrom[j] + d[j]*i*delta; + position[j] = positionFrom[j] + d[j]*i*delta; + } + renderer->GetActiveCamera()->SetFocalPoint(focalPt); + renderer->GetActiveCamera()->SetPosition(position); + renderer->GetActiveCamera()->Dolly(0.3/15 + 1.0); + renderer->ResetCameraClippingRange(); + interactor->Render(); } + } } //------------------------------------------------------------------------------ diff --git a/vv/vvStructSelector.cxx b/vv/vvStructSelector.cxx index 17af30a..08dd794 100644 --- a/vv/vvStructSelector.cxx +++ b/vv/vvStructSelector.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -21,28 +21,26 @@ void vvStructSelector::SetStructures(StructureType structures) { - mStructures=structures; - for (StructureType::iterator i=structures.begin();i!=structures.end();i++) - { - std::ostringstream ss; - ss << (*i).first << ":" << (*i).second; - this->structSelectionWidget->addItem(ss.str().c_str()); - } + mStructures=structures; + for (StructureType::iterator i=structures.begin(); i!=structures.end(); i++) { + std::ostringstream ss; + ss << (*i).first << ":" << (*i).second; + this->structSelectionWidget->addItem(ss.str().c_str()); + } } std::vector vvStructSelector::getSelectedItems() { - std::vector result; - for (int i=0;icount();i++) - { - if (structSelectionWidget->item(i)->isSelected()) - result.push_back(mStructures[i].first); - } - return result; + std::vector result; + for (int i=0; icount(); i++) { + if (structSelectionWidget->item(i)->isSelected()) + result.push_back(mStructures[i].first); + } + return result; } vvStructSelector::vvStructSelector() { - setupUi(this); + setupUi(this); } diff --git a/vv/vvStructureSetActor.cxx b/vv/vvStructureSetActor.cxx index 7ea1ef9..ce0060d 100644 --- a/vv/vvStructureSetActor.cxx +++ b/vv/vvStructureSetActor.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -20,37 +20,42 @@ #include "vvROIActor.h" //------------------------------------------------------------------------------ -vvStructureSetActor::vvStructureSetActor() { +vvStructureSetActor::vvStructureSetActor() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vvStructureSetActor::~vvStructureSetActor() { +vvStructureSetActor::~vvStructureSetActor() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvStructureSetActor::SetStructureSet(clitk::DicomRT_StructureSet * s) { +void vvStructureSetActor::SetStructureSet(clitk::DicomRT_StructureSet * s) +{ mStructureSet = s; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvStructureSetActor::SetSlicerManager(vvSlicerManager * s) { +void vvStructureSetActor::SetSlicerManager(vvSlicerManager * s) +{ mSlicerManager = s; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vvROIActor * vvStructureSetActor::GetROIActor(int n) { +vvROIActor * vvStructureSetActor::GetROIActor(int n) +{ if (mMapROIIndex.find(n) == mMapROIIndex.end()) { std::cerr << "No ROI number " << n << std::endl; - return NULL; + return NULL; } return mROIActors[mMapROIIndex[n]]; } @@ -58,7 +63,8 @@ vvROIActor * vvStructureSetActor::GetROIActor(int n) { //------------------------------------------------------------------------------ -void vvStructureSetActor::CreateNewROIActor(int n) { +void vvStructureSetActor::CreateNewROIActor(int n) +{ // Check clitk::DicomRT_ROI * roi = mStructureSet->GetROI(n); if (roi == NULL) { diff --git a/vv/vvSurfaceViewerDialog.cxx b/vv/vvSurfaceViewerDialog.cxx index 2a8ee9e..d39ad25 100644 --- a/vv/vvSurfaceViewerDialog.cxx +++ b/vv/vvSurfaceViewerDialog.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -38,128 +38,121 @@ class vvManagerCallback : public vtkCommand { public: - static vvManagerCallback *New() { - return new vvManagerCallback; + static vvManagerCallback *New() { + return new vvManagerCallback; + } + + void Execute(vtkObject *caller, + unsigned long event, + void *vtkNotUsed(callData)) { + vtkInteractorStyle *isi = static_cast(caller); + if (isi) { + std::string KeyPress = isi->GetInteractor()->GetKeySym(); + if (KeyPress == "Left") { + this->IV->PreviousTime(); + } + if (KeyPress == "Right") { + this->IV->NextTime(); + } } - - void Execute(vtkObject *caller, - unsigned long event, - void *vtkNotUsed(callData)) - { - vtkInteractorStyle *isi = static_cast(caller); - if (isi) - { - std::string KeyPress = isi->GetInteractor()->GetKeySym(); - if (KeyPress == "Left") - { - this->IV->PreviousTime(); - } - if (KeyPress == "Right") - { - this->IV->NextTime(); - } - } - } - vvSurfaceViewerDialog *IV; + } + vvSurfaceViewerDialog *IV; }; //==================================================================== vvSurfaceViewerDialog::vvSurfaceViewerDialog(QWidget * parent, Qt::WindowFlags f) - :QDialog(parent,f), Ui::vvSurfaceViewerDialog() { + :QDialog(parent,f), Ui::vvSurfaceViewerDialog() +{ - // initialization - setupUi(this); + // initialization + setupUi(this); - mReaders.clear(); - mMapper = NULL; - mActor = NULL; - mRenderer = NULL; - mCurrentTime = 0; + mReaders.clear(); + mMapper = NULL; + mActor = NULL; + mRenderer = NULL; + mCurrentTime = 0; - connect(loadButton,SIGNAL(clicked()),this,SLOT(LoadSurface())); + connect(loadButton,SIGNAL(clicked()),this,SLOT(LoadSurface())); } vvSurfaceViewerDialog::~vvSurfaceViewerDialog() { - for (unsigned int i = 0; i < mReaders.size();i++) - mReaders[i]->Delete(); + for (unsigned int i = 0; i < mReaders.size(); i++) + mReaders[i]->Delete(); - if (mMapper) - mMapper->Delete(); + if (mMapper) + mMapper->Delete(); - if (mActor) - mActor->Delete(); + if (mActor) + mActor->Delete(); - if (mRenderer) - mRenderer->Delete(); + if (mRenderer) + mRenderer->Delete(); } void vvSurfaceViewerDialog::LoadSurface() { - QString Extensions = "All Files (*)"; - Extensions += ";;Surface ( *.vtk)"; - QStringList files = QFileDialog::getOpenFileNames(this,tr("Load Surfaces"),tr(""),Extensions); - if (files.isEmpty()) - return; - - if (!mMapper) - { - mMapper = vtkPolyDataMapper::New(); - } - - for (int i = 0; i < files.size(); i++) - { - vtkOBJReader* reader = vtkOBJReader::New(); - reader->SetFileName(files[i].toStdString().c_str()); - reader->Update(); - mReaders.push_back(reader); - } - - mMapper->SetInput(mReaders[mCurrentTime]->GetOutput()); - - if (!mActor) - { - mActor = vtkActor::New(); - mActor->SetMapper(mMapper); - } - if (!mRenderer) - { - mRenderer = vtkRenderer::New(); - mRenderer->AddActor(mActor); - renderWidget->GetRenderWindow()->AddRenderer(mRenderer); - } - - mRenderer->ResetCamera(); - renderWidget->GetRenderWindow()->Render(); - - vvManagerCallback *smc = vvManagerCallback::New(); - smc->IV = this; - - if (renderWidget->GetRenderWindow()->GetInteractor()) - renderWidget->GetRenderWindow()->GetInteractor()-> - GetInteractorStyle()->AddObserver(vtkCommand::KeyPressEvent, smc); - //readHeader->Delete(); + QString Extensions = "All Files (*)"; + Extensions += ";;Surface ( *.vtk)"; + QStringList files = QFileDialog::getOpenFileNames(this,tr("Load Surfaces"),tr(""),Extensions); + if (files.isEmpty()) + return; + + if (!mMapper) { + mMapper = vtkPolyDataMapper::New(); + } + + for (int i = 0; i < files.size(); i++) { + vtkOBJReader* reader = vtkOBJReader::New(); + reader->SetFileName(files[i].toStdString().c_str()); + reader->Update(); + mReaders.push_back(reader); + } + + mMapper->SetInput(mReaders[mCurrentTime]->GetOutput()); + + if (!mActor) { + mActor = vtkActor::New(); + mActor->SetMapper(mMapper); + } + if (!mRenderer) { + mRenderer = vtkRenderer::New(); + mRenderer->AddActor(mActor); + renderWidget->GetRenderWindow()->AddRenderer(mRenderer); + } + + mRenderer->ResetCamera(); + renderWidget->GetRenderWindow()->Render(); + + vvManagerCallback *smc = vvManagerCallback::New(); + smc->IV = this; + + if (renderWidget->GetRenderWindow()->GetInteractor()) + renderWidget->GetRenderWindow()->GetInteractor()-> + GetInteractorStyle()->AddObserver(vtkCommand::KeyPressEvent, smc); + //readHeader->Delete(); } void vvSurfaceViewerDialog::NextTime() { - mCurrentTime++; - if (mCurrentTime >= mReaders.size()) - mCurrentTime = 0; - mMapper->SetInput(mReaders[mCurrentTime]->GetOutput()); - mMapper->Modified(); - renderWidget->GetRenderWindow()->Render(); + mCurrentTime++; + if (mCurrentTime >= mReaders.size()) + mCurrentTime = 0; + mMapper->SetInput(mReaders[mCurrentTime]->GetOutput()); + mMapper->Modified(); + renderWidget->GetRenderWindow()->Render(); } void vvSurfaceViewerDialog::PreviousTime() { - mCurrentTime--; - if (mCurrentTime < 0) - mCurrentTime = mReaders.size() - 1; - mMapper->SetInput(mReaders[mCurrentTime]->GetOutput()); - mMapper->Modified(); - renderWidget->GetRenderWindow()->Render(); + mCurrentTime--; + if (mCurrentTime < 0) + mCurrentTime = mReaders.size() - 1; + mMapper->SetInput(mReaders[mCurrentTime]->GetOutput()); + mMapper->Modified(); + renderWidget->GetRenderWindow()->Render(); } #endif /* end #define _vvSurfaceViewerDialog_CXX */ diff --git a/vv/vvTemplateFile.cxx b/vv/vvTemplateFile.cxx index 3a17c01..83ccf58 100644 --- a/vv/vvTemplateFile.cxx +++ b/vv/vvTemplateFile.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr diff --git a/vv/vvToolBase.cxx b/vv/vvToolBase.cxx index c8ea311..e9e442b 100644 --- a/vv/vvToolBase.cxx +++ b/vv/vvToolBase.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr diff --git a/vv/vvToolBase.txx b/vv/vvToolBase.txx index 7e1ac30..1e3de99 100644 --- a/vv/vvToolBase.txx +++ b/vv/vvToolBase.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,19 +17,21 @@ ======================================================================-====*/ template -vvToolBase::vvToolBase(vvMainWindowBase * m) { - mMainWindowBase = m; +vvToolBase::vvToolBase(vvMainWindowBase * m) +{ + mMainWindowBase = m; } //------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // Default value (to be overwritten) template -void vvToolBase::Initialize() { +void vvToolBase::Initialize() +{ SetToolName("Unnamed tool (use SetToolName in Initialize())"); SetToolMenuName("Unnamed tool"); SetToolIconFilename(""); SetToolTip("Unamed tool."); } -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ diff --git a/vv/vvToolBinarize.cxx b/vv/vvToolBinarize.cxx index 6d85154..6821ba2 100644 --- a/vv/vvToolBinarize.cxx +++ b/vv/vvToolBinarize.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -36,7 +36,8 @@ ADD_TOOL(vvToolBinarize); //------------------------------------------------------------------------------ -void vvToolBinarize::Initialize() { +void vvToolBinarize::Initialize() +{ SetToolName("Binarize"); SetToolMenuName("Binarize"); SetToolIconFilename(":/common/icons/binarize.png"); @@ -47,15 +48,15 @@ void vvToolBinarize::Initialize() { //------------------------------------------------------------------------------ vvToolBinarize::vvToolBinarize(vvMainWindowBase * parent, Qt::WindowFlags f) - :vvToolWidgetBase(parent,f), - vvToolBase(parent), - Ui::vvToolBinarize() + :vvToolWidgetBase(parent,f), + vvToolBase(parent), + Ui::vvToolBinarize() { // GUI Initialization Ui_vvToolBinarize::setupUi(mToolWidget); mInteractiveDisplayIsEnabled = mCheckBoxInteractiveDisplay->isChecked(); - // Connect signals & slots + // Connect signals & slots connect(mRadioButtonLowerThan, SIGNAL(toggled(bool)), this, SLOT(enableLowerThan(bool))); connect(mCheckBoxUseFG, SIGNAL(toggled(bool)), this, SLOT(useFGBGtoggled(bool))); connect(mCheckBoxUseBG, SIGNAL(toggled(bool)), this, SLOT(useFGBGtoggled(bool))); @@ -67,7 +68,7 @@ vvToolBinarize::vvToolBinarize(vvMainWindowBase * parent, Qt::WindowFlags f) mFGSlider->SetText("Foreground value"); mBGSlider->SetText("Background value"); - // Main filter + // Main filter mFilter = new clitk::BinarizeImageGenericFilter; // Set how many inputs are needed for this tool @@ -77,18 +78,19 @@ vvToolBinarize::vvToolBinarize(vvMainWindowBase * parent, Qt::WindowFlags f) //------------------------------------------------------------------------------ -vvToolBinarize::~vvToolBinarize() { +vvToolBinarize::~vvToolBinarize() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolBinarize::InteractiveDisplayToggled(bool b) { +void vvToolBinarize::InteractiveDisplayToggled(bool b) +{ mInteractiveDisplayIsEnabled = b; if (!mInteractiveDisplayIsEnabled) { RemoveVTKObjects(); - } - else { + } else { for(unsigned int i=0; ishowActors(); if (mRadioButtonLowerThan->isChecked()) @@ -102,10 +104,11 @@ void vvToolBinarize::InteractiveDisplayToggled(bool b) { //------------------------------------------------------------------------------ -void vvToolBinarize::RemoveVTKObjects() { +void vvToolBinarize::RemoveVTKObjects() +{ for(unsigned int i=0; ihideActors(); - mImageContourLower[i]->hideActors(); + mImageContourLower[i]->hideActors(); } if (mCurrentSlicerManager) mCurrentSlicerManager->Render(); @@ -114,36 +117,38 @@ void vvToolBinarize::RemoveVTKObjects() { //------------------------------------------------------------------------------ -bool vvToolBinarize::close() { +bool vvToolBinarize::close() +{ RemoveVTKObjects(); - return vvToolWidgetBase::close(); + return vvToolWidgetBase::close(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolBinarize::reject() { +void vvToolBinarize::reject() +{ // DD("vvToolBinarize::reject"); RemoveVTKObjects(); - return vvToolWidgetBase::reject(); + return vvToolWidgetBase::reject(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolBinarize::enableLowerThan(bool b) { +void vvToolBinarize::enableLowerThan(bool b) +{ if (!b) { mThresholdSlider1->resetMaximum(); for(unsigned int i=0; ihideActors(); + mImageContourLower[i]->hideActors(); } mCurrentSlicerManager->Render(); - } - else { + } else { valueChangedT1(mThresholdSlider1->GetValue()); valueChangedT2(mThresholdSlider2->GetValue()); for(unsigned int i=0; ishowActors(); + mImageContourLower[i]->showActors(); } mCurrentSlicerManager->Render(); } @@ -152,8 +157,9 @@ void vvToolBinarize::enableLowerThan(bool b) { //------------------------------------------------------------------------------ -void vvToolBinarize::useFGBGtoggled(bool) { - if (!mCheckBoxUseBG->isChecked() && !mCheckBoxUseFG->isChecked()) +void vvToolBinarize::useFGBGtoggled(bool) +{ + if (!mCheckBoxUseBG->isChecked() && !mCheckBoxUseFG->isChecked()) mCheckBoxUseBG->toggle(); } //------------------------------------------------------------------------------ @@ -164,7 +170,8 @@ void vvToolBinarize::useFGBGtoggled(bool) { // DD("vvToolBinarize::InputIsSelected vector in binarize"); // DD(m.size()); // } -void vvToolBinarize::InputIsSelected(vvSlicerManager * m) { +void vvToolBinarize::InputIsSelected(vvSlicerManager * m) +{ mCurrentSlicerManager = m; // Specific for this gui @@ -175,7 +182,7 @@ void vvToolBinarize::InputIsSelected(vvSlicerManager * m) { mFGSlider->SetImage(mCurrentImage); mBGSlider->SetImage(mCurrentImage); // DD(mCurrentSlicerManager->GetFileName().c_str()); - // mFGSlider->SetMaximum(mCurrentImage->GetFirstVTKImageData()->GetScalarTypeMax()); +// mFGSlider->SetMaximum(mCurrentImage->GetFirstVTKImageData()->GetScalarTypeMax()); // mFGSlider->SetMinimum(mCurrentImage->GetFirstVTKImageData()->GetScalarTypeMin()); // mBGSlider->SetMaximum(mCurrentImage->GetFirstVTKImageData()->GetScalarTypeMax()); // mBGSlider->SetMinimum(mCurrentImage->GetFirstVTKImageData()->GetScalarTypeMin()); @@ -190,9 +197,9 @@ void vvToolBinarize::InputIsSelected(vvSlicerManager * m) { mBGSlider->SetValue(0); mFGSlider->SetSingleStep(1); mBGSlider->SetSingleStep(1); - + // VTK objects for interactive display - for(int i=0;iNumberOfSlicers(); i++) { + for(int i=0; iNumberOfSlicers(); i++) { mImageContour.push_back(new vvImageContour); mImageContour[i]->setSlicer(mCurrentSlicerManager->GetSlicer(i)); mImageContour[i]->setColor(1.0, 0.0, 0.0); @@ -225,19 +232,21 @@ void vvToolBinarize::InputIsSelected(vvSlicerManager * m) { //------------------------------------------------------------------------------ -void vvToolBinarize::UpdateSlice(int slicer,int slices) { +void vvToolBinarize::UpdateSlice(int slicer,int slices) +{ if (!mInteractiveDisplayIsEnabled) return; if (!mCurrentSlicerManager) close(); mImageContour[slicer]->update(mThresholdSlider1->GetValue()); - if (mRadioButtonLowerThan->isChecked()) + if (mRadioButtonLowerThan->isChecked()) mImageContourLower[slicer]->update(mThresholdSlider2->GetValue()); - // mCurrentSlicerManager->GetSlicer(slicer)->Render(); + // mCurrentSlicerManager->GetSlicer(slicer)->Render(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolBinarize::GetArgsInfoFromGUI() { +void vvToolBinarize::GetArgsInfoFromGUI() +{ /* //KEEP THIS FOR READING GGO FROM FILE int argc=1; @@ -280,15 +289,14 @@ void vvToolBinarize::GetArgsInfoFromGUI() { if (mCheckBoxUseBG->isChecked()) { if (mCheckBoxUseFG->isChecked()) mArgsInfo.mode_arg = (char*)"both"; else mArgsInfo.mode_arg = (char*)"BG"; - } - else mArgsInfo.mode_arg = (char*)"FG"; + } else mArgsInfo.mode_arg = (char*)"FG"; mArgsInfo.verbose_flag = false; // Required (even if not used) mArgsInfo.input_given = 0; mArgsInfo.output_given = 0; - + mArgsInfo.input_arg = new char; mArgsInfo.output_arg = new char; } @@ -296,14 +304,15 @@ void vvToolBinarize::GetArgsInfoFromGUI() { //------------------------------------------------------------------------------ -void vvToolBinarize::apply() { +void vvToolBinarize::apply() +{ if (!mCurrentSlicerManager) close(); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); GetArgsInfoFromGUI(); // Main filter - clitk::BinarizeImageGenericFilter::Pointer filter = - clitk::BinarizeImageGenericFilter::New(); + clitk::BinarizeImageGenericFilter::Pointer filter = + clitk::BinarizeImageGenericFilter::New(); filter->SetInputVVImage(mCurrentImage); filter->SetArgsInfo(mArgsInfo); filter->EnableReadOnDisk(false); @@ -313,7 +322,7 @@ void vvToolBinarize::apply() { vvImage::Pointer output = filter->GetOutputVVImage(); std::ostringstream osstream; osstream << "Binarized_" << mCurrentSlicerManager->GetSlicer(0)->GetFileName() << ".mhd"; - AddImage(output,osstream.str()); + AddImage(output,osstream.str()); QApplication::restoreOverrideCursor(); close(); } @@ -321,12 +330,13 @@ void vvToolBinarize::apply() { //------------------------------------------------------------------------------ -void vvToolBinarize::valueChangedT2(double v) { +void vvToolBinarize::valueChangedT2(double v) +{ // DD("valueChangedT2"); if (mRadioButtonLowerThan->isChecked()) { mThresholdSlider1->SetMaximum(v); if (!mInteractiveDisplayIsEnabled) return; - for(int i=0;iNumberOfSlicers(); i++) { + for(int i=0; iNumberOfSlicers(); i++) { mImageContourLower[i]->update(v); } // mCurrentSlicerManager->Render(); @@ -336,13 +346,14 @@ void vvToolBinarize::valueChangedT2(double v) { //------------------------------------------------------------------------------ -void vvToolBinarize::valueChangedT1(double v) { +void vvToolBinarize::valueChangedT1(double v) +{ // DD("valueChangedT1"); if (!mCurrentSlicerManager) close(); mThresholdSlider2->SetMinimum(v); - // int m1 = (int)lrint(v); + // int m1 = (int)lrint(v); if (!mInteractiveDisplayIsEnabled) return; - for(int i=0;iNumberOfSlicers(); i++) { + for(int i=0; iNumberOfSlicers(); i++) { mImageContour[i]->update(v); } // mCurrentSlicerManager->Render(); diff --git a/vv/vvToolConvert.cxx b/vv/vvToolConvert.cxx index d63a4ea..af68500 100644 --- a/vv/vvToolConvert.cxx +++ b/vv/vvToolConvert.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -45,18 +45,20 @@ vvToolConvert::vvToolConvert(vvMainWindowBase * parent, Qt::WindowFlags f): //------------------------------------------------------------------------------ -vvToolConvert::~vvToolConvert() { +vvToolConvert::~vvToolConvert() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolConvert::Initialize() { +void vvToolConvert::Initialize() +{ SetToolName("Convert"); SetToolMenuName("Convert with WidgetBase"); SetToolIconFilename(":/common/icons/ducky.png"); SetToolTip("Make 'foo' on an image."); - + // Create a menu to choose the convert image QMenu * m = new QMenu(); m->setTitle("Convert to "); @@ -80,8 +82,8 @@ void vvToolConvert::Initialize() { for(unsigned int i=0; iaddAction(QIcon(QString::fromUtf8(mListOfPixelTypeIcons[i].c_str())), - tr(s.c_str())); + mMapOfPixelType[s] = m->addAction(QIcon(QString::fromUtf8(mListOfPixelTypeIcons[i].c_str())), + tr(s.c_str())); m->addAction(mMapOfPixelType[s]); } @@ -91,7 +93,8 @@ void vvToolConvert::Initialize() { //------------------------------------------------------------------------------ -void vvToolConvert::show() { +void vvToolConvert::show() +{ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); // Get action menu name QAction * cc = dynamic_cast(mSender); @@ -100,33 +103,34 @@ void vvToolConvert::show() { int index = mMainWindowBase->GetSlicerManagerCurrentIndex(); vvSlicerManager * m = mMainWindowBase->GetSlicerManagers()[index]; assert(m != NULL); // Should no occur - + // Create filter and run ! clitk::ImageConvertGenericFilter * filter = new clitk::ImageConvertGenericFilter; filter->SetInputVVImage(m->GetImage()); filter->SetOutputPixelType(type); filter->EnableDisplayWarning(false); filter->Update(); - + // Manage warning if (filter->IsWarningOccur()) { QApplication::restoreOverrideCursor(); - QMessageBox::warning(mMainWindowBase, "Warning", filter->GetWarning().c_str()); + QMessageBox::warning(mMainWindowBase, "Warning", filter->GetWarning().c_str()); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); } - + // Output vvImage::Pointer output = filter->GetOutputVVImage(); std::ostringstream osstream; osstream << "Convert_" << type << "_" << m->GetSlicer(0)->GetFileName() << ".mhd"; - AddImage(output,osstream.str()); + AddImage(output,osstream.str()); QApplication::restoreOverrideCursor(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolConvert::apply() { +void vvToolConvert::apply() +{ // nothing !! } //------------------------------------------------------------------------------ diff --git a/vv/vvToolCreator.txx b/vv/vvToolCreator.txx index 47b526c..234ac1f 100644 --- a/vv/vvToolCreator.txx +++ b/vv/vvToolCreator.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -18,7 +18,8 @@ //------------------------------------------------------------------------------ template -void vvToolCreator::InsertToolInMenu(vvMainWindowBase * m) { +void vvToolCreator::InsertToolInMenu(vvMainWindowBase * m) +{ mMainWindow = m; // Default Initialization @@ -30,13 +31,14 @@ void vvToolCreator::InsertToolInMenu(vvMainWindowBase * m) { ToolType::Initialize(); // Common Initialization (insertion into menu) - vvToolCreatorBase::InsertToolInMenu(mMainWindow); + vvToolCreatorBase::InsertToolInMenu(mMainWindow); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ template -vvToolCreator* & vvToolCreator::GetInstance() { +vvToolCreator* & vvToolCreator::GetInstance() +{ if(!mSingleton) mSingleton = new vvToolCreator; return mSingleton; diff --git a/vv/vvToolCreatorBase.cxx b/vv/vvToolCreatorBase.cxx index e5d60bd..3b0610c 100644 --- a/vv/vvToolCreatorBase.cxx +++ b/vv/vvToolCreatorBase.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -22,47 +22,51 @@ #include //------------------------------------------------------------------------------ -vvToolCreatorBase::vvToolCreatorBase(QString name): mExperimental(false) { +vvToolCreatorBase::vvToolCreatorBase(QString name): mExperimental(false) +{ mUseContextMenu = false; mToolName = name; - vvToolManager::GetInstance()->AddTool(this); + vvToolManager::GetInstance()->AddTool(this); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolCreatorBase::MenuToolSlot() { - mSender = QObject::sender(); - MenuSpecificToolSlot(); +void vvToolCreatorBase::MenuToolSlot() +{ + mSender = QObject::sender(); + MenuSpecificToolSlot(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolCreatorBase::InsertToolInMenu(vvMainWindowBase * m) { - mMainWindow = m; +void vvToolCreatorBase::InsertToolInMenu(vvMainWindowBase * m) +{ + mMainWindow = m; if (mUseContextMenu) { InsertToolInContextMenu(); - return; + return; } // Create main action - if (mToolIconFilename == "noicon") + if (mToolIconFilename == "noicon") mAction = new QAction(QString("&").append(mToolMenuName), this); - else - mAction = new QAction(QIcon(mToolIconFilename), + else + mAction = new QAction(QIcon(mToolIconFilename), QString("&").append(mToolMenuName), this); mAction->setStatusTip(mToolTip); // Connect the action connect(mAction, SIGNAL(triggered()), this, SLOT(MenuToolSlot())); if (mExperimental) - mMainWindow->GetExperimentalToolMenu()->addAction(mAction); + mMainWindow->GetExperimentalToolMenu()->addAction(mAction); else - mMainWindow->GetToolMenu()->addAction(mAction); -} + mMainWindow->GetToolMenu()->addAction(mAction); +} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolCreatorBase::InsertToolInContextMenu() { +void vvToolCreatorBase::InsertToolInContextMenu() +{ mMainWindow->GetContextMenu()->addMenu(mToolMenu); for(unsigned int i=0; iactions().size(); i++) { mListOfActions.push_back(m->actions()[i]); diff --git a/vv/vvToolCreatorBase.txx b/vv/vvToolCreatorBase.txx index 94741dd..5cd2c50 100644 --- a/vv/vvToolCreatorBase.txx +++ b/vv/vvToolCreatorBase.txx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -17,7 +17,8 @@ ======================================================================-====*/ template -void vvToolCreatorBase::CreateTool() { +void vvToolCreatorBase::CreateTool() +{ // Get information on the current image mMainWindow->UpdateCurrentSlicer(); // Create the tool diff --git a/vv/vvToolCropImage.cxx b/vv/vvToolCropImage.cxx index 6192350..1600e86 100644 --- a/vv/vvToolCropImage.cxx +++ b/vv/vvToolCropImage.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -35,9 +35,10 @@ ADD_TOOL(vvToolCropImage); //------------------------------------------------------------------------------ vvToolCropImage::vvToolCropImage(vvMainWindowBase * parent, Qt::WindowFlags f): - vvToolWidgetBase(parent, f), - vvToolBase(parent), - Ui::vvToolCropImage() { + vvToolWidgetBase(parent, f), + vvToolBase(parent), + Ui::vvToolCropImage() +{ // GUI Initialization Ui_vvToolCropImage::setupUi(mToolWidget); @@ -49,32 +50,36 @@ vvToolCropImage::vvToolCropImage(vvMainWindowBase * parent, Qt::WindowFlags f): //------------------------------------------------------------------------------ -vvToolCropImage::~vvToolCropImage() { +vvToolCropImage::~vvToolCropImage() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -bool vvToolCropImage::close() { +bool vvToolCropImage::close() +{ for(int i=0; isetMinimum(xminSlider->value()); mReducedExtent[0] = xminSlider->value(); UpdateExtent(); @@ -83,7 +88,8 @@ void vvToolCropImage::sliderXMinValueChanged(int s) { //------------------------------------------------------------------------------ -void vvToolCropImage::sliderXMaxValueChanged(int s) { +void vvToolCropImage::sliderXMaxValueChanged(int s) +{ xminSlider->setMaximum(xmaxSlider->value()); mReducedExtent[1] = xmaxSlider->value(); UpdateExtent(); @@ -92,7 +98,8 @@ void vvToolCropImage::sliderXMaxValueChanged(int s) { //------------------------------------------------------------------------------ -void vvToolCropImage::sliderYMinValueChanged(int s) { +void vvToolCropImage::sliderYMinValueChanged(int s) +{ ymaxSlider->setMinimum(yminSlider->value()); mReducedExtent[2] = yminSlider->value(); UpdateExtent(); @@ -101,7 +108,8 @@ void vvToolCropImage::sliderYMinValueChanged(int s) { //------------------------------------------------------------------------------ -void vvToolCropImage::sliderYMaxValueChanged(int s) { +void vvToolCropImage::sliderYMaxValueChanged(int s) +{ yminSlider->setMaximum(ymaxSlider->value()); mReducedExtent[3] = ymaxSlider->value(); UpdateExtent(); @@ -110,7 +118,8 @@ void vvToolCropImage::sliderYMaxValueChanged(int s) { //------------------------------------------------------------------------------ -void vvToolCropImage::sliderZMinValueChanged(int s) { +void vvToolCropImage::sliderZMinValueChanged(int s) +{ zmaxSlider->setMinimum(zminSlider->value()); mReducedExtent[4] = zminSlider->value(); UpdateExtent(); @@ -119,7 +128,8 @@ void vvToolCropImage::sliderZMinValueChanged(int s) { //------------------------------------------------------------------------------ -void vvToolCropImage::sliderZMaxValueChanged(int s) { +void vvToolCropImage::sliderZMaxValueChanged(int s) +{ zminSlider->setMaximum(zmaxSlider->value()); mReducedExtent[5] = zmaxSlider->value(); UpdateExtent(); @@ -146,18 +156,20 @@ void vvToolCropImage::sliderZMaxValueChanged(int s) { //------------------------------------------------------------------------------ -void vvToolCropImage::UpdateExtent() { +void vvToolCropImage::UpdateExtent() +{ for(int i=0; iNumberOfSlicers(); i++) { mCurrentSlicerManager->GetSlicer(i)->SetReducedExtent(mReducedExtent); - mCurrentSlicerManager->GetSlicer(i)->ForceUpdateDisplayExtent(); - mCurrentSlicerManager->GetSlicer(i)->Render(); + mCurrentSlicerManager->GetSlicer(i)->ForceUpdateDisplayExtent(); + mCurrentSlicerManager->GetSlicer(i)->Render(); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) { +void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) +{ // Change interface according to number of dimension mExtentSize = 2*slicer->GetDimension(); @@ -177,7 +189,7 @@ void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) { spin_zmin->setHidden(true); spin_zmax->setHidden(true); } - + // Record initial extend mReducedExtent = new int[mExtentSize]; mInitialExtent = new int[mExtentSize]; @@ -189,7 +201,7 @@ void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) { //DD(mInitialExtent[i]); mCurrentSlicerManager->GetSlicer(i)->EnableReducedExtent(true); } - + // Not now .... // mIntensitySlider->SetImage(mCurrentImage); //mIntensitySlider->setEnabled(false); @@ -229,13 +241,13 @@ void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) { spin_zmax->setMaximum(imsize[2]-1); spin_zmax->setValue(imsize[2]-1); } - + // if (slicer->GetDimension() >3) { // spin_tmin->setMaximum(imsize[3]-1); // spin_tmax->setMaximum(imsize[3]-1); // spin_tmax->setValue(imsize[3]-1); - // } - + // } + // Connect connect(xminSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderXMinValueChanged(int))); connect(xmaxSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderXMaxValueChanged(int))); @@ -245,7 +257,7 @@ void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) { connect(zmaxSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderZMaxValueChanged(int))); // connect(tminSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderTMinValueChanged(int))); // connect(tmaxSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderTMaxValueChanged(int))); - + // connect(mCurrentSlicerManager,SIGNAL(UpdateSlice(int,int)),this,SLOT(UpdateExtent())); //connect(mCurrentSlicerManager,SIGNAL(UpdateTSlice(int,int)),this,SLOT(UpdateExtent())); @@ -256,7 +268,8 @@ void vvToolCropImage::InputIsSelected(vvSlicerManager * slicer) { //------------------------------------------------------------------------------ -void vvToolCropImage::autoCropValueChanged(double v) { +void vvToolCropImage::autoCropValueChanged(double v) +{ // DD(v); // vvImageToITKImageVector -> TODO a generic method // then sliceriterator on each dimension from in to max @@ -266,34 +279,34 @@ void vvToolCropImage::autoCropValueChanged(double v) { //------------------------------------------------------------------------------ -void vvToolCropImage::apply() { +void vvToolCropImage::apply() +{ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); vvImage::Pointer mResult=vvImage::New(); vvImage::Pointer image= mCurrentSlicerManager->GetImage(); for (std::vector::const_iterator i=image->GetVTKImages().begin(); - i!=image->GetVTKImages().end();i++) - { - vtkSmartPointer filter=vtkSmartPointer::New(); - ///Vtk is very weird, you need to "translate the extent" to get the correct origin - //http://markmail.org/message/vndc2tr6kcabiakp#query:vtkImageClip%20origin+page:1+mid:6na7y57floutklvz+state:results - vtkSmartPointer translate=vtkSmartPointer::New(); - filter->SetInput(*i); - filter->SetOutputWholeExtent(xminSlider->value(),xmaxSlider->value(), - yminSlider->value(),ymaxSlider->value(), - zminSlider->value(),zmaxSlider->value()); - translate->SetTranslation(-xminSlider->value(),-yminSlider->value(),-zminSlider->value()); - translate->SetInput(filter->GetOutput()); - filter->ClipDataOn(); //Really create a cropped copy of the image - translate->Update(); - vtkImageData* output=vtkImageData::New(); - output->ShallowCopy(translate->GetOutput()); - mResult->AddImage(output); - } + i!=image->GetVTKImages().end(); i++) { + vtkSmartPointer filter=vtkSmartPointer::New(); + ///Vtk is very weird, you need to "translate the extent" to get the correct origin + //http://markmail.org/message/vndc2tr6kcabiakp#query:vtkImageClip%20origin+page:1+mid:6na7y57floutklvz+state:results + vtkSmartPointer translate=vtkSmartPointer::New(); + filter->SetInput(*i); + filter->SetOutputWholeExtent(xminSlider->value(),xmaxSlider->value(), + yminSlider->value(),ymaxSlider->value(), + zminSlider->value(),zmaxSlider->value()); + translate->SetTranslation(-xminSlider->value(),-yminSlider->value(),-zminSlider->value()); + translate->SetInput(filter->GetOutput()); + filter->ClipDataOn(); //Really create a cropped copy of the image + translate->Update(); + vtkImageData* output=vtkImageData::New(); + output->ShallowCopy(translate->GetOutput()); + mResult->AddImage(output); + } QApplication::restoreOverrideCursor(); std::ostringstream osstream; osstream << "Crop_" << mCurrentSlicerManager->GetSlicer(0)->GetFileName() << ".mhd"; - AddImage(mResult, osstream.str()); + AddImage(mResult, osstream.str()); close(); } //------------------------------------------------------------------------------ diff --git a/vv/vvToolFoo.cxx b/vv/vvToolFoo.cxx index 66a97d7..b6a7ced 100644 --- a/vv/vvToolFoo.cxx +++ b/vv/vvToolFoo.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -25,9 +25,10 @@ ADD_TOOL(vvToolFoo); //------------------------------------------------------------------------------ vvToolFoo::vvToolFoo(vvMainWindowBase * parent, Qt::WindowFlags f) - :QDialog(parent), - vvToolBase(parent), - Ui::vvToolFoo() { + :QDialog(parent), + vvToolBase(parent), + Ui::vvToolFoo() +{ // Setup the UI Ui_vvToolFoo::setupUi(this); } @@ -35,13 +36,15 @@ vvToolFoo::vvToolFoo(vvMainWindowBase * parent, Qt::WindowFlags f) //------------------------------------------------------------------------------ -vvToolFoo::~vvToolFoo() { +vvToolFoo::~vvToolFoo() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolFoo::Initialize() { +void vvToolFoo::Initialize() +{ SetToolName("Foo"); SetToolMenuName("Foo"); SetToolIconFilename(":/common/icons/ducky.png"); diff --git a/vv/vvToolFooWithWidgetBase.cxx b/vv/vvToolFooWithWidgetBase.cxx index 719c9b0..f6074f9 100644 --- a/vv/vvToolFooWithWidgetBase.cxx +++ b/vv/vvToolFooWithWidgetBase.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -25,9 +25,10 @@ ADD_TOOL(vvToolFooWithWidgetBase); //------------------------------------------------------------------------------ vvToolFooWithWidgetBase::vvToolFooWithWidgetBase(vvMainWindowBase * parent, Qt::WindowFlags f) - :vvToolWidgetBase(parent, f), - vvToolBase(parent), - Ui::vvToolFoo() { + :vvToolWidgetBase(parent, f), + vvToolBase(parent), + Ui::vvToolFoo() +{ // Setup the UI Ui_vvToolFoo::setupUi(mToolWidget); } @@ -35,13 +36,15 @@ vvToolFooWithWidgetBase::vvToolFooWithWidgetBase(vvMainWindowBase * parent, Qt:: //------------------------------------------------------------------------------ -vvToolFooWithWidgetBase::~vvToolFooWithWidgetBase() { +vvToolFooWithWidgetBase::~vvToolFooWithWidgetBase() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolFooWithWidgetBase::Initialize() { +void vvToolFooWithWidgetBase::Initialize() +{ SetToolName("Foo"); SetToolMenuName("Foo with WidgetBase"); SetToolIconFilename(":/common/icons/ducky.png"); @@ -51,14 +54,16 @@ void vvToolFooWithWidgetBase::Initialize() { //------------------------------------------------------------------------------ -void vvToolFooWithWidgetBase::InputIsSelected(vvSlicerManager *m) { - +void vvToolFooWithWidgetBase::InputIsSelected(vvSlicerManager *m) +{ + } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolFooWithWidgetBase::apply() { +void vvToolFooWithWidgetBase::apply() +{ close(); } //------------------------------------------------------------------------------ diff --git a/vv/vvToolImageArithm.cxx b/vv/vvToolImageArithm.cxx index 3ab3965..ad6343e 100644 --- a/vv/vvToolImageArithm.cxx +++ b/vv/vvToolImageArithm.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -29,13 +29,14 @@ ADD_TOOL(vvToolImageArithm); //------------------------------------------------------------------------------ vvToolImageArithm::vvToolImageArithm(vvMainWindowBase * parent, Qt::WindowFlags f) - :vvToolWidgetBase(parent, f), - vvToolBase(parent), - Ui::vvToolImageArithm() { + :vvToolWidgetBase(parent, f), + vvToolBase(parent), + Ui::vvToolImageArithm() +{ // Setup the UI Ui_vvToolImageArithm::setupUi(mToolWidget); - // Main filter + // Main filter mFilter = new clitk::ImageArithmGenericFilter; // Set how many inputs are needed for this tool @@ -46,13 +47,15 @@ vvToolImageArithm::vvToolImageArithm(vvMainWindowBase * parent, Qt::WindowFlags //------------------------------------------------------------------------------ -vvToolImageArithm::~vvToolImageArithm() { +vvToolImageArithm::~vvToolImageArithm() +{ } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolImageArithm::Initialize() { +void vvToolImageArithm::Initialize() +{ SetToolName("ImageArithm"); SetToolMenuName("ImageArithm"); SetToolIconFilename(":/common/icons/arithm.png"); @@ -63,9 +66,10 @@ void vvToolImageArithm::Initialize() { //------------------------------------------------------------------------------ -void vvToolImageArithm::InputIsSelected(std::vector & l) { +void vvToolImageArithm::InputIsSelected(std::vector & l) +{ mInput1 = l[0]; - mInput2 = l[1]; + mInput2 = l[1]; mTwoInputs = true; mGroupBoxOneInput->setEnabled(false); mGroupBoxTwoInputs->setEnabled(true); @@ -74,7 +78,8 @@ void vvToolImageArithm::InputIsSelected(std::vector & l) { //------------------------------------------------------------------------------ -void vvToolImageArithm::InputIsSelected(vvSlicerManager * l) { +void vvToolImageArithm::InputIsSelected(vvSlicerManager * l) +{ mInput1 = l; mTwoInputs = false; // DD("Single input"); @@ -85,7 +90,8 @@ void vvToolImageArithm::InputIsSelected(vvSlicerManager * l) { //------------------------------------------------------------------------------ -void vvToolImageArithm::GetArgsInfoFromGUI() { +void vvToolImageArithm::GetArgsInfoFromGUI() +{ // DD("GetArgsInfoFromGUI"); mArgsInfo.input1_given = false; if (mTwoInputs) { @@ -99,9 +105,8 @@ void vvToolImageArithm::GetArgsInfoFromGUI() { if (radioButtonMin->isChecked()) mArgsInfo.operation_arg = 4; if (radioButtonAbsDiff->isChecked()) mArgsInfo.operation_arg = 5; if (radioButtonSquaredDiff->isChecked()) mArgsInfo.operation_arg = 6; - } - else { - mArgsInfo.input2_given = false; + } else { + mArgsInfo.input2_given = false; mArgsInfo.scalar_given = true; if (radioButtonSumV->isChecked()) mArgsInfo.operation_arg = 0; if (radioButtonMultiplyV->isChecked()) mArgsInfo.operation_arg = 1; @@ -117,7 +122,7 @@ void vvToolImageArithm::GetArgsInfoFromGUI() { mArgsInfo.scalar_arg = mValueSpinBox->value(); } mArgsInfo.output_given = false; - mArgsInfo.verbose_flag = false; + mArgsInfo.verbose_flag = false; mArgsInfo.setFloatOutput_flag = mCheckBoxUseFloatOutputType->isChecked(); mArgsInfo.imagetypes_flag = false; } @@ -125,7 +130,8 @@ void vvToolImageArithm::GetArgsInfoFromGUI() { //------------------------------------------------------------------------------ -void vvToolImageArithm::apply() { +void vvToolImageArithm::apply() +{ if (!mCurrentSlicerManager) close(); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); GetArgsInfoFromGUI(); @@ -135,7 +141,7 @@ void vvToolImageArithm::apply() { // Input inputs.push_back(mInput1->GetImage()); inputs.push_back(mInput2->GetImage()); - + // Check input type if (inputs[0]->GetScalarTypeAsString() != inputs[1]->GetScalarTypeAsString()) { std::cerr << "Sorry inputs should have the same pixeltype." << std::endl; @@ -146,28 +152,27 @@ void vvToolImageArithm::apply() { close(); return; } - } - else { + } else { // Input inputs.push_back(mInput1->GetImage()); DD("Single input"); } - + // Main filter - clitk::ImageArithmGenericFilter::Pointer filter = + clitk::ImageArithmGenericFilter::Pointer filter = clitk::ImageArithmGenericFilter::New(); filter->SetInputVVImages(inputs); filter->SetArgsInfo(mArgsInfo); filter->EnableReadOnDisk(false); filter->EnableOverwriteInputImage(false); filter->Update(); - + // Output vvImage::Pointer output = filter->GetOutputVVImage(); std::ostringstream osstream; - osstream << "Arithm_" << mArgsInfo.operation_arg << "_ " + osstream << "Arithm_" << mArgsInfo.operation_arg << "_ " << mCurrentSlicerManager->GetSlicer(0)->GetFileName() << ".mhd"; - AddImage(output,osstream.str()); + AddImage(output,osstream.str()); QApplication::restoreOverrideCursor(); close(); } diff --git a/vv/vvToolInputSelectorWidget.cxx b/vv/vvToolInputSelectorWidget.cxx index 813b3c7..a8478e4 100644 --- a/vv/vvToolInputSelectorWidget.cxx +++ b/vv/vvToolInputSelectorWidget.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,32 +23,35 @@ //------------------------------------------------------------------------------ vvToolInputSelectorWidget::vvToolInputSelectorWidget(QWidget * parent, Qt::WindowFlags f): - QWidget(parent, f) { - setupUi(this); + QWidget(parent, f) +{ + setupUi(this); setEnabled(true); mNumberOfAcceptedInputs = 0; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -int vvToolInputSelectorWidget::GetNumberOfInput() { +int vvToolInputSelectorWidget::GetNumberOfInput() +{ return mListOfSimpleInputWidget.size(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolInputSelectorWidget::AddInputSelector(QString & s, - const std::vector & l, - int index, - bool allowSkip) { +void vvToolInputSelectorWidget::AddInputSelector(QString & s, + const std::vector & l, + int index, + bool allowSkip) +{ // DD("ICICICICICICICIC AddInputSelector ADD layout"); // DD(index); //DD(l.size()); vvToolSimpleInputSelectorWidget * input = new vvToolSimpleInputSelectorWidget; mListOfSimpleInputWidget.push_back(input); mSkipInput.push_back(false); - + input->SetText(s); input->EnableAllowSkip(allowSkip); @@ -67,16 +70,17 @@ void vvToolInputSelectorWidget::AddInputSelector(QString & s, else input->setEnabled(false); //DD(GetNumberOfInput()); - // Connect signals & slots + // Connect signals & slots connect(input, SIGNAL(accepted()), this, SLOT(accept())); - connect(input, SIGNAL(rejected()), this, SLOT(reject())); - connect(input, SIGNAL(sigskip()), this, SLOT(skip())); + connect(input, SIGNAL(rejected()), this, SLOT(reject())); + connect(input, SIGNAL(sigskip()), this, SLOT(skip())); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolInputSelectorWidget::Initialize() { +void vvToolInputSelectorWidget::Initialize() +{ for(unsigned int i=0; iInitialize(); } @@ -84,15 +88,15 @@ void vvToolInputSelectorWidget::Initialize() { //------------------------------------------------------------------------------ -void vvToolInputSelectorWidget::accept() { +void vvToolInputSelectorWidget::accept() +{ // DD("vvToolInputSelectorWidget::accept"); //DD(mNumberOfAcceptedInputs); mNumberOfAcceptedInputs++; if (mNumberOfAcceptedInputs == GetNumberOfInput()) { setEnabled(false); emit accepted(); - } - else { + } else { //DD("accepted"); // for(unsigned int i=mNumberOfAcceptedInputs; iInitialize(); @@ -104,7 +108,8 @@ void vvToolInputSelectorWidget::accept() { //------------------------------------------------------------------------------ -void vvToolInputSelectorWidget::reject() { +void vvToolInputSelectorWidget::reject() +{ // DD("vvToolInputSelectorWidget::reject"); if (mNumberOfAcceptedInputs != 0) { // for(unsigned int i=mNumberOfAcceptedInputs; isetEnabled(true); mNumberOfAcceptedInputs--; //} - } - else { + } else { emit rejected(); } } @@ -123,7 +127,8 @@ void vvToolInputSelectorWidget::reject() { //------------------------------------------------------------------------------ -void vvToolInputSelectorWidget::skip() { +void vvToolInputSelectorWidget::skip() +{ // DD("SKIP"); mSkipInput[mNumberOfAcceptedInputs] = true; accept();//mNumberOfAcceptedInputs++; @@ -132,7 +137,8 @@ void vvToolInputSelectorWidget::skip() { //------------------------------------------------------------------------------ -std::vector & vvToolInputSelectorWidget::GetSelectedInputs() { +std::vector & vvToolInputSelectorWidget::GetSelectedInputs() +{ std::vector * l = new std::vector; for(unsigned int i=0; i & vvToolInputSelectorWidget::GetSelectedInputs() { //------------------------------------------------------------------------------ -void vvToolInputSelectorWidget::AnImageIsBeingClosed(vvSlicerManager * m) { +void vvToolInputSelectorWidget::AnImageIsBeingClosed(vvSlicerManager * m) +{ // DD("TODO : verify that the image still exist !!"); // for(int i=0; i< } diff --git a/vv/vvToolManager.cxx b/vv/vvToolManager.cxx index f1450ce..13b0a4a 100644 --- a/vv/vvToolManager.cxx +++ b/vv/vvToolManager.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -21,13 +21,14 @@ #include "vvMainWindowBase.h" //------------------------------------------------------------------------------ -/// Unique static instance -vvToolManager* vvToolManager::mSingleton=0; +/// Unique static instance +vvToolManager* vvToolManager::mSingleton=0; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -vvToolManager * vvToolManager::GetInstance() { +vvToolManager * vvToolManager::GetInstance() +{ if (mSingleton == 0) { mSingleton = new vvToolManager; } @@ -37,15 +38,17 @@ vvToolManager * vvToolManager::GetInstance() { //------------------------------------------------------------------------------ -void vvToolManager::AddTool(vvToolCreatorBase * v) { +void vvToolManager::AddTool(vvToolCreatorBase * v) +{ std::cout << "Adding the tool <" << v->mToolName.toStdString() << ">." << std::endl; GetInstance()->mListOfTools.push_back(v); -} +} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolManager::InsertToolsInMenu(vvMainWindowBase * m) { +void vvToolManager::InsertToolsInMenu(vvMainWindowBase * m) +{ for(unsigned int i=0; imListOfTools.size(); i++) { GetInstance()->mListOfTools[i]->InsertToolInMenu(m); } diff --git a/vv/vvToolMedianFilter.cxx b/vv/vvToolMedianFilter.cxx index 04ca82c..22c122f 100644 --- a/vv/vvToolMedianFilter.cxx +++ b/vv/vvToolMedianFilter.cxx @@ -1,141 +1,143 @@ - /*========================================================================= - - Program: vv - Module: $RCSfile: vvToolMedianFilter.cxx,v $ - Language: C++ - Date: $Date: 2010/05/17 10:41:49 $ - Version: $Revision: 1.3 $ - Author : Bharath Navalpakkam (Bharath.Navalpakkam@creatis.insa-lyon.fr) - - Copyright (C) 2010 - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS http://www.creatis.insa-lyon.fr - - 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 3 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. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - - =========================================================================*/ - - #include "vvToolMedianFilter.h" - #include "vvSlicerManager.h" - #include "vvSlicer.h" - #include "vvToolInputSelectorWidget.h" - #include - - - //------------------------------------------------------------------------------ - // Create the tool and automagically - ADD_TOOL(vvToolMedianFilter); - //------------------------------------------------------------------------------ - - //------------------------------------------------------------------------------ - vvToolMedianFilter::vvToolMedianFilter(vvMainWindowBase * parent, Qt::WindowFlags f) - :vvToolWidgetBase(parent,f), - vvToolBase(parent), - Ui::vvToolMedianFilter() - { - - // Setup the UI - - Ui_vvToolMedianFilter::setupUi(mToolWidget); - - mFilter = new clitk::MedianImageGenericFilter; - - - - // Main filter - - // Set how many inputs are needed for this tool +/*========================================================================= + + Program: vv + Module: $RCSfile: vvToolMedianFilter.cxx,v $ + Language: C++ + Date: $Date: 2010/05/18 16:20:57 $ + Version: $Revision: 1.4 $ + Author : Bharath Navalpakkam (Bharath.Navalpakkam@creatis.insa-lyon.fr) + + Copyright (C) 2010 + Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr + CREATIS http://www.creatis.insa-lyon.fr + + 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 3 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. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + =========================================================================*/ + +#include "vvToolMedianFilter.h" +#include "vvSlicerManager.h" +#include "vvSlicer.h" +#include "vvToolInputSelectorWidget.h" +#include + + +//------------------------------------------------------------------------------ +// Create the tool and automagically +ADD_TOOL(vvToolMedianFilter); +//------------------------------------------------------------------------------ + +//------------------------------------------------------------------------------ +vvToolMedianFilter::vvToolMedianFilter(vvMainWindowBase * parent, Qt::WindowFlags f) + :vvToolWidgetBase(parent,f), + vvToolBase(parent), + Ui::vvToolMedianFilter() +{ + + // Setup the UI + + Ui_vvToolMedianFilter::setupUi(mToolWidget); + + mFilter = new clitk::MedianImageGenericFilter; + + + + // Main filter + + // Set how many inputs are needed for this tool AddInputSelector("Select one image", mFilter); - } - - //------------------------------------------------------------------------------ - vvToolMedianFilter::~vvToolMedianFilter() { - } - //------------------------------------------------------------------------------ - void vvToolMedianFilter::Initialize() { - SetToolName("MedianFilter"); - SetToolMenuName("MedianFilter"); - SetToolIconFilename(":common/icons/ducky.png"); - SetToolTip("Make 'MedianFilter' on an image."); - SetToolExperimental(true); - } - //------------------------------------------------------------------------------ - - void vvToolMedianFilter::apply() { - - GetArgsInfoFromGUI(); - if (!mCurrentSlicerManager) close(); +} + +//------------------------------------------------------------------------------ +vvToolMedianFilter::~vvToolMedianFilter() +{ +} +//------------------------------------------------------------------------------ +void vvToolMedianFilter::Initialize() +{ + SetToolName("MedianFilter"); + SetToolMenuName("MedianFilter"); + SetToolIconFilename(":common/icons/ducky.png"); + SetToolTip("Make 'MedianFilter' on an image."); + SetToolExperimental(true); +} +//------------------------------------------------------------------------------ + +void vvToolMedianFilter::apply() +{ + + GetArgsInfoFromGUI(); + if (!mCurrentSlicerManager) close(); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); // Main filter - clitk::MedianImageGenericFilter::Pointer filter = - clitk::MedianImageGenericFilter::New(); - filter->SetInputVVImage(mCurrentImage); - filter->SetArgsInfo(mArgsInfo); - filter->EnableReadOnDisk(false); - filter->Update(); + clitk::MedianImageGenericFilter::Pointer filter = + clitk::MedianImageGenericFilter::New(); + filter->SetInputVVImage(mCurrentImage); + filter->SetArgsInfo(mArgsInfo); + filter->EnableReadOnDisk(false); + filter->Update(); // Output vvImage::Pointer output = filter->GetOutputVVImage(); std::ostringstream osstream; osstream << "MedianFiltered_" << mCurrentSlicerManager->GetSlicer(0)->GetFileName() << ".mhd"; - AddImage(output,osstream.str()); + AddImage(output,osstream.str()); QApplication::restoreOverrideCursor(); close(); - } - //------------------------------------------------------------------------------ - void vvToolMedianFilter::GetArgsInfoFromGUI() { - /* //KEEP THIS FOR READING GGO FROM FILE - int argc=1; - std::string a = "toto"; - char * const* argv = new char*; - //a.c_str(); - struct cmdline_parser_params p; - p.check_required = 0; - int good = cmdline_parser_ext(argc, argv, &args_info, &p); - DD(good); - */ - mArgsInfo.radius_given=0; - mArgsInfo.verbose_flag = false; - // mArgsInfo.radius_arg = new int[3]; +} +//------------------------------------------------------------------------------ +void vvToolMedianFilter::GetArgsInfoFromGUI() +{ + /* //KEEP THIS FOR READING GGO FROM FILE + int argc=1; + std::string a = "toto"; + char * const* argv = new char*; + //a.c_str(); + struct cmdline_parser_params p; + p.check_required = 0; + int good = cmdline_parser_ext(argc, argv, &args_info, &p); + DD(good); + */ + mArgsInfo.radius_given=0; + mArgsInfo.verbose_flag = false; + // mArgsInfo.radius_arg = new int[3]; // Required (even if not used) - mArgsInfo.input_given = 0; - mArgsInfo.output_given = 0; - mArgsInfo.input_arg=new char; - mArgsInfo.output_arg = new char; - mArgsInfo.config_given=0; - mArgsInfo.verbose_given=0; - } - //------------------------------------------------------------------------------ -void vvToolMedianFilter::InputIsSelected(vvSlicerManager *m){ + mArgsInfo.input_given = 0; + mArgsInfo.output_given = 0; + mArgsInfo.input_arg=new char; + mArgsInfo.output_arg = new char; + mArgsInfo.config_given=0; + mArgsInfo.verbose_given=0; +} +//------------------------------------------------------------------------------ +void vvToolMedianFilter::InputIsSelected(vvSlicerManager *m) +{ mCurrentSlicerManager =m; // Specific for this gui - mArgsInfo.radius_arg = new int[3]; + mArgsInfo.radius_arg = new int[3]; int checkdimensions=mCurrentSlicerManager->GetDimension(); - if(checkdimensions<3) - { - horizontalSlider_3->hide(); - spinBox_3->hide(); - mArgsInfo.radius_arg[2]=0; - connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(UpdateH1slider())); - connect(horizontalSlider_2, SIGNAL(valueChanged(int)), this, SLOT(UpdateH2slider())); - } - else - { - horizontalSlider->show(); - horizontalSlider_2->show(); - horizontalSlider_3->show(); - connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(UpdateH1slider())); - connect(horizontalSlider_2, SIGNAL(valueChanged(int)), this, SLOT(UpdateH2slider())); - connect(horizontalSlider_3, SIGNAL(valueChanged(int)), this, SLOT(UpdateH3slider())); + if(checkdimensions<3) { + horizontalSlider_3->hide(); + spinBox_3->hide(); + mArgsInfo.radius_arg[2]=0; + connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(UpdateH1slider())); + connect(horizontalSlider_2, SIGNAL(valueChanged(int)), this, SLOT(UpdateH2slider())); + } else { + horizontalSlider->show(); + horizontalSlider_2->show(); + horizontalSlider_3->show(); + connect(horizontalSlider, SIGNAL(valueChanged(int)), this, SLOT(UpdateH1slider())); + connect(horizontalSlider_2, SIGNAL(valueChanged(int)), this, SLOT(UpdateH2slider())); + connect(horizontalSlider_3, SIGNAL(valueChanged(int)), this, SLOT(UpdateH3slider())); } } @@ -143,17 +145,17 @@ void vvToolMedianFilter::InputIsSelected(vvSlicerManager *m){ void vvToolMedianFilter::UpdateH1slider() { - + mArgsInfo.radius_arg[0]=horizontalSlider->value(); spinBox->setValue(mArgsInfo.radius_arg[0]); } void vvToolMedianFilter::UpdateH2slider() { - mArgsInfo.radius_arg[1]=horizontalSlider_2->value(); + mArgsInfo.radius_arg[1]=horizontalSlider_2->value(); spinBox_2->setValue(mArgsInfo.radius_arg[1]); } void vvToolMedianFilter::UpdateH3slider() { - mArgsInfo.radius_arg[2]=horizontalSlider_3->value(); + mArgsInfo.radius_arg[2]=horizontalSlider_3->value(); spinBox_3->setValue(mArgsInfo.radius_arg[2]); } diff --git a/vv/vvToolResample.cxx b/vv/vvToolResample.cxx index 531a03b..f9b7a4a 100644 --- a/vv/vvToolResample.cxx +++ b/vv/vvToolResample.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -31,7 +31,8 @@ ADD_TOOL(vvToolResample); vvToolResample::vvToolResample(vvMainWindowBase * parent, Qt::WindowFlags f): vvToolWidgetBase(parent,f), vvToolBase(parent), - Ui::vvToolResample() { + Ui::vvToolResample() +{ Ui_vvToolResample::setupUi(mToolWidget); mFilter = clitk::ImageResampleGenericFilter::New(); @@ -115,7 +116,8 @@ vvToolResample::vvToolResample(vvMainWindowBase * parent, Qt::WindowFlags f): //------------------------------------------------------------------------------ -void vvToolResample::Initialize() { +void vvToolResample::Initialize() +{ SetToolName("Resample Image"); SetToolMenuName("Resample"); SetToolIconFilename(":/common/icons/resample.png"); @@ -125,7 +127,8 @@ void vvToolResample::Initialize() { //------------------------------------------------------------------------------ -void vvToolResample::InputIsSelected(vvSlicerManager* m) { +void vvToolResample::InputIsSelected(vvSlicerManager* m) +{ mCurrentSlicerManager = m; mCurrentImage = mCurrentSlicerManager->GetSlicer(0)->GetImage(); @@ -141,7 +144,7 @@ void vvToolResample::InputIsSelected(vvSlicerManager* m) { mInputOrigin.resize(mDimension); mInputSpacing.resize(mDimension); mInputSize.resize(mDimension); - for (int i = 0; i < mDimension;i++) { + for (int i = 0; i < mDimension; i++) { mInputOrigin[i] = mCurrentImage->GetOrigin()[i]; mInputSpacing[i] = mCurrentImage->GetSpacing()[i]; mInputSize[i] = mCurrentImage->GetSize()[i]; @@ -171,7 +174,8 @@ void vvToolResample::InputIsSelected(vvSlicerManager* m) { //------------------------------------------------------------------------------ -void vvToolResample::UpdateOutputInfo() { +void vvToolResample::UpdateOutputInfo() +{ mOutputSizeLabel->setText(GetVectorIntAsString(mOutputSize)); mOutputSpacingLabel->setText(GetVectorDoubleAsString(mOutputSpacing)); mOutputMemoryLabel->setText(GetSizeInBytes(mOutputSize)); @@ -180,7 +184,8 @@ void vvToolResample::UpdateOutputInfo() { //------------------------------------------------------------------------------ -QString vvToolResample::GetSizeInBytes(std::vector & size) { +QString vvToolResample::GetSizeInBytes(std::vector & size) +{ int t = 1; for (unsigned int i=0; iGetScalarSize()*mCurrentImage->GetNumberOfScalarComponents(); @@ -190,25 +195,23 @@ QString vvToolResample::GetSizeInBytes(std::vector & size) { t /= 1000000000; result += QString::number(t); result += " GB)"; - } - else if (t > 1000000) { + } else if (t > 1000000) { t /= 1000000; result += QString::number(t); result += " MB)"; - } - else if (t > 1000) { + } else if (t > 1000) { t /= 1000; result += QString::number(t); result += " KB)"; - } - else result += ")"; + } else result += ")"; return result; } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -QString vvToolResample::GetVectorDoubleAsString(std::vector vectorDouble) { +QString vvToolResample::GetVectorDoubleAsString(std::vector vectorDouble) +{ QString result; for (unsigned int i= 0; i vectorDouble //------------------------------------------------------------------------------ -QString vvToolResample::GetVectorIntAsString(std::vector vectorInt) { +QString vvToolResample::GetVectorIntAsString(std::vector vectorInt) +{ QString result; for (unsigned int i= 0; i vectorInt) { //------------------------------------------------------------------------------ -void vvToolResample::FillSizeEdit(std::vector size) { +void vvToolResample::FillSizeEdit(std::vector size) +{ xSizeLineEdit->setText(QString::number(size[0])); ySizeLineEdit->setText(QString::number(size[1])); if (size.size() > 2) @@ -244,7 +249,8 @@ void vvToolResample::FillSizeEdit(std::vector size) { //------------------------------------------------------------------------------ -void vvToolResample::FillSpacingEdit(std::vector spacing) { +void vvToolResample::FillSpacingEdit(std::vector spacing) +{ xSpacingLineEdit->setText(QString::number(spacing[0])); ySpacingLineEdit->setText(QString::number(spacing[1])); if (spacing.size() > 2) @@ -254,7 +260,8 @@ void vvToolResample::FillSpacingEdit(std::vector spacing) { //------------------------------------------------------------------------------ -void vvToolResample::UpdateOutputSizeAndSpacing() { +void vvToolResample::UpdateOutputSizeAndSpacing() +{ mOutputSize.resize(mDimension); mOutputSize = mInputSize; mOutputSpacing.resize(mDimension); @@ -275,7 +282,8 @@ void vvToolResample::UpdateOutputSizeAndSpacing() { //------------------------------------------------------------------------------ -void vvToolResample::UpdateControlSizeAndSpacing() { +void vvToolResample::UpdateControlSizeAndSpacing() +{ scaleSizeLineEdit->setText(""); scaleSpacingLineEdit->setText(""); isoSizeLineEdit->setText(""); @@ -298,15 +306,13 @@ void vvToolResample::UpdateControlSizeAndSpacing() { ySizeLineEdit->setReadOnly(0); if (mDimension > 2) zSizeLineEdit->setReadOnly(0); - } - else { + } else { if (spacingRadioButton->isChecked()) { xSpacingLineEdit->setReadOnly(0); ySpacingLineEdit->setReadOnly(0); if (mDimension > 2) zSpacingLineEdit->setReadOnly(0); - } - else if (scaleSizeRadioButton->isChecked()) + } else if (scaleSizeRadioButton->isChecked()) scaleSizeLineEdit->setReadOnly(0); else if (scaleSpacingRadioButton->isChecked()) scaleSpacingLineEdit->setReadOnly(0); @@ -320,39 +326,40 @@ void vvToolResample::UpdateControlSizeAndSpacing() { //------------------------------------------------------------------------------ -void vvToolResample::ComputeNewSpacingFromSize() { +void vvToolResample::ComputeNewSpacingFromSize() +{ double newSpacing = mInputSpacing[0]*mInputSize[0]; xSpacingLineEdit->setText(QString::number(newSpacing/xSizeLineEdit->text().toDouble())); newSpacing = mInputSpacing[1]*mInputSize[1]; ySpacingLineEdit->setText(QString::number(newSpacing/ySizeLineEdit->text().toDouble())); - if (mDimension > 2) - { - newSpacing = mInputSpacing[2]*mInputSize[2]; - zSpacingLineEdit->setText(QString::number(newSpacing/zSizeLineEdit->text().toDouble())); - } + if (mDimension > 2) { + newSpacing = mInputSpacing[2]*mInputSize[2]; + zSpacingLineEdit->setText(QString::number(newSpacing/zSizeLineEdit->text().toDouble())); + } UpdateOutputSizeAndSpacing(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolResample::ComputeNewSizeFromSpacing() { +void vvToolResample::ComputeNewSizeFromSpacing() +{ double newSize = mInputSpacing[0]*mInputSize[0]; xSizeLineEdit->setText(QString::number(newSize/xSpacingLineEdit->text().toDouble())); newSize = mInputSpacing[1]*mInputSize[1]; ySizeLineEdit->setText(QString::number(newSize/ySpacingLineEdit->text().toDouble())); - if (mDimension > 2) - { - newSize = mInputSpacing[2]*mInputSize[2]; - zSizeLineEdit->setText(QString::number(newSize/zSpacingLineEdit->text().toDouble())); - } + if (mDimension > 2) { + newSize = mInputSpacing[2]*mInputSize[2]; + zSizeLineEdit->setText(QString::number(newSize/zSpacingLineEdit->text().toDouble())); + } UpdateOutputSizeAndSpacing(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolResample::ComputeNewSpacingFromScale() { +void vvToolResample::ComputeNewSpacingFromScale() +{ xSpacingLineEdit->setText(QString::number(mInputSpacing[0]*scaleSpacingLineEdit->text().toDouble()/100)); ySpacingLineEdit->setText(QString::number(mInputSpacing[1]*scaleSpacingLineEdit->text().toDouble()/100)); if (mDimension > 2) @@ -363,7 +370,8 @@ void vvToolResample::ComputeNewSpacingFromScale() { //------------------------------------------------------------------------------ -void vvToolResample::ComputeNewSizeFromScale() { +void vvToolResample::ComputeNewSizeFromScale() +{ xSizeLineEdit->setText(QString::number(mInputSize[0]*scaleSizeLineEdit->text().toDouble()/100)); ySizeLineEdit->setText(QString::number(mInputSize[1]*scaleSizeLineEdit->text().toDouble()/100)); if (mDimension > 2) @@ -374,7 +382,8 @@ void vvToolResample::ComputeNewSizeFromScale() { //------------------------------------------------------------------------------ -void vvToolResample::ComputeNewSpacingFromIso() { +void vvToolResample::ComputeNewSpacingFromIso() +{ xSpacingLineEdit->setText(QString::number(isoSpacingLineEdit->text().toDouble())); ySpacingLineEdit->setText(QString::number(isoSpacingLineEdit->text().toDouble())); if (mDimension > 2) @@ -385,7 +394,8 @@ void vvToolResample::ComputeNewSpacingFromIso() { //------------------------------------------------------------------------------ -void vvToolResample::ComputeNewSizeFromIso() { +void vvToolResample::ComputeNewSizeFromIso() +{ xSizeLineEdit->setText(QString::number(isoSizeLineEdit->text().toDouble())); ySizeLineEdit->setText(QString::number(isoSizeLineEdit->text().toDouble())); if (mDimension > 2) @@ -396,20 +406,19 @@ void vvToolResample::ComputeNewSizeFromIso() { //------------------------------------------------------------------------------ -void vvToolResample::UpdateInterpolation() { +void vvToolResample::UpdateInterpolation() +{ if (interpolationComboBox->currentText() == "BSpline") { bSplineLabel->show(); bSplineOrderSpinBox->show(); bLUTFactorLabel->hide(); bLUTSpinBox->hide(); - } - else if (interpolationComboBox->currentText() == "B-LUT (faster BSpline)") { + } else if (interpolationComboBox->currentText() == "B-LUT (faster BSpline)") { bSplineLabel->show(); bSplineOrderSpinBox->show(); bLUTFactorLabel->show(); bLUTSpinBox->show(); - } - else { + } else { bSplineLabel->hide(); bSplineOrderSpinBox->hide(); bLUTFactorLabel->hide(); @@ -420,15 +429,15 @@ void vvToolResample::UpdateInterpolation() { //------------------------------------------------------------------------------ -void vvToolResample::UpdateGaussianFilter() { +void vvToolResample::UpdateGaussianFilter() +{ if (gaussianFilterCheckBox->isChecked()) { gaussianFilterLabel->show(); xGaussianLineEdit->show(); yGaussianLineEdit->show(); if (mDimension > 2) zGaussianLineEdit->show(); - } - else { + } else { gaussianFilterLabel->hide(); xGaussianLineEdit->hide(); yGaussianLineEdit->hide(); @@ -439,7 +448,8 @@ void vvToolResample::UpdateGaussianFilter() { //------------------------------------------------------------------------------ -void vvToolResample::apply() { +void vvToolResample::apply() +{ // Get resampler options std::vector sigma; @@ -475,7 +485,8 @@ void vvToolResample::apply() { //------------------------------------------------------------------------------ -std::string vvToolResample::GetOutputFileName() { +std::string vvToolResample::GetOutputFileName() +{ QFileInfo info(QString(mCurrentSlicerManager->GetFileName().c_str())); return (info.path().toStdString() + "/resampled_" + info.fileName().toStdString()); } diff --git a/vv/vvToolRigidReg.cxx b/vv/vvToolRigidReg.cxx index 907ea83..0955381 100644 --- a/vv/vvToolRigidReg.cxx +++ b/vv/vvToolRigidReg.cxx @@ -36,9 +36,9 @@ ADD_TOOL(vvToolRigidReg); //------------------------------------------------------------------------------ vvToolRigidReg::vvToolRigidReg(vvMainWindowBase * parent, Qt::WindowFlags f): - vvToolWidgetBase(parent, f), - vvToolBase(parent), - Ui::vvToolRigidReg() + vvToolWidgetBase(parent, f), + vvToolBase(parent), + Ui::vvToolRigidReg() { // GUI Initialization Ui_vvToolRigidReg::setupUi(mToolWidget); diff --git a/vv/vvToolSimpleInputSelectorWidget.cxx b/vv/vvToolSimpleInputSelectorWidget.cxx index 02d0277..9c948fc 100644 --- a/vv/vvToolSimpleInputSelectorWidget.cxx +++ b/vv/vvToolSimpleInputSelectorWidget.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,8 +23,9 @@ //------------------------------------------------------------------------------ vvToolSimpleInputSelectorWidget::vvToolSimpleInputSelectorWidget(QWidget * parent, Qt::WindowFlags f): - QWidget(parent, f) { - setupUi(this); + QWidget(parent, f) +{ + setupUi(this); setEnabled(true); mSlicerManagerList.clear(); } @@ -32,11 +33,12 @@ vvToolSimpleInputSelectorWidget::vvToolSimpleInputSelectorWidget(QWidget * paren //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::Initialize() { - // Connect signals & slots +void vvToolSimpleInputSelectorWidget::Initialize() +{ + // Connect signals & slots connect(mInputSelectionButtonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(mInputSelectionButtonBox, SIGNAL(rejected()), this, SLOT(reject())); - connect(mInputSequenceBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeInput(int))); + connect(mInputSequenceBox, SIGNAL(currentIndexChanged(int)), this, SLOT(changeInput(int))); if (mSlicerManagerList.size() == 1) { if (!mAllowSkip) accept(); } @@ -48,27 +50,29 @@ void vvToolSimpleInputSelectorWidget::Initialize() { //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::SetText(QString & s) { +void vvToolSimpleInputSelectorWidget::SetText(QString & s) +{ mGroupBox->setTitle(s); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::EnableAllowSkip(bool b) { +void vvToolSimpleInputSelectorWidget::EnableAllowSkip(bool b) +{ mAllowSkip = b; if (mAllowSkip) { mInputSelectionButtonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok|QDialogButtonBox::Discard); connect(mInputSelectionButtonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(skip(QAbstractButton*))); - } - else + } else mInputSelectionButtonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::SetInputList(const std::vector & l, int index) { +void vvToolSimpleInputSelectorWidget::SetInputList(const std::vector & l, int index) +{ if (l.size() == 0) { // TODO !!! DD("no input > error message"); @@ -88,7 +92,8 @@ void vvToolSimpleInputSelectorWidget::SetInputList(const std::vectorsetEnabled(b); mInputSequenceBox->setEnabled(b); @@ -97,7 +102,8 @@ void vvToolSimpleInputSelectorWidget::setEnabled(bool b) { //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::accept() { +void vvToolSimpleInputSelectorWidget::accept() +{ mInputSelectionButtonBox->setEnabled(false); mInputSequenceBox->setEnabled(false); emit accepted(); @@ -107,21 +113,24 @@ void vvToolSimpleInputSelectorWidget::accept() { //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::reject() { +void vvToolSimpleInputSelectorWidget::reject() +{ emit rejected(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::skip(QAbstractButton* b) { +void vvToolSimpleInputSelectorWidget::skip(QAbstractButton* b) +{ if (b->text() == "Discard") emit sigskip(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolSimpleInputSelectorWidget::changeInput(int index) { +void vvToolSimpleInputSelectorWidget::changeInput(int index) +{ if (index<0) return; mCurrentIndex = index; vvImage * mCurrentImage = mSlicerManagerList[index]->GetImage(); @@ -146,7 +155,8 @@ void vvToolSimpleInputSelectorWidget::changeInput(int index) { //------------------------------------------------------------------------------ -vvSlicerManager * vvToolSimpleInputSelectorWidget::GetSelectedInput() { +vvSlicerManager * vvToolSimpleInputSelectorWidget::GetSelectedInput() +{ return mSlicerManagerList[GetSelectedInputIndex()]; } //------------------------------------------------------------------------------ diff --git a/vv/vvToolStructureSetManager.cxx b/vv/vvToolStructureSetManager.cxx index ea24ca6..b04b028 100644 --- a/vv/vvToolStructureSetManager.cxx +++ b/vv/vvToolStructureSetManager.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -37,9 +37,10 @@ ADD_TOOL(vvToolStructureSetManager); //------------------------------------------------------------------------------ vvToolStructureSetManager::vvToolStructureSetManager(vvMainWindowBase * parent, Qt::WindowFlags f) - :vvToolWidgetBase(parent, f), - vvToolBase(parent), - Ui::vvToolStructureSetManager() { + :vvToolWidgetBase(parent, f), + vvToolBase(parent), + Ui::vvToolStructureSetManager() +{ // Setup the UI Ui_vvToolStructureSetManager::setupUi(mToolWidget); mTree->clear(); @@ -47,16 +48,16 @@ vvToolStructureSetManager::vvToolStructureSetManager(vvMainWindowBase * parent, mCurrentStructureSetIndex = -1; mGroupBoxROI->setEnabled(false); mCurrentROIActor = NULL; - + mDefaultLUTColor = vtkLookupTable::New(); for(unsigned int i=0; iGetNumberOfTableValues(); i++) { double r = (rand()/(RAND_MAX+1.0)); double v = (rand()/(RAND_MAX+1.0)); double b = (rand()/(RAND_MAX+1.0)); - mDefaultLUTColor->SetTableValue(i, r, v, b); + mDefaultLUTColor->SetTableValue(i, r, v, b); // std::cout << "mDefaultLUTColor->SetTableValue(" << i << ", " << r << ", " << v << ", " << b << ");" << std::endl; } - #include "vvDefaultLut.h" +#include "vvDefaultLut.h" // Add input selector AddInputSelector("Select image"); @@ -65,14 +66,16 @@ vvToolStructureSetManager::vvToolStructureSetManager(vvMainWindowBase * parent, //------------------------------------------------------------------------------ -vvToolStructureSetManager::~vvToolStructureSetManager() { +vvToolStructureSetManager::~vvToolStructureSetManager() +{ DD("vvToolStructureSetManager DESTRUCTOR"); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolStructureSetManager::Initialize() { +void vvToolStructureSetManager::Initialize() +{ SetToolName("StructureSetManager"); SetToolMenuName("StructureSet"); SetToolIconFilename(":/common/icons/ducky.png"); @@ -83,7 +86,8 @@ void vvToolStructureSetManager::Initialize() { //------------------------------------------------------------------------------ -void vvToolStructureSetManager::InputIsSelected(vvSlicerManager *m) { +void vvToolStructureSetManager::InputIsSelected(vvSlicerManager *m) +{ // Hide the input selector QList s; s.push_back(0); @@ -91,7 +95,7 @@ void vvToolStructureSetManager::InputIsSelected(vvSlicerManager *m) { splitter->setSizes(s); // Connect open menus // connect(mOpenComboBox, SIGNAL(activated(int)), this, SLOT(open(int))); - + connect(mOpenBinaryButton, SIGNAL(clicked()), this, SLOT(openBinaryImage())); DD(mCurrentImage->GetNumberOfDimensions()); @@ -108,7 +112,8 @@ void vvToolStructureSetManager::InputIsSelected(vvSlicerManager *m) { //------------------------------------------------------------------------------ -void vvToolStructureSetManager::LeftButtonReleaseEvent(int slicer) { +void vvToolStructureSetManager::LeftButtonReleaseEvent(int slicer) +{ DD("vvToolStructureSetManager::UpdateSlice"); //DD(slicer); //DD(view); @@ -122,20 +127,30 @@ void vvToolStructureSetManager::LeftButtonReleaseEvent(int slicer) { //------------------------------------------------------------------------------ -void vvToolStructureSetManager::open(int type) { +void vvToolStructureSetManager::open(int type) +{ DD(type); switch (type) { - case 0: openBinaryImage(); return; // Open binary image; - case 1: DD("TODO"); return; // Open DICOM RT - case 2: DD("TODO"); return; // Open mesh - default: std::cerr << "Error ????" << std::endl; exit(0); + case 0: + openBinaryImage(); + return; // Open binary image; + case 1: + DD("TODO"); + return; // Open DICOM RT + case 2: + DD("TODO"); + return; // Open mesh + default: + std::cerr << "Error ????" << std::endl; + exit(0); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolStructureSetManager::addRoiInTreeWidget(clitk::DicomRT_ROI * roi, QTreeWidgetItem * ww) { +void vvToolStructureSetManager::addRoiInTreeWidget(clitk::DicomRT_ROI * roi, QTreeWidgetItem * ww) +{ QTreeWidgetItem * w = new QTreeWidgetItem(ww); w->setText(0, QString("%1").arg(roi->GetROINumber())); w->setText(1, QString("%1").arg(roi->GetName().c_str())); @@ -153,7 +168,8 @@ void vvToolStructureSetManager::addRoiInTreeWidget(clitk::DicomRT_ROI * roi, QTr //------------------------------------------------------------------------------ -void vvToolStructureSetManager::updateStructureSetInTreeWidget(int index, clitk::DicomRT_StructureSet * s) { +void vvToolStructureSetManager::updateStructureSetInTreeWidget(int index, clitk::DicomRT_StructureSet * s) +{ QTreeWidgetItem * ss; if (mMapStructureSetIndexToTreeWidget.find(index) == mMapStructureSetIndexToTreeWidget.end()) { // Main row item @@ -163,11 +179,10 @@ void vvToolStructureSetManager::updateStructureSetInTreeWidget(int index, clitk: ss->setText(1, QString("%1").arg(s->GetLabel().c_str())); // Insert in list mMapStructureSetIndexToTreeWidget[index] = ss; - + // Connect Structure TreeWidget // TODO - } - else ss = mMapStructureSetIndexToTreeWidget[index]; + } else ss = mMapStructureSetIndexToTreeWidget[index]; // Insert ROI const std::vector & rois = s->GetListOfROI(); @@ -180,7 +195,8 @@ void vvToolStructureSetManager::updateStructureSetInTreeWidget(int index, clitk: //------------------------------------------------------------------------------ -int vvToolStructureSetManager::addStructureSet(clitk::DicomRT_StructureSet * mStructureSet) { +int vvToolStructureSetManager::addStructureSet(clitk::DicomRT_StructureSet * mStructureSet) +{ // Create actor for this SS vvStructureSetActor * mStructureSetActor = new vvStructureSetActor; @@ -199,7 +215,8 @@ int vvToolStructureSetManager::addStructureSet(clitk::DicomRT_StructureSet * mSt //------------------------------------------------------------------------------ -void vvToolStructureSetManager::openBinaryImage() { +void vvToolStructureSetManager::openBinaryImage() +{ DD("openBinaryImage"); // Select current StructureSet (or create) int index; @@ -209,12 +226,10 @@ void vvToolStructureSetManager::openBinaryImage() { clitk::DicomRT_StructureSet * mStructureSet = new clitk::DicomRT_StructureSet; index = addStructureSet(mStructureSet); DD(index); - } - else { // Get first SS + } else { // Get first SS index = 0; } - } - else { + } else { index = mCurrentStructureSetIndex; } DD(index); @@ -228,9 +243,9 @@ void vvToolStructureSetManager::openBinaryImage() { // Open images QString Extensions = "Images files ( *.mhd *.hdr *.his)"; Extensions += ";;All Files (*)"; - QStringList filename = + QStringList filename = QFileDialog::getOpenFileNames(this,tr("Open binary image"), - mMainWindowBase->GetInputPathName(),Extensions); + mMainWindowBase->GetInputPathName(),Extensions); if (filename.size() == 0) return; std::vector mLoadedROIIndex; @@ -246,7 +261,7 @@ void vvToolStructureSetManager::openBinaryImage() { mReader->SetInputFilenames(filenames); mReader->Update(IMAGE); QApplication::restoreOverrideCursor(); - + if (mReader->GetLastError().size() != 0) { std::cerr << "Error while reading " << filename[i].toStdString() << std::endl; QString error = "Cannot open file \n"; @@ -265,19 +280,19 @@ void vvToolStructureSetManager::openBinaryImage() { DD(bin_dim); if (dim < bin_dim) { ////////// TO CHANGE FOR 3D/4D std::ostringstream os; - os << "Error. Loaded binary image is " << bin_dim - << "D while selected image is " << dim << "D" << std::endl; + os << "Error. Loaded binary image is " << bin_dim + << "D while selected image is " << dim << "D" << std::endl; QMessageBox::information(this,tr("Reading problem"),os.str().c_str()); return; } - + // Add a new roi to the structure int n = mCurrentStructureSet->AddBinaryImageAsNewROI(binaryImage, filename[i].toStdString()); //DD(n); mLoadedROIIndex.push_back(n); mCurrentStructureSet->GetROI(n)->SetBackgroundValueLabelImage(mBackgroundValueSpinBox->value()); - + // Change color NEED DEFAULT COLOR LIST DD(mDefaultLUTColor->GetNumberOfTableValues ()); if (nGetNumberOfTableValues ()) { @@ -287,27 +302,28 @@ void vvToolStructureSetManager::openBinaryImage() { DD(color[2]); mCurrentStructureSet->GetROI(n)->SetDisplayColor(color[0], color[1], color[2]); } - + // Add a new roi actor mCurrentStructureSetActor->CreateNewROIActor(n); } // end loop on n selected filenames // Update the TreeWidget updateStructureSetInTreeWidget(index, mCurrentStructureSet); - + // Render loaded ROIs (the first is sufficient) for(unsigned int i=0; iGetROIActor(mLoadedROIIndex[i])->Update(); } for(int i=0; iNumberOfSlicers(); i++) { - mCurrentSlicerManager->GetSlicer(i)->Render(); + mCurrentSlicerManager->GetSlicer(i)->Render(); } } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolStructureSetManager::apply() { +void vvToolStructureSetManager::apply() +{ close(); } //------------------------------------------------------------------------------ @@ -320,9 +336,10 @@ void vvToolStructureSetManager::apply() { //------------------------------------------------------------------------------ -void vvToolStructureSetManager::selectedItemChangedInTree() { +void vvToolStructureSetManager::selectedItemChangedInTree() +{ DD("selectedItemChangedInTree"); - + // Search which roi is selected QList l = mTree->selectedItems(); DD(l.size()); @@ -350,17 +367,17 @@ void vvToolStructureSetManager::selectedItemChangedInTree() { mGroupBoxROI->setEnabled(true); mROInameLabel->setText(roi->GetName().c_str()); mCheckBoxShow->setChecked(actor->IsVisible()); - + // Warning -> avoir unuseful Render here by disconnect slider - // - disconnect(mOpacitySlider, SIGNAL(valueChanged(int)), - this, SLOT(opacityChanged(int))); + // + disconnect(mOpacitySlider, SIGNAL(valueChanged(int)), + this, SLOT(opacityChanged(int))); mOpacitySlider->setValue((int)lrint(actor->GetOpacity()*100)); mOpacitySpinBox->setValue((int)lrint(actor->GetOpacity()*100)); - connect(mOpacitySlider, SIGNAL(valueChanged(int)), - this, SLOT(opacityChanged(int))); + connect(mOpacitySlider, SIGNAL(valueChanged(int)), + this, SLOT(opacityChanged(int))); - actor->SetSelected(true); // remove old selection + actor->SetSelected(true); // remove old selection // The following must not render !! DD("before update"); actor->Update(); // To change in UpdateSelecte @@ -372,35 +389,38 @@ void vvToolStructureSetManager::selectedItemChangedInTree() { //------------------------------------------------------------------------------ -void vvToolStructureSetManager::visibleROIToggled(bool b) { +void vvToolStructureSetManager::visibleROIToggled(bool b) +{ mCurrentROIActor->SetVisible(b); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolStructureSetManager::opacityChanged(int v) { +void vvToolStructureSetManager::opacityChanged(int v) +{ mCurrentROIActor->SetOpacity((double)v/100.0); mCurrentROIActor->UpdateColor(); - mCurrentSlicerManager->Render(); + mCurrentSlicerManager->Render(); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolStructureSetManager::changeColor() { +void vvToolStructureSetManager::changeColor() +{ QColor color; - color.setRgbF(mCurrentROIActor->GetROI()->GetDisplayColor()[0], - mCurrentROIActor->GetROI()->GetDisplayColor()[1], - mCurrentROIActor->GetROI()->GetDisplayColor()[2]); + color.setRgbF(mCurrentROIActor->GetROI()->GetDisplayColor()[0], + mCurrentROIActor->GetROI()->GetDisplayColor()[1], + mCurrentROIActor->GetROI()->GetDisplayColor()[2]); QColor c = QColorDialog::getColor(color, this, "Choose the ROI color"); mCurrentROIActor->GetROI()->SetDisplayColor(c.redF(), c.greenF(), c.blueF()); mCurrentROIActor->UpdateColor(); - QTreeWidgetItem * w = mMapROIToTreeWidget[mCurrentROI]; - QBrush brush(QColor(mCurrentROI->GetDisplayColor()[0]*255, - mCurrentROI->GetDisplayColor()[1]*255, - mCurrentROI->GetDisplayColor()[2]*255)); + QTreeWidgetItem * w = mMapROIToTreeWidget[mCurrentROI]; + QBrush brush(QColor(mCurrentROI->GetDisplayColor()[0]*255, + mCurrentROI->GetDisplayColor()[1]*255, + mCurrentROI->GetDisplayColor()[2]*255)); brush.setStyle(Qt::SolidPattern); for(int i=0; icolumnCount (); i++) { w->setBackground(i, brush); diff --git a/vv/vvToolWidgetBase.cxx b/vv/vvToolWidgetBase.cxx index d5632dc..d19e1d5 100644 --- a/vv/vvToolWidgetBase.cxx +++ b/vv/vvToolWidgetBase.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -23,8 +23,9 @@ //------------------------------------------------------------------------------ vvToolWidgetBase::vvToolWidgetBase(vvMainWindowBase * parent, Qt::WindowFlags f) - :QDialog(parent, f), - Ui::vvToolWidgetBase() { + :QDialog(parent, f), + Ui::vvToolWidgetBase() +{ // Set Modality : dialog is not modal but stay always on top because // parent is set at construction @@ -34,12 +35,12 @@ vvToolWidgetBase::vvToolWidgetBase(vvMainWindowBase * parent, Qt::WindowFlags f) setModal(false); setAttribute(Qt::WA_DeleteOnClose); mCurrentSlicerManager = 0; - + // GUI Initialization setupUi(this); - // Connect signals & slots - connect(mMainWindow, SIGNAL(AnImageIsBeingClosed(vvSlicerManager*)), + // Connect signals & slots + connect(mMainWindow, SIGNAL(AnImageIsBeingClosed(vvSlicerManager*)), this, SLOT(AnImageIsBeingClosed(vvSlicerManager*))); connect(mToolInputSelectionWidget, SIGNAL(accepted()), this, SLOT(InputIsSelected())); connect(mToolInputSelectionWidget, SIGNAL(rejected()), this, SLOT(close())); @@ -53,8 +54,9 @@ vvToolWidgetBase::vvToolWidgetBase(vvMainWindowBase * parent, Qt::WindowFlags f) //------------------------------------------------------------------------------ -vvToolWidgetBase::~vvToolWidgetBase() { - +vvToolWidgetBase::~vvToolWidgetBase() +{ + } //------------------------------------------------------------------------------ @@ -69,7 +71,8 @@ vvToolWidgetBase::~vvToolWidgetBase() { //------------------------------------------------------------------------------ -void vvToolWidgetBase::AddInputSelector(QString s, clitk::ImageToImageGenericFilterBase * f, bool allowSkip) { +void vvToolWidgetBase::AddInputSelector(QString s, clitk::ImageToImageGenericFilterBase * f, bool allowSkip) +{ // DD("AddInputSelector with filter"); // DD(mMainWindowBase->GetSlicerManagers().size()); int j=0; @@ -80,9 +83,9 @@ void vvToolWidgetBase::AddInputSelector(QString s, clitk::ImageToImageGenericFil // DD(i); vvImage * s = mMainWindow->GetSlicerManagers()[i]->GetImage(); // DD(s->GetScalarTypeAsString()); - if (mFilter->CheckImageType(s->GetNumberOfDimensions(), - s->GetNumberOfScalarComponents(), - s->GetScalarTypeAsString())) { + if (mFilter->CheckImageType(s->GetNumberOfDimensions(), + s->GetNumberOfScalarComponents(), + s->GetScalarTypeAsString())) { mSlicerManagersCompatible.push_back(mMainWindow->GetSlicerManagers()[i]); if ((int)i == mMainWindow->GetSlicerManagerCurrentIndex()) mCurrentCompatibleIndex = j; j++; @@ -99,7 +102,8 @@ void vvToolWidgetBase::AddInputSelector(QString s, clitk::ImageToImageGenericFil //------------------------------------------------------------------------------ -void vvToolWidgetBase::AddInputSelector(QString s, bool allowSkip) { +void vvToolWidgetBase::AddInputSelector(QString s, bool allowSkip) +{ // DD("AddInput without filter"); // DD(mMainWindow->GetSlicerManagers().size()); mSlicerManagersCompatible.clear(); @@ -112,13 +116,14 @@ void vvToolWidgetBase::AddInputSelector(QString s, bool allowSkip) { return; } mToolInputSelectionWidget->AddInputSelector(s, mMainWindow->GetSlicerManagers(), - mMainWindow->GetSlicerManagerCurrentIndex(), allowSkip); + mMainWindow->GetSlicerManagerCurrentIndex(), allowSkip); } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -void vvToolWidgetBase::show() { +void vvToolWidgetBase::show() +{ if (!mIsInitialized) { // DD("show -> init"); mToolInputSelectionWidget->Initialize(); @@ -130,7 +135,8 @@ void vvToolWidgetBase::show() { //------------------------------------------------------------------------------ -bool vvToolWidgetBase::close() { +bool vvToolWidgetBase::close() +{ // DD("vvToolWidgetBase::close()"); return QDialog::close(); } @@ -138,7 +144,8 @@ bool vvToolWidgetBase::close() { //------------------------------------------------------------------------------ -void vvToolWidgetBase::AnImageIsBeingClosed(vvSlicerManager * m) { +void vvToolWidgetBase::AnImageIsBeingClosed(vvSlicerManager * m) +{ mToolInputSelectionWidget->AnImageIsBeingClosed(m); if (m == mCurrentSlicerManager) { close(); @@ -148,15 +155,16 @@ void vvToolWidgetBase::AnImageIsBeingClosed(vvSlicerManager * m) { //------------------------------------------------------------------------------ -void vvToolWidgetBase::InitializeInputs() { +void vvToolWidgetBase::InitializeInputs() +{ /* if (mFilter) { int j=0; mToolInputSelectionWidget->setToolTip(QString("%1").arg(mFilter->GetAvailableImageTypes().c_str())); for(unsigned int i=0; iGetSlicerManagers().size(); i++) { vvImage * s = mMainWindow->GetSlicerManagers()[i]->GetImage(); - if (mFilter->CheckImageType(s->GetNumberOfDimensions(), - s->GetNumberOfScalarComponents(), + if (mFilter->CheckImageType(s->GetNumberOfDimensions(), + s->GetNumberOfScalarComponents(), s->GetScalarTypeAsString())) { mSlicerManagersCompatible.push_back(mMainWindow->GetSlicerManagers()[i]); if ((int)i == mMainWindow->GetSlicerManagerCurrentIndex()) mCurrentCompatibleIndex = j; @@ -168,7 +176,7 @@ void vvToolWidgetBase::InitializeInputs() { mSlicerManagersCompatible = mMainWindow->GetSlicerManagers(); mCurrentCompatibleIndex = mMainWindow->GetSlicerManagerCurrentIndex(); } - mToolInputSelectionWidget->Initialize(mSlicerManagersCompatible, + mToolInputSelectionWidget->Initialize(mSlicerManagersCompatible, mCurrentCompatibleIndex); mIsInitialized = true; */ @@ -185,7 +193,8 @@ void vvToolWidgetBase::InitializeInputs() { //------------------------------------------------------------------------------ -void vvToolWidgetBase::InputIsSelected() { +void vvToolWidgetBase::InputIsSelected() +{ // DD("InputIsSelected"); buttonBox->setEnabled(true); std::vector & l = mToolInputSelectionWidget->GetSelectedInputs(); @@ -200,7 +209,8 @@ void vvToolWidgetBase::InputIsSelected() { //------------------------------------------------------------------------------ -void vvToolWidgetBase::InputIsSelected(vvSlicerManager * m) { +void vvToolWidgetBase::InputIsSelected(vvSlicerManager * m) +{ std::cerr << "You MUST overwrite this method vvToolWidgetBase::InputIsSelected(vvSlicerManager * m) if you use one single input" << std::endl; exit(0); } @@ -208,7 +218,8 @@ void vvToolWidgetBase::InputIsSelected(vvSlicerManager * m) { //------------------------------------------------------------------------------ -void vvToolWidgetBase::InputIsSelected(std::vector & l) { +void vvToolWidgetBase::InputIsSelected(std::vector & l) +{ buttonBox->setEnabled(true); // DD("InputIsSelected(vector)"); // DD(l.size()); diff --git a/vv/vvUtils.cxx b/vv/vvUtils.cxx index 1e01482..100aeb5 100644 --- a/vv/vvUtils.cxx +++ b/vv/vvUtils.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -28,31 +28,30 @@ typedef std::list FileListType; ///Returns the last images opened by the user FileListType GetRecentlyOpenedImages() { - std::ifstream in((QDir::homePath().toStdString() + "/" + vv_user_file).c_str()); - std::string current_file; - FileListType result; + std::ifstream in((QDir::homePath().toStdString() + "/" + vv_user_file).c_str()); + std::string current_file; + FileListType result; + in >> current_file; + while (in.good()) { + result.push_back(current_file); in >> current_file; - while (in.good()) - { - result.push_back(current_file); - in >> current_file; - } - in.close(); - return result; + } + in.close(); + return result; } ///Adds an image to the list of recently opened images void AddToRecentlyOpenedImages(std::string filename) { - FileListType file_list = GetRecentlyOpenedImages(); - FileListType::iterator i = std::find(file_list.begin(),file_list.end(),filename); - if (i != file_list.end()) // avoid dupes - file_list.erase(i); - while (file_list.size() >= 6) //keep list to a reasonable size - file_list.pop_back(); - file_list.push_front(filename); - std::ofstream out((QDir::homePath().toStdString() + "/" + vv_user_file).c_str(),std::ios_base::out | std::ios_base::trunc); - for (FileListType::iterator j = file_list.begin() ; j != file_list.end() ; j++) - out << (*j) << std::endl; - out.close(); + FileListType file_list = GetRecentlyOpenedImages(); + FileListType::iterator i = std::find(file_list.begin(),file_list.end(),filename); + if (i != file_list.end()) // avoid dupes + file_list.erase(i); + while (file_list.size() >= 6) //keep list to a reasonable size + file_list.pop_back(); + file_list.push_front(filename); + std::ofstream out((QDir::homePath().toStdString() + "/" + vv_user_file).c_str(),std::ios_base::out | std::ios_base::trunc); + for (FileListType::iterator j = file_list.begin() ; j != file_list.end() ; j++) + out << (*j) << std::endl; + out.close(); } diff --git a/vv/vvs.cxx b/vv/vvs.cxx index 4d0e457..c00ad46 100644 --- a/vv/vvs.cxx +++ b/vv/vvs.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: vv http://www.creatis.insa-lyon.fr/rio/vv - Authors belong to: + Authors belong to: - University of LYON http://www.universite-lyon.fr/ - Léon Bérard cancer center http://oncora1.lyon.fnclcc.fr - CREATIS CNRS laboratory http://www.creatis.insa-lyon.fr @@ -24,29 +24,29 @@ int main( int argc, char** argv ) { - initialize_IO(); - QApplication app(argc,argv); - vvDummyWindow w; - w.show(); - return app.exec(); + initialize_IO(); + QApplication app(argc,argv); + vvDummyWindow w; + w.show(); + return app.exec(); } vvDummyWindow::vvDummyWindow() { - setupUi(this); + setupUi(this); } void vvDummyWindow::Run() { - vvImageReader imr; - imr.SetInputFilename("CT_UNTAGGED2MM_0.mhd"); - imr.Update(IMAGE); - - vvMeshReader r; - r.SetImage(imr.GetOutput()); - r.SetFilename("struct.DCM"); - std::vector selected; - selected.push_back(1); - r.SetSelectedItems(selected); - r.Update(); + vvImageReader imr; + imr.SetInputFilename("CT_UNTAGGED2MM_0.mhd"); + imr.Update(IMAGE); + + vvMeshReader r; + r.SetImage(imr.GetOutput()); + r.SetFilename("struct.DCM"); + std::vector selected; + selected.push_back(1); + r.SetSelectedItems(selected); + r.Update(); }