comparison Framework/Toolbox/DicomStructureSet.cpp @ 0:351ab0da0150

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 14 Oct 2016 15:34:11 +0200
parents
children ff1e935768e7
comparison
equal deleted inserted replaced
-1:000000000000 0:351ab0da0150
1 /**
2 * Stone of Orthanc
3 * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics
4 * Department, University Hospital of Liege, Belgium
5 *
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * In addition, as a special exception, the copyright holders of this
12 * program give permission to link the code of its release with the
13 * OpenSSL project's "OpenSSL" library (or with modified versions of it
14 * that use the same license as the "OpenSSL" library), and distribute
15 * the linked executables. You must obey the GNU General Public License
16 * in all respects for all of the code used other than "OpenSSL". If you
17 * modify file(s) with this exception, you may extend this exception to
18 * your version of the file(s), but you are not obligated to do so. If
19 * you do not wish to do so, delete this exception statement from your
20 * version. If you delete this exception statement from all source files
21 * in the program, then also delete it here.
22 *
23 * This program is distributed in the hope that it will be useful, but
24 * WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 * General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 **/
31
32
33 #include "DicomStructureSet.h"
34
35 #include "../Orthanc/Core/Logging.h"
36 #include "../Orthanc/Core/OrthancException.h"
37 #include "../Messaging/MessagingToolbox.h"
38
39 #include <stdio.h>
40 #include <boost/lexical_cast.hpp>
41
42 namespace OrthancStone
43 {
44 static const Json::Value& GetSequence(const Json::Value& instance,
45 uint16_t group,
46 uint16_t element)
47 {
48 char buf[16];
49 sprintf(buf, "%04x,%04x", group, element);
50
51 if (instance.type() != Json::objectValue ||
52 !instance.isMember(buf) ||
53 instance[buf].type() != Json::objectValue ||
54 !instance[buf].isMember("Type") ||
55 !instance[buf].isMember("Value") ||
56 instance[buf]["Type"].type() != Json::stringValue ||
57 instance[buf]["Value"].type() != Json::arrayValue ||
58 instance[buf]["Type"].asString() != "Sequence")
59 {
60 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
61 }
62
63 return instance[buf]["Value"];
64 }
65
66
67 static uint8_t ConvertColor(double v)
68 {
69 if (v < 0)
70 {
71 return 0;
72 }
73 else if (v >= 255)
74 {
75 return 255;
76 }
77 else
78 {
79 return static_cast<uint8_t>(v);
80 }
81 }
82
83
84 SliceGeometry DicomStructureSet::ExtractSliceGeometry(double& sliceThickness,
85 IOrthancConnection& orthanc,
86 const Json::Value& contour)
87 {
88 const Json::Value& sequence = GetSequence(contour, 0x3006, 0x0016);
89
90 if (sequence.size() != 1)
91 {
92 throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented);
93 }
94
95 DicomDataset contourImageSequence(sequence[0]);
96 std::string parentUid = contourImageSequence.GetStringValue(std::make_pair(0x0008, 0x1155));
97
98 std::string post;
99 orthanc.RestApiPost(post, "/tools/lookup", parentUid);
100
101 Json::Value tmp;
102 MessagingToolbox::ParseJson(tmp, post);
103
104 if (tmp.type() != Json::arrayValue ||
105 tmp.size() != 1 ||
106 !tmp[0].isMember("Type") ||
107 !tmp[0].isMember("Path") ||
108 tmp[0]["Type"].type() != Json::stringValue ||
109 tmp[0]["ID"].type() != Json::stringValue ||
110 tmp[0]["Type"].asString() != "Instance")
111 {
112 throw Orthanc::OrthancException(Orthanc::ErrorCode_UnknownResource);
113 }
114
115 Json::Value parentInstance;
116 MessagingToolbox::RestApiGet(parentInstance, orthanc, "/instances/" + tmp[0]["ID"].asString());
117
118 if (parentInstance.type() != Json::objectValue ||
119 !parentInstance.isMember("ParentSeries") ||
120 parentInstance["ParentSeries"].type() != Json::stringValue)
121 {
122 throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol);
123 }
124
125 std::string parentSeriesId = parentInstance["ParentSeries"].asString();
126 bool isFirst = parentSeriesId_.empty();
127
128 if (isFirst)
129 {
130 parentSeriesId_ = parentSeriesId;
131 }
132 else if (parentSeriesId_ != parentSeriesId)
133 {
134 LOG(ERROR) << "This RT-STRUCT refers to several different series";
135 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
136 }
137
138 Json::Value parentTags;
139 MessagingToolbox::RestApiGet(parentTags, orthanc, "/instances/" + tmp[0]["ID"].asString() + "/tags?simplify");
140
141 if (parentTags.type() != Json::objectValue ||
142 !parentTags.isMember("ImageOrientationPatient") ||
143 !parentTags.isMember("ImagePositionPatient") ||
144 parentTags["ImageOrientationPatient"].type() != Json::stringValue ||
145 parentTags["ImagePositionPatient"].type() != Json::stringValue)
146 {
147 throw Orthanc::OrthancException(Orthanc::ErrorCode_NetworkProtocol);
148 }
149
150 SliceGeometry slice(parentTags["ImagePositionPatient"].asString(),
151 parentTags["ImageOrientationPatient"].asString());
152
153 sliceThickness = 1; // 1 mm by default
154
155 if (parentTags.isMember("SliceThickness") &&
156 parentTags["SliceThickness"].type() == Json::stringValue)
157 {
158 Vector tmp;
159 GeometryToolbox::ParseVector(tmp, parentTags["SliceThickness"].asString());
160 if (tmp.size() > 0)
161 {
162 sliceThickness = tmp[0];
163 }
164 }
165
166 if (isFirst)
167 {
168 normal_ = slice.GetNormal();
169 }
170 else if (!GeometryToolbox::IsParallel(normal_, slice.GetNormal()))
171 {
172 LOG(ERROR) << "Incompatible orientation of slices in this RT-STRUCT";
173 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
174 }
175
176 return slice;
177 }
178
179
180 const DicomStructureSet::Structure& DicomStructureSet::GetStructure(size_t index) const
181 {
182 if (index >= structures_.size())
183 {
184 throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented);
185 }
186
187 return structures_[index];
188 }
189
190
191 bool DicomStructureSet::IsPolygonOnSlice(const Polygon& polygon,
192 const SliceGeometry& geometry) const
193 {
194 double d = boost::numeric::ublas::inner_prod(geometry.GetOrigin(), normal_);
195
196 return (GeometryToolbox::IsNear(d, polygon.projectionAlongNormal_, polygon.sliceThickness_ / 2.0) &&
197 !polygon.points_.empty());
198 }
199
200
201 DicomStructureSet::DicomStructureSet(IOrthancConnection& orthanc,
202 const std::string& instanceId)
203 {
204 Json::Value instance;
205 MessagingToolbox::RestApiGet(instance, orthanc, "/instances/" + instanceId + "/tags");
206
207 Json::Value rtRoiObservationSequence = GetSequence(instance, 0x3006, 0x0080);
208 Json::Value roiContourSequence = GetSequence(instance, 0x3006, 0x0039);
209 Json::Value structureSetRoiSequence = GetSequence(instance, 0x3006, 0x0020);
210
211 Json::Value::ArrayIndex count = rtRoiObservationSequence.size();
212 if (count != roiContourSequence.size() ||
213 count != structureSetRoiSequence.size())
214 {
215 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
216 }
217
218 structures_.resize(count);
219 for (Json::Value::ArrayIndex i = 0; i < count; i++)
220 {
221 DicomDataset observation(rtRoiObservationSequence[i]);
222 DicomDataset roi(structureSetRoiSequence[i]);
223 DicomDataset content(roiContourSequence[i]);
224
225 structures_[i].interpretation_ = observation.GetStringValue(std::make_pair(0x3006, 0x00a4), "No interpretation");
226 structures_[i].name_ = roi.GetStringValue(std::make_pair(0x3006, 0x0026), "No name");
227 structures_[i].red_ = 255;
228 structures_[i].green_ = 0;
229 structures_[i].blue_ = 0;
230
231 DicomDataset::Tag tag(0x3006, 0x002a);
232
233 Vector color;
234 if (content.HasTag(tag))
235 {
236 content.GetVectorValue(color, tag);
237 if (color.size() == 3)
238 {
239 structures_[i].red_ = ConvertColor(color[0]);
240 structures_[i].green_ = ConvertColor(color[1]);
241 structures_[i].blue_ = ConvertColor(color[2]);
242 }
243 }
244
245 const Json::Value& slices = GetSequence(roiContourSequence[i], 0x3006, 0x0040);
246
247 LOG(WARNING) << "New RT structure: \"" << structures_[i].name_
248 << "\" with interpretation \"" << structures_[i].interpretation_
249 << "\" containing " << slices.size() << " slices (color: "
250 << static_cast<int>(structures_[i].red_) << ","
251 << static_cast<int>(structures_[i].green_) << ","
252 << static_cast<int>(structures_[i].blue_) << ")";
253
254 for (Json::Value::ArrayIndex j = 0; j < slices.size(); j++)
255 {
256 DicomDataset slice(slices[j]);
257
258 unsigned int npoints = slice.GetUnsignedIntegerValue(std::make_pair(0x3006, 0x0046));
259 LOG(INFO) << "Parsing slice containing " << npoints << " vertices";
260
261 if (slice.GetStringValue(std::make_pair(0x3006, 0x0042)) != "CLOSED_PLANAR")
262 {
263 throw Orthanc::OrthancException(Orthanc::ErrorCode_NotImplemented);
264 }
265
266 std::string slicesData;
267 orthanc.RestApiGet(slicesData, "/instances/" + instanceId + "/content/3006-0039/" +
268 boost::lexical_cast<std::string>(i) + "/3006-0040/" +
269 boost::lexical_cast<std::string>(j) + "/3006-0050");
270
271 Vector points;
272 if (!GeometryToolbox::ParseVector(points, slicesData) ||
273 points.size() != 3 * npoints)
274 {
275 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
276 }
277
278 Polygon polygon;
279 SliceGeometry geometry = ExtractSliceGeometry(polygon.sliceThickness_, orthanc, slices[j]);
280 polygon.projectionAlongNormal_ = geometry.ProjectAlongNormal(geometry.GetOrigin());
281
282 for (size_t k = 0; k < npoints; k++)
283 {
284 Vector v(3);
285 v[0] = points[3 * k];
286 v[1] = points[3 * k + 1];
287 v[2] = points[3 * k + 2];
288
289 if (!GeometryToolbox::IsNear(geometry.ProjectAlongNormal(v),
290 polygon.projectionAlongNormal_,
291 polygon.sliceThickness_ / 2.0 /* in mm */))
292 {
293 LOG(ERROR) << "This RT-STRUCT contains a point that is off the slice of its instance";
294 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
295 }
296
297 polygon.points_.push_back(v);
298 }
299
300 structures_[i].polygons_.push_back(polygon);
301 }
302 }
303
304 if (parentSeriesId_.empty() ||
305 normal_.size() != 3)
306 {
307 throw Orthanc::OrthancException(Orthanc::ErrorCode_BadFileFormat);
308 }
309 }
310
311
312 Vector DicomStructureSet::GetStructureCenter(size_t index) const
313 {
314 const Structure& structure = GetStructure(index);
315
316 Vector center;
317 GeometryToolbox::AssignVector(center, 0, 0, 0);
318 if (structure.polygons_.empty())
319 {
320 return center;
321 }
322
323 double n = static_cast<double>(structure.polygons_.size());
324
325 for (Polygons::const_iterator polygon = structure.polygons_.begin();
326 polygon != structure.polygons_.end(); ++polygon)
327 {
328 if (!polygon->points_.empty())
329 {
330 center += polygon->points_.front() / n;
331 }
332 }
333
334 return center;
335 }
336
337
338 const std::string& DicomStructureSet::GetStructureName(size_t index) const
339 {
340 return GetStructure(index).name_;
341 }
342
343
344 const std::string& DicomStructureSet::GetStructureInterpretation(size_t index) const
345 {
346 return GetStructure(index).interpretation_;
347 }
348
349
350 void DicomStructureSet::GetStructureColor(uint8_t& red,
351 uint8_t& green,
352 uint8_t& blue,
353 size_t index) const
354 {
355 const Structure& s = GetStructure(index);
356 red = s.red_;
357 green = s.green_;
358 blue = s.blue_;
359 }
360
361
362 void DicomStructureSet::Render(CairoContext& context,
363 const SliceGeometry& slice) const
364 {
365 cairo_t* cr = context.GetObject();
366
367 for (Structures::const_iterator structure = structures_.begin();
368 structure != structures_.end(); ++structure)
369 {
370 for (Polygons::const_iterator polygon = structure->polygons_.begin();
371 polygon != structure->polygons_.end(); ++polygon)
372 {
373 if (IsPolygonOnSlice(*polygon, slice))
374 {
375 context.SetSourceColor(structure->red_, structure->green_, structure->blue_);
376
377 Points::const_iterator p = polygon->points_.begin();
378
379 double x, y;
380 slice.ProjectPoint(x, y, *p);
381 cairo_move_to(cr, x, y);
382 ++p;
383
384 while (p != polygon->points_.end())
385 {
386 slice.ProjectPoint(x, y, *p);
387 cairo_line_to(cr, x, y);
388 ++p;
389 }
390
391 slice.ProjectPoint(x, y, *polygon->points_.begin());
392 cairo_line_to(cr, x, y);
393 }
394 }
395 }
396
397 cairo_stroke(cr);
398 }
399 }