]> Creatis software - clitk.git/blob - vv/vvMeshReader.cxx
Use vtkGDCMPolyDataReader to read mesh
[clitk.git] / vv / vvMeshReader.cxx
1 /*=========================================================================
2   Program:   vv                     http://www.creatis.insa-lyon.fr/rio/vv
3
4   Authors belong to:
5   - University of LYON              http://www.universite-lyon.fr/
6   - Léon Bérard cancer center       http://www.centreleonberard.fr
7   - CREATIS CNRS laboratory         http://www.creatis.insa-lyon.fr
8
9   This software is distributed WITHOUT ANY WARRANTY; without even
10   the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11   PURPOSE.  See the copyright notices for more information.
12
13   It is distributed under dual licence
14
15   - BSD        See included LICENSE.txt file
16   - CeCILL-B   http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
17   ===========================================================================**/
18
19 // std
20 #include <algorithm>
21
22 // qt
23 #include <QApplication>
24
25 // gdcm 
26 #include <gdcmFile.h>
27 #if GDCM_MAJOR_VERSION == 2
28 #include <gdcmReader.h>
29 #include <gdcmTag.h>
30 #include <gdcmAttribute.h>
31 #else
32 #include <gdcm.h>
33 #include <gdcmSQItem.h>
34 #endif
35
36 // vtk
37 #include <vtkSmartPointer.h>
38 #include <vtkAppendPolyData.h>
39 #include <vtkCellArray.h>
40 #include <vtkMetaImageWriter.h>
41 #include <vtkMetaImageReader.h>
42 #include <vtkPolyDataWriter.h>
43 #include <vtkImageData.h>
44 #include <vtkImageCast.h>
45 #include <vtkImageGaussianSmooth.h>
46
47 // clitk
48 #include "clitkCommon.h"
49 #include "clitkCommon.h"
50 #include "clitkDicomRT_StructureSet.h"
51 #include "vvMeshReader.h"
52 #include "vvProgressDialog.h"
53
54 //------------------------------------------------------------------------------
55 vvMeshReader::vvMeshReader() :
56 vtk_mode(false)
57 {}
58 //------------------------------------------------------------------------------
59
60
61 //------------------------------------------------------------------------------
62 void vvMeshReader::Update()
63 {
64   DD("vvMeshReader::Update");
65
66   //Show a progress bar only when opening a DC-struct (ie. multiple contours)
67   vvProgressDialog progress("Opening " + filename,(!vtk_mode) && (selected_contours.size()>1));
68   this->start();
69   while (this->isRunning()) {
70     progress.SetProgress(result.size(),selected_contours.size());
71     this->wait(50);
72     qApp->processEvents();
73   }
74 }
75 //------------------------------------------------------------------------------
76
77
78 //------------------------------------------------------------------------------
79 void vvMeshReader::run()
80 {
81   ///Verify the important stuff has been set
82   assert(filename != "");
83   if (vtk_mode) { //Read vtkPolyData
84     vvMesh::Pointer m=vvMesh::New();
85     m->ReadFromVTK(filename.c_str());
86     if (vf) m->propagateContour(vf);
87     m->ComputeMasks(image->GetVTKImages()[0],false); //don't extrude the contour
88     result.push_back(m);
89   } else { //Read a Dicom-struct file
90     assert(selected_contours.size() > 0);
91     assert(image);
92     std::vector<vvMesh::Pointer> contour_stacks=readSelectedContours();
93     for (std::vector<vvMesh::Pointer>::iterator i=contour_stacks.begin();
94          i!=contour_stacks.end(); i++) {
95       (*i)->ComputeMasks(image->GetVTKImages()[0],true); //Remesh the contour
96       (*i)->ComputeMeshes();
97       if (vf) (*i)->propagateContour(vf);
98       result.push_back(*i);
99     }
100   }
101 }
102 //------------------------------------------------------------------------------
103
104
105 //------------------------------------------------------------------------------
106 std::vector<std::pair<int,std::string> > vvMeshReader::GetROINames()
107 {
108   assert(filename!="");
109   std::vector<std::pair<int, std::string> > roi_names;
110   DD(GDCM_MAJOR_VERSION);
111   DD(CLITK_USE_SYSTEM_GDCM);
112
113 #if CLITK_USE_SYSTEM_GDCM == 1
114   // Read RT-struct data
115   DD("before read");
116   vtkSmartPointer<vtkGDCMPolyDataReader> areader = vtkGDCMPolyDataReader::New();
117   areader->SetFileName(filename.c_str());
118   areader->Update();
119   DD("after read");
120
121   // get info on roi names
122   vtkRTStructSetProperties * p = areader->GetRTStructSetProperties();
123   DD(p->GetNumberOfStructureSetROIs());
124   DD(p->GetStructureSetROIName(0));
125   DD(p->GetStructureSetROINumber(0));  
126   int n = p->GetNumberOfStructureSetROIs();
127   DD(n);
128   
129   for(unsigned int i=0; i<n; i++) {
130     std::string name = p->GetStructureSetROIName(i);
131     int nb = p->GetStructureSetROINumber(i);
132     roi_names.push_back(make_pair(nb,name));
133   }
134
135 #else
136 #if GDCM_MAJOR_VERSION == 2 
137
138     // duplicate code from  clitk::DicomRT_StructureSet::Read
139     gdcm::Reader * reader = new gdcm::Reader;
140     reader->SetFileName( filename.c_str() );
141     reader->Read();
142
143     const gdcm::DataSet &ds = reader->GetFile().GetDataSet();
144
145     // Check file type
146     //Verify if the file is a RT-Structure-Set dicom file
147     gdcm::File * mFile = &(reader->GetFile());
148     gdcm::MediaStorage ms;
149     ms.SetFromFile(*mFile);
150     if( ms != gdcm::MediaStorage::RTStructureSetStorage )
151       {
152         std::cerr << "Error. the file " << filename
153                   << " 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])"
154                   << std::endl;
155         exit(0);
156       }
157
158     gdcm::Attribute<0x8,0x60> modality;
159     modality.SetFromDataSet( ds );
160     if( modality.GetValue() != "RTSTRUCT" )
161       {
162         std::cerr << "Error. the file " << filename
163                   << " is not a Dicom Struct ? (must have 0x0008,0x0060 = RTSTRUCT [RT Structure Set Storage])"
164                   << std::endl;
165         exit(0);
166       }
167
168     gdcm::Attribute<0x20,0x10> studyid;
169     studyid.SetFromDataSet( ds );
170
171     gdcm::Tag tssroisq(0x3006,0x0020);
172     // 0x3006,0x0020 = [ Structure Set ROI Sequence ]
173     bool b = ds.FindDataElement(tssroisq);
174     if (!b) { // FIXME
175       clitkExceptionMacro("Error: tag 0x3006,0x0020 [ Structure Set ROI Sequence ] not found");
176     }
177   
178     const gdcm::DataElement &ssroisq = ds.GetDataElement( tssroisq );
179     gdcm::SmartPointer<gdcm::SequenceOfItems> roi_seq = ssroisq.GetValueAsSQ();
180     assert(roi_seq); // FIXME error message
181   
182     for(unsigned int ridx = 0; ridx < roi_seq->GetNumberOfItems(); ++ridx)
183       {
184          gdcm::Item & item = roi_seq->GetItem( ridx + 1); // Item starts at 1
185
186         const gdcm::Item & sitem = roi_seq->GetItem(ridx+1); // Item start at #1   
187
188         const gdcm::DataSet& snestedds = sitem.GetNestedDataSet();
189         const gdcm::DataSet& nestedds = item.GetNestedDataSet();
190
191         if( snestedds.FindDataElement( gdcm::Tag(0x3006,0x22) ) )
192           {
193             // const gdcm::DataElement & a = nestedds.GetDataElement(gdcm::Tag(0x3006,0x26));
194             // DD(a.GetValue());
195
196             gdcm::Attribute<0x3006,0x26> roiname;
197             roiname.SetFromDataSet( snestedds );
198             std::string name = roiname.GetValue();      // 0x3006,0x0026 = [ROI Name]
199             gdcm::Attribute<0x3006,0x0022> roinumber;
200             roinumber.SetFromDataSet( snestedds );
201             int nb = roinumber.GetValue();  // 0x3006,0x0022 = [ROI Number]
202           
203             roi_names.push_back(make_pair(nb,name));
204           }
205       }
206   
207     delete reader;
208
209 #else
210   gdcm::File reader;
211   reader.SetFileName(filename.c_str());
212   reader.SetMaxSizeLoadEntry(16384);
213   reader.Load();
214
215   gdcm::SeqEntry * roi_info=reader.GetSeqEntry(0x3006,0x0020);
216   assert(roi_info);
217   // DD("ici");
218   //int n=0;
219   for (gdcm::SQItem* i=roi_info->GetFirstSQItem(); i!=0; i=roi_info->GetNextSQItem())
220     if (i->GetEntryValue(0x3006,0x0022)!= gdcm::GDCM_UNFOUND)
221       roi_names.push_back(make_pair(atoi(i->GetEntryValue(0x3006,0x0022).c_str()),i->GetEntryValue(0x3006,0x0026)));
222 #endif
223 #endif
224
225   return roi_names;
226
227 }
228 //------------------------------------------------------------------------------
229
230
231 //------------------------------------------------------------------------------
232 std::vector<vvMesh::Pointer> vvMeshReader::readSelectedContours()
233 {
234   std::vector<vvMesh::Pointer> result;
235 #if GDCM_MAJOR_VERSION == 2
236
237 #if CLITK_USE_SYSTEM_GDCM == 0
238   
239   clitkExceptionMacro("ERROR ! You need to compile vv with itk4 + system_gdcm to use this function");
240
241 #endif
242
243   gdcm::Reader reader;
244   reader.SetFileName(filename.c_str());
245   reader.Read();
246
247   const gdcm::DataSet &ds = reader.GetFile().GetDataSet();
248
249   gdcm::SmartPointer<gdcm::SequenceOfItems> rois = ds.GetDataElement(gdcm::Tag(0x3006,0x39)).GetValueAsSQ();
250   gdcm::SmartPointer<gdcm::SequenceOfItems> roi_info = ds.GetDataElement(gdcm::Tag(0x3006,0x20)).GetValueAsSQ();
251   assert(rois); // TODO error message
252   assert(roi_info); // TODO error message
253   assert(rois->GetNumberOfItems() == roi_info->GetNumberOfItems());
254
255   for (unsigned ridx = 0; ridx < rois->GetNumberOfItems(); ++ridx)
256     {
257       vtkSmartPointer<vtkAppendPolyData> append=vtkSmartPointer<vtkAppendPolyData>::New();
258       const gdcm::DataSet& ds_rois = rois->GetItem( ridx + 1).GetNestedDataSet();
259       const gdcm::DataSet& ds_roi_info = roi_info->GetItem( ridx + 1).GetNestedDataSet();
260
261       gdcm::Attribute<0x3006,0x84> roinumber;
262       roinumber.SetFromDataSet(ds_rois);
263       if (std::find(selected_contours.begin(), selected_contours.end(), roinumber.GetValue()) != selected_contours.end()) //Only read selected ROIs
264         {
265           gdcm::Attribute<0x3006,0x2a> trgb;
266           trgb.SetFromDataSet(ds_rois);
267           vvMesh::Pointer current_roi=vvMesh::New();
268           current_roi->r = trgb[0] / 255.0;
269           current_roi->g = trgb[1] / 255.0;
270           current_roi->b = trgb[2] / 255.0;
271
272           gdcm::Attribute<0x3006,0x26> tstructure_name;
273           tstructure_name.SetFromDataSet(ds_roi_info);
274           current_roi->structure_name = tstructure_name.GetValue();
275
276           gdcm::SmartPointer<gdcm::SequenceOfItems> roi_seq = ds_rois.GetDataElement(gdcm::Tag(0x3006,0x40)).GetValueAsSQ();
277           double z0=-1; //Used to determine spacing between slices, assumed to be constant
278           for (unsigned j = 0; j < roi_seq->GetNumberOfItems(); ++j)
279             {
280               gdcm::Item & item_roi_seq = roi_seq->GetItem(j + 1); // Item starts at 1
281               const gdcm::DataSet& ds_roi_seq = item_roi_seq.GetNestedDataSet();
282               gdcm::Attribute<0x3006,0x42> tcontour_type;
283               tcontour_type.SetFromDataSet(ds_roi_seq);
284               std::string contour_type = tcontour_type.GetValue();
285               if (contour_type=="CLOSED_PLANAR ")
286                 {
287                   gdcm::Attribute<0x3006,0x46> tpoint_number;
288                   tpoint_number.SetFromDataSet(ds_roi_seq);
289                   const gdcm::DataElement & points_data = ds_roi_seq.GetDataElement(gdcm::Tag(0x3006,0x50));
290                   gdcm::Attribute<0x3006,0x50> tpoints;
291                   tpoints.SetFromDataElement(points_data);
292                   assert(tpoints.GetNumberOfValues() == static_cast<unsigned int>(tpoint_number.GetValue()) * 3);
293                   const double* points = tpoints.GetValues();
294                   if (z0 == -1) //First contour
295                     z0=points[2];
296                   else
297                     if (current_roi->GetSpacing()==-1 && points[2] != z0 )
298                       current_roi->SetSpacing(points[2]-z0);
299                   vtkPolyData * contour=vtkPolyData::New();
300                   contour->Allocate(); //for cell structures
301                   contour->SetPoints(vtkPoints::New());
302                   vtkIdType ids[2];
303                   for (unsigned idx = 0; idx < tpoints.GetNumberOfValues(); idx += 3)
304                     {
305                       contour->GetPoints()->InsertNextPoint(points[idx], points[idx+1], points[idx+2]);
306                       ids[0] = idx / 3;
307                       ids[1] = (ids[0] + 1) % tpoint_number.GetValue(); //0-1,1-2,...,n-1-0
308                       contour->GetLines()->InsertNextCell(2, ids);
309                     }
310                   append->AddInput(contour);
311                 }
312               else
313                 if (contour_type == "POINT ")
314                   ; // silently ignore POINT type since we don't need them at the moment
315                 else
316                   std::cerr << "Warning: contour type " << contour_type << " not handled!" << std::endl;
317             }
318           append->Update();
319           current_roi->AddMesh(append->GetOutput());
320           result.push_back(current_roi);
321         }
322       else
323         {
324           //std::cerr << "Warning: ignoring ROI #" << roi_number << std::endl;
325         }
326     }
327 #else
328   gdcm::File reader;
329   reader.SetFileName(filename.c_str());
330   reader.SetMaxSizeLoadEntry(16384);
331   reader.Load();
332
333   gdcm::SeqEntry * rois=reader.GetSeqEntry(0x3006,0x0039);
334   ///We need to iterate both on the contours themselves, and on the contour info
335   gdcm::SeqEntry * roi_info=reader.GetSeqEntry(0x3006,0x0020);
336   gdcm::SQItem* k=roi_info->GetFirstSQItem();
337   for(gdcm::SQItem* i=rois->GetFirstSQItem(); i!=0; i=rois->GetNextSQItem()) { //loop over ROIS
338     assert(k!=0);
339     vtkSmartPointer<vtkAppendPolyData> append=vtkSmartPointer<vtkAppendPolyData>::New();
340     std::istringstream ss(i->GetEntryValue(0x3006,0x0084));
341     int roi_number;
342     ss >> roi_number;
343     if (std::find(selected_contours.begin(),selected_contours.end(),roi_number) != selected_contours.end()) { //Only read selected ROIs
344       vvMesh::Pointer current_roi=vvMesh::New();
345       std::vector<double> rgb=clitk::parse_string<double>(i->GetEntryValue(0x3006,0x002a),'\\');
346       assert(rgb.size()==3);
347       current_roi->r=rgb[0]/255;
348       current_roi->g=rgb[1]/255;
349       current_roi->b=rgb[2]/255;
350       current_roi->structure_name=k->GetEntryValue(0x3006,0x0026);
351       gdcm::SeqEntry * contours=i->GetSeqEntry(0x3006,0x0040);
352       double z0=-1; //Used to determine spacing between slices, assumed to be constant
353       for(gdcm::SQItem* j=contours->GetFirstSQItem(); j!=0; j=contours->GetNextSQItem()) { //loop over 2D contours
354         std::string contour_type=j->GetEntryValue(0x3006,0x0042);
355         if (contour_type=="CLOSED_PLANAR ") {
356           int point_number=clitk::parse_value<int>(j->GetEntryValue(0x3006,0x0046));
357           std::vector<float> points=clitk::parse_string<float>(j->GetEntryValue(0x3006,0x0050),'\\');
358           assert(points.size() == static_cast<unsigned int>(point_number)*3);
359           if (z0 == -1) //First contour
360             z0=points[2];
361           //2nd contour, spacing not yet set. Need to be sure we are on a different slice,
362           //sometimes there is more than one closed contour per slice
363           else if (current_roi->GetSpacing()==-1 && points[2] != z0 )
364             current_roi->SetSpacing(points[2]-z0);
365           vtkPolyData * contour=vtkPolyData::New();
366           contour->Allocate(); //for cell structures
367           contour->SetPoints(vtkPoints::New());
368           vtkIdType ids[2];
369           for (unsigned int idx=0; idx<points.size(); idx+=3) {
370             contour->GetPoints()->InsertNextPoint(points[idx],points[idx+1],points[idx+2]);
371             ids[0]=idx/3;
372             ids[1]=(ids[0]+1)%point_number; //0-1,1-2,...,n-1-0
373             contour->GetLines()->InsertNextCell(2,ids);
374           }
375           append->AddInput(contour);
376         } else if (contour_type == "POINT ")
377           ; // silently ignore POINT type since we don't need them at the moment
378         else
379           std::cerr << "Warning: contour type " << contour_type << " not handled!" << std::endl;
380       }
381       append->Update();
382       current_roi->AddMesh(append->GetOutput());
383       result.push_back(current_roi);
384     } else {
385       //std::cerr << "Warning: ignoring ROI #" << roi_number << std::endl;
386     }
387     k=roi_info->GetNextSQItem(); //increment the second loop variable
388   }
389 #endif
390   return result;
391 }
392