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