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