comparison Plugin/ParsedDicomImage.cpp @ 0:02f7a0400a91

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 25 Feb 2015 13:45:35 +0100
parents
children 828c61fc8253
comparison
equal deleted inserted replaced
-1:000000000000 0:02f7a0400a91
1 /**
2 * Orthanc - A Lightweight, RESTful DICOM Store
3 * Copyright (C) 2012-2015 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 Affero General Public License
8 * as published by the Free Software Foundation, either version 3 of
9 * the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 **/
19
20
21 #include "ParsedDicomImage.h"
22
23 #include "../Orthanc/OrthancException.h"
24 #include "../Orthanc/Toolbox.h"
25 #include "../Orthanc/ImageFormats/ImageProcessing.h"
26 #include "../Orthanc/ImageFormats/ImageBuffer.h"
27 #include "JpegWriter.h"
28 #include "ViewerToolbox.h"
29
30 #include <gdcmImageReader.h>
31 #include <gdcmImageChangePlanarConfiguration.h>
32 #include <gdcmImageChangePhotometricInterpretation.h>
33 #include <boost/lexical_cast.hpp>
34 #include <boost/math/special_functions/round.hpp>
35
36 #include "../Resources/ThirdParty/base64/base64.h"
37
38
39 namespace OrthancPlugins
40 {
41 struct ParsedDicomImage::PImpl
42 {
43 gdcm::ImageReader reader_;
44 std::auto_ptr<gdcm::ImageChangePhotometricInterpretation> photometric_;
45 std::auto_ptr<gdcm::ImageChangePlanarConfiguration> interleaved_;
46 std::string decoded_;
47
48 const gdcm::Image& GetImage() const
49 {
50 if (interleaved_.get() != NULL)
51 {
52 return interleaved_->GetOutput();
53 }
54
55 if (photometric_.get() != NULL)
56 {
57 return photometric_->GetOutput();
58 }
59
60 return reader_.GetImage();
61 }
62
63
64 const gdcm::DataSet& GetDataSet() const
65 {
66 return reader_.GetFile().GetDataSet();
67 }
68 };
69
70
71 template <typename TargetType, typename SourceType>
72 static void ChangeDynamics(Orthanc::ImageAccessor& target,
73 const Orthanc::ImageAccessor& source,
74 SourceType source1, TargetType target1,
75 SourceType source2, TargetType target2)
76 {
77 if (source.GetWidth() != target.GetWidth() ||
78 source.GetHeight() != target.GetHeight())
79 {
80 throw Orthanc::OrthancException(Orthanc::ErrorCode_IncompatibleImageSize);
81 }
82
83 float scale = static_cast<float>(target2 - target1) / static_cast<float>(source2 - source1);
84 float offset = static_cast<float>(target1) - scale * static_cast<float>(source1);
85
86 const float minValue = static_cast<float>(std::numeric_limits<TargetType>::min());
87 const float maxValue = static_cast<float>(std::numeric_limits<TargetType>::max());
88
89 for (unsigned int y = 0; y < source.GetHeight(); y++)
90 {
91 const SourceType* p = reinterpret_cast<const SourceType*>(source.GetConstRow(y));
92 TargetType* q = reinterpret_cast<TargetType*>(target.GetRow(y));
93
94 for (unsigned int x = 0; x < source.GetWidth(); x++, p++, q++)
95 {
96 float v = (scale * static_cast<float>(*p)) + offset;
97
98 if (v > maxValue)
99 {
100 *q = std::numeric_limits<TargetType>::max();
101 }
102 else if (v < minValue)
103 {
104 *q = std::numeric_limits<TargetType>::min();
105 }
106 else
107 {
108 *q = static_cast<TargetType>(boost::math::iround(v));
109 }
110 }
111 }
112 }
113
114
115 void ParsedDicomImage::Setup(const std::string& dicom)
116 {
117 // Prepare a memory stream over the DICOM instance
118 std::stringstream stream(dicom);
119
120 // Parse the DICOM instance using GDCM
121 pimpl_->reader_.SetStream(stream);
122 if (!pimpl_->reader_.Read())
123 {
124 throw Orthanc::OrthancException("GDCM cannot extract an image from this DICOM instance");
125 }
126
127 // Change photometric interpretation, if required
128 {
129 const gdcm::Image& image = pimpl_->GetImage();
130 if (image.GetPixelFormat().GetSamplesPerPixel() == 1)
131 {
132 if (image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::MONOCHROME1 &&
133 image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::MONOCHROME2)
134 {
135 pimpl_->photometric_.reset(new gdcm::ImageChangePhotometricInterpretation());
136 pimpl_->photometric_->SetInput(image);
137 pimpl_->photometric_->SetPhotometricInterpretation(gdcm::PhotometricInterpretation::MONOCHROME2);
138 if (!pimpl_->photometric_->Change())
139 {
140 throw Orthanc::OrthancException("GDCM cannot change the photometric interpretation");
141 }
142 }
143 }
144 else
145 {
146 if (image.GetPixelFormat().GetSamplesPerPixel() == 3 &&
147 image.GetPhotometricInterpretation() != gdcm::PhotometricInterpretation::RGB)
148 {
149 pimpl_->photometric_.reset(new gdcm::ImageChangePhotometricInterpretation());
150 pimpl_->photometric_->SetInput(image);
151 pimpl_->photometric_->SetPhotometricInterpretation(gdcm::PhotometricInterpretation::RGB);
152 if (!pimpl_->photometric_->Change())
153 {
154 throw Orthanc::OrthancException("GDCM cannot change the photometric interpretation");
155 }
156 }
157 }
158 }
159
160 // Possibly convert planar configuration to interleaved
161 {
162 const gdcm::Image& image = pimpl_->GetImage();
163 if (image.GetPlanarConfiguration() != 0 &&
164 image.GetPixelFormat().GetSamplesPerPixel() != 1)
165 {
166 pimpl_->interleaved_.reset(new gdcm::ImageChangePlanarConfiguration());
167 pimpl_->interleaved_->SetInput(image);
168 if (!pimpl_->interleaved_->Change())
169 {
170 throw Orthanc::OrthancException("GDCM cannot change the planar configuration to interleaved");
171 }
172 }
173 }
174
175 // Decode the image to the memory buffer
176 {
177 const gdcm::Image& image = pimpl_->GetImage();
178 pimpl_->decoded_.resize(image.GetBufferLength());
179
180 if (pimpl_->decoded_.size() > 0)
181 {
182 image.GetBuffer(&pimpl_->decoded_[0]);
183 }
184 }
185 }
186
187
188 ParsedDicomImage::ParsedDicomImage(const std::string& dicom) : pimpl_(new PImpl)
189 {
190 Setup(dicom);
191 }
192
193
194 bool ParsedDicomImage::GetTag(std::string& result,
195 uint16_t group,
196 uint16_t element,
197 bool stripSpaces)
198 {
199 const gdcm::Tag tag(group, element);
200
201 if (pimpl_->GetDataSet().FindDataElement(tag))
202 {
203 const gdcm::ByteValue* value = pimpl_->GetDataSet().GetDataElement(tag).GetByteValue();
204 if (value)
205 {
206 result = std::string(value->GetPointer(), value->GetLength());
207
208 if (stripSpaces)
209 {
210 result = Orthanc::Toolbox::StripSpaces(result);
211 }
212
213 return true;
214 }
215 }
216
217 return false;
218 }
219
220
221 bool ParsedDicomImage::GetAccessor(Orthanc::ImageAccessor& accessor)
222 {
223 const gdcm::Image& image = pimpl_->GetImage();
224
225 size_t size = pimpl_->decoded_.size();
226 void* buffer = (size ? &pimpl_->decoded_[0] : NULL);
227 unsigned int height = image.GetRows();
228 unsigned int width = image.GetColumns();
229
230 if (image.GetPixelFormat().GetSamplesPerPixel() == 1 &&
231 (image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::MONOCHROME1 ||
232 image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::MONOCHROME2))
233 {
234 switch (image.GetPixelFormat())
235 {
236 case gdcm::PixelFormat::UINT16:
237 accessor.AssignWritable(Orthanc::PixelFormat_Grayscale16, width, height, 2 * width, buffer);
238 return true;
239
240 case gdcm::PixelFormat::INT16:
241 accessor.AssignWritable(Orthanc::PixelFormat_SignedGrayscale16, width, height, 2 * width, buffer);
242 return true;
243
244 case gdcm::PixelFormat::UINT8:
245 accessor.AssignWritable(Orthanc::PixelFormat_Grayscale8, width, height, width, buffer);
246 return true;
247 }
248 }
249 else if (image.GetPixelFormat().GetSamplesPerPixel() == 3 &&
250 image.GetPhotometricInterpretation() == gdcm::PhotometricInterpretation::RGB)
251 {
252 switch (image.GetPixelFormat())
253 {
254 case gdcm::PixelFormat::UINT8:
255 accessor.AssignWritable(Orthanc::PixelFormat_RGB24, width, height, 3 * width, buffer);
256 return true;
257 }
258 }
259
260 return false;
261 }
262
263 bool ParsedDicomImage::GetCornerstoneMetadata(Json::Value& json)
264 {
265 using namespace Orthanc;
266
267 ImageAccessor accessor;
268 if (!GetAccessor(accessor))
269 {
270 return false;
271 }
272
273 float windowCenter, windowWidth;
274
275 switch (accessor.GetFormat())
276 {
277 case PixelFormat_Grayscale8:
278 case PixelFormat_Grayscale16:
279 case PixelFormat_SignedGrayscale16:
280 {
281 int64_t a, b;
282 Orthanc::ImageProcessing::GetMinMaxValue(a, b, accessor);
283 json["minPixelValue"] = (a < 0 ? static_cast<int32_t>(a) : 0);
284 json["maxPixelValue"] = (b > 0 ? static_cast<int32_t>(b) : 1);
285 json["color"] = false;
286
287 windowCenter = static_cast<float>(a + b) / 2.0f;
288
289 if (a == b)
290 {
291 windowWidth = 127.5f; // Arbitrary value
292 }
293 else
294 {
295 windowWidth = static_cast<float>(b - a) / 2.0f;
296 }
297
298 break;
299 }
300
301 case PixelFormat_RGB24:
302 json["minPixelValue"] = 0;
303 json["maxPixelValue"] = 255;
304 json["color"] = true;
305 windowCenter = 127.5f;
306 windowWidth = 127.5f;
307 break;
308
309 default:
310 return false;
311 }
312
313 const gdcm::Image& image = pimpl_->GetImage();
314 json["slope"] = image.GetSlope();
315 json["intercept"] = image.GetIntercept();
316 json["rows"] = image.GetRows();
317 json["columns"] = image.GetColumns();
318 json["height"] = image.GetRows();
319 json["width"] = image.GetColumns();
320 json["columnPixelSpacing"] = image.GetSpacing(1);
321 json["rowPixelSpacing"] = image.GetSpacing(0);
322
323 json["windowCenter"] = windowCenter * image.GetSlope() + image.GetIntercept();
324 json["windowWidth"] = windowWidth * image.GetSlope();
325
326 try
327 {
328 std::string width, center;
329 if (GetTag(center, 0x0028, 0x1050 /*DICOM_TAG_WINDOW_CENTER*/) &&
330 GetTag(width, 0x0028, 0x1051 /*DICOM_TAG_WINDOW_WIDTH*/))
331 {
332 float a = boost::lexical_cast<float>(width);
333 float b = boost::lexical_cast<float>(center);
334 json["windowWidth"] = a;
335 json["windowCenter"] = b;
336 }
337 }
338 catch (boost::bad_lexical_cast&)
339 {
340 }
341
342 return true;
343 }
344
345
346 bool ParsedDicomImage::EncodeUsingDeflate(Json::Value& result,
347 uint8_t compressionLevel /* between 0 and 9 */)
348 {
349 using namespace Orthanc;
350
351 ImageAccessor accessor;
352 if (!GetAccessor(accessor))
353 {
354 return false;
355 }
356
357 result = Json::objectValue;
358 result["Orthanc"] = Json::objectValue;
359 if (!GetCornerstoneMetadata(result))
360 {
361 return false;
362 }
363
364 ImageBuffer buffer;
365 buffer.SetMinimalPitchForced(true);
366
367 ImageAccessor converted;
368
369
370 switch (accessor.GetFormat())
371 {
372 case Orthanc::PixelFormat_RGB24:
373 converted = accessor;
374 break;
375
376 case Orthanc::PixelFormat_Grayscale8:
377 case Orthanc::PixelFormat_Grayscale16:
378 buffer.SetFormat(Orthanc::PixelFormat_SignedGrayscale16);
379 buffer.SetWidth(accessor.GetWidth());
380 buffer.SetHeight(accessor.GetHeight());
381 converted = buffer.GetAccessor();
382 ImageProcessing::Convert(converted, accessor);
383 break;
384
385 case Orthanc::PixelFormat_SignedGrayscale16:
386 converted = accessor;
387 break;
388
389 default:
390 // Unsupported pixel format
391 return false;
392 }
393
394 // Sanity check: The pitch must be minimal
395 assert(converted.GetSize() == converted.GetWidth() * converted.GetHeight() *
396 GetBytesPerPixel(converted.GetFormat()));
397 result["Orthanc"]["Compression"] = "Deflate";
398 result["sizeInBytes"] = converted.GetSize();
399
400 std::string z;
401 if (!CompressUsingDeflate(z, converted.GetConstBuffer(), converted.GetSize(), compressionLevel))
402 {
403 return false;
404 }
405
406 result["Orthanc"]["PixelData"] = base64_encode(z);
407
408 return true;
409 }
410
411
412
413 bool ParsedDicomImage::EncodeUsingJpeg(Json::Value& result,
414 uint8_t quality /* between 0 and 100 */)
415 {
416 using namespace Orthanc;
417
418 ImageAccessor accessor;
419 if (!GetAccessor(accessor))
420 {
421 return false;
422 }
423
424 result = Json::objectValue;
425 result["Orthanc"] = Json::objectValue;
426 GetCornerstoneMetadata(result);
427
428 ImageBuffer buffer;
429 buffer.SetMinimalPitchForced(true);
430
431 ImageAccessor converted;
432
433 if (accessor.GetFormat() == Orthanc::PixelFormat_Grayscale8 ||
434 accessor.GetFormat() == Orthanc::PixelFormat_RGB24)
435 {
436 result["Orthanc"]["Stretched"] = false;
437 converted = accessor;
438 }
439 else if (accessor.GetFormat() == Orthanc::PixelFormat_Grayscale16 ||
440 accessor.GetFormat() == Orthanc::PixelFormat_SignedGrayscale16)
441 {
442 result["Orthanc"]["Stretched"] = true;
443 buffer.SetFormat(Orthanc::PixelFormat_Grayscale8);
444 buffer.SetWidth(accessor.GetWidth());
445 buffer.SetHeight(accessor.GetHeight());
446 converted = buffer.GetAccessor();
447
448 int64_t a, b;
449 Orthanc::ImageProcessing::GetMinMaxValue(a, b, accessor);
450 result["Orthanc"]["StretchLow"] = static_cast<int32_t>(a);
451 result["Orthanc"]["StretchHigh"] = static_cast<int32_t>(b);
452
453 if (accessor.GetFormat() == Orthanc::PixelFormat_Grayscale16)
454 {
455 ChangeDynamics<uint8_t, uint16_t>(converted, accessor, a, 0, b, 255);
456 }
457 else
458 {
459 ChangeDynamics<uint8_t, int16_t>(converted, accessor, a, 0, b, 255);
460 }
461 }
462 else
463 {
464 return false;
465 }
466
467 result["Orthanc"]["Compression"] = "Jpeg";
468 result["sizeInBytes"] = converted.GetSize();
469
470 std::string jpeg;
471 OrthancPlugins::JpegWriter writer;
472 writer.SetQuality(quality);
473 writer.WriteToMemory(jpeg, converted);
474 result["Orthanc"]["PixelData"] = base64_encode(jpeg);
475 return true;
476 }
477 };