]> Creatis software - gdcm.git/blob - src/gdcmSegmentedPalette.h
FIX: Make it compiler on st***d Sun compiler
[gdcm.git] / src / gdcmSegmentedPalette.h
1 /*=========================================================================
2  
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSegmentedPalette.h,v $
5   Language:  C++
6   Date:      $Date: 2007/10/26 09:00:31 $
7   Version:   $Revision: 1.13 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18
19 #ifndef _GDCMSEGMENTEDPALETTE_H_
20 #define _GDCMSEGMENTEDPALETTE_H_
21
22 #include "gdcmFile.h"
23 #include "gdcmTagKey.h"
24 #include "gdcmDataEntry.h"
25
26 // Notepad from Satomi Takeo:
27 // http://blog.goo.ne.jp/satomi_takeo/e/3643e5249b2a9650f9e10ef1c830e8b8
28 // I bet the code was compiled on VS6. Make it compile on other platform:
29 // * typedef are not inherited
30 // * need to explicitely add typename keyword
31 // * Uint8 / Uint16 are neither C nor C++
32 // * replace all dcmtk code with equivalent gdcm code
33 // * Add extra parameter to ReadPaletteInto to save extracted info
34
35 // MM: Over 50000 DICOM files I only found two that had a Segmented Palette LUT
36 // And both were coming from a ALOKA SSD-4000 station
37 //
38 // JPRx :
39 // It compiles fine under gcc 4.1.2 and msvc 7
40 // It doesn't compile on msvc 6, borland and SunOS
41 // Any fix welcome !
42
43 #include <assert.h>
44 #include <algorithm>
45 #include <deque>
46 #include <map>
47 #include <vector>
48 #include <iterator>
49
50 // Hack for VS6
51 #if defined(_MSC_VER) && (_MSC_VER < 1310)
52 #define GDCM_TYPENAME
53 #else
54 #define GDCM_TYPENAME typename
55 #endif
56
57 namespace GDCM_NAME_SPACE
58 {
59 // Long stody short: Sun compiler only provide the second interface of std::distance, since the implemenation
60 // is so trivial, I'd rather redo it myself.
61 // Ref:
62 // http://www.sgi.com/tech/stl/distance.html#2
63 // The second version of distance was the one defined in the original STL, and the first version is the one defined in the draft C++ standard; the definition was changed because the older interface was clumsy and error-prone. The older interface required the use of a temporary variable, and it has semantics that are somewhat nonintuitive: it increments n by the distance from first to last, rather than storing that distance in n
64   template<typename InputIterator>
65     inline int32_t
66     mydistance(InputIterator first, InputIterator last)
67       {
68       int32_t n = 0;
69       while (first != last)
70         {
71         ++first;
72         ++n;
73         }
74       return n;
75       }
76
77     // abstract class for segment.
78     template <typename EntryType>
79     class Segment {
80     public:
81         typedef std::map<const EntryType*, const Segment*> SegmentMap;
82         virtual bool Expand(const SegmentMap& instances,
83             std::vector<EntryType>& expanded) const = 0;
84         const EntryType* First() const { return _first; }
85         const EntryType* Last() const { return _last; }
86         struct ToMap {
87             typename SegmentMap::value_type
88                 operator()(const Segment* segment) const
89             { return std::make_pair(segment->First(), segment); }
90         };
91     protected:
92         Segment(const EntryType* first, const EntryType* last) {
93             _first = first; _last = last;
94         }
95         const EntryType* _first;
96         const EntryType* _last;
97     };
98
99     // discrete segment (opcode = 0)
100     template <typename EntryType>
101     class DiscreteSegment : public Segment<EntryType> {
102     public:
103         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
104         DiscreteSegment(const EntryType* first)
105             : Segment<EntryType>(first, first+2+*(first+1)) {}
106         virtual bool Expand(const SegmentMap&,
107             std::vector<EntryType>& expanded) const
108         {
109             std::copy(this->_first + 2, this->_last, std::back_inserter(expanded));
110             return true;
111         }
112     };
113
114     // linear segment (opcode = 1)
115     template <typename EntryType>
116     class LinearSegment : public Segment<EntryType> {
117     public:
118         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
119         LinearSegment(const EntryType* first)
120             : Segment<EntryType>(first, first+3) {}
121         virtual bool Expand(const SegmentMap&,
122             std::vector<EntryType>& expanded) const
123         {
124             if ( expanded.empty() ) {
125                 // linear segment can't be the first segment.
126                 return false;
127             }
128             EntryType length = *(this->_first + 1);
129             EntryType y0 = expanded.back();
130             EntryType y1 = *(this->_first + 2);
131             double y01 = y1 - y0;
132             for ( EntryType i = 0; i <length; ++i ) {
133                 double value_float
134                     = static_cast<double>(y0)
135                     + (static_cast<double>(i)/static_cast<double>(length)) * y01;
136                 EntryType value_int = static_cast<EntryType>(value_float + 0.5);
137                 expanded.push_back(value_int);
138             }
139             return true;
140         }
141     };
142
143     // indirect segment (opcode = 2)
144     template <typename EntryType>
145     class IndirectSegment : public Segment<EntryType> {
146     public:
147         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
148         IndirectSegment(const EntryType* first)
149             : Segment<EntryType>(first, first+2+4/sizeof(EntryType)) {}
150         virtual bool Expand(const SegmentMap& instances,
151             std::vector<EntryType>& expanded) const
152         {
153             if ( instances.empty() ) {
154                 // some other segments are required as references.
155                 return false;
156             }
157             const EntryType* first_segment = instances.begin()->first;
158             const unsigned short* pOffset
159                 = reinterpret_cast<const unsigned short*>(this->_first + 2);
160             unsigned long offsetBytes
161                 = (*pOffset) | (static_cast<unsigned long>(*(pOffset + 1)) << 16);
162             const EntryType* copied_part_head
163                 = first_segment + offsetBytes / sizeof(EntryType);
164             GDCM_TYPENAME SegmentMap::const_iterator ppHeadSeg = instances.find(copied_part_head);
165             if ( ppHeadSeg == instances.end() ) {
166                 // referred segment not found
167                 return false;
168             }
169             EntryType nNumCopies = *(this->_first + 1);
170             GDCM_TYPENAME SegmentMap::const_iterator ppSeg = ppHeadSeg;
171             while ( mydistance(ppHeadSeg, ppSeg) < nNumCopies ) {
172                 // assert( mydistance(ppHeadSeg, ppSeg) == std::distance(ppHeadSeg, ppSeg) );
173                 assert( ppSeg != instances.end() );
174                 ppSeg->second->Expand(instances, expanded);
175                 ++ppSeg;
176             }
177             return true;
178         }
179     };
180
181     template <typename EntryType>
182     void ExpandPalette(const EntryType* raw_values, uint32_t length,
183         std::vector<EntryType>& palette)
184     {
185         typedef std::deque<Segment<EntryType>*> SegmentList;
186         SegmentList segments;
187         const EntryType* raw_seg = raw_values;
188         while ( (mydistance(raw_values, raw_seg) * sizeof(EntryType)) < length ) {
189             // assert( mydistance(raw_values, raw_seg) == std::distance(raw_values, raw_seg) );
190             Segment<EntryType>* segment = NULL;
191             if ( *raw_seg == 0 ) {
192                 segment = new DiscreteSegment<EntryType>(raw_seg);
193             } else if ( *raw_seg == 1 ) {
194                 segment = new LinearSegment<EntryType>(raw_seg);
195             } else if ( *raw_seg == 2 ) {
196                 segment = new IndirectSegment<EntryType>(raw_seg);
197             }
198             if ( segment ) {
199                 segments.push_back(segment);
200                 raw_seg = segment->Last();
201             } else {
202                 // invalid opcode
203                 break;
204             }
205
206         }
207         GDCM_TYPENAME Segment<EntryType>::SegmentMap instances;
208         std::transform(segments.begin(), segments.end(),
209             std::inserter(instances, instances.end()), GDCM_TYPENAME Segment<EntryType>::ToMap());
210         GDCM_TYPENAME SegmentList::iterator ppSeg = segments.begin();
211         GDCM_TYPENAME SegmentList::iterator endOfSegments = segments.end();
212         for ( ; ppSeg != endOfSegments; ++ppSeg ) {
213             (*ppSeg)->Expand(instances, palette);
214         }
215         ppSeg = segments.begin();
216         for ( ; ppSeg != endOfSegments; ++ppSeg ) {
217             delete *ppSeg;
218         }
219     }
220
221     void ReadPaletteInto(GDCM_NAME_SPACE::File* pds, const GDCM_NAME_SPACE::TagKey& descriptor,
222       const GDCM_NAME_SPACE::TagKey& segment, uint8_t* lut)
223       {
224       unsigned int desc_values[3] = {0,0,0};
225       unsigned long count = 0;
226       //if ( pds->findAndGetUint16Array(descriptor, desc_values, &count).good() )
227       std::string desc_values_str = pds->GetEntryString(descriptor.GetGroup(), descriptor.GetElement() );
228       count = sscanf( desc_values_str.c_str(), "%u\\%u\\%u", desc_values, desc_values+1, desc_values+2 );
229         {
230         assert( count == 3 );
231         unsigned int num_entries = desc_values[0];
232         if ( num_entries == 0 ) {
233           num_entries = 0x10000;
234         }
235         unsigned int min_pixel_value = desc_values[1];
236         assert( min_pixel_value == 0 ); // FIXME
237         unsigned int entry_size = desc_values[2];
238         assert( entry_size == 8 || entry_size == 16 );
239         //DcmElement* pe = NULL;
240         GDCM_NAME_SPACE::DataEntry* pe = NULL;
241
242         pe = pds->GetDataEntry(segment.GetGroup(), segment.GetElement() );
243           {
244           //if ( pds->findAndGetElement(segment, pe).good() )
245           unsigned long length = pe->GetLength();
246           if ( entry_size == 8 )
247             {
248             uint8_t* segment_values = NULL;
249             //if ( pe->getUint8Array(segment_values).good() )
250             segment_values = (uint8_t*)pe->GetBinArea();
251               {
252               std::vector<uint8_t> palette;
253               palette.reserve(num_entries);
254               ExpandPalette(segment_values, length, palette);
255               memcpy(lut, &palette[0], palette.size() );
256               }
257             } 
258           else if ( entry_size == 16 ) 
259             {
260             uint16_t* segment_values = NULL;
261             segment_values = (uint16_t*)pe->GetBinArea();
262               {
263               //if ( pe->getUint16Array(segment_values).good() )
264               std::vector<uint16_t> palette;
265               palette.reserve(num_entries);
266               ExpandPalette(segment_values, length, palette);
267               memcpy(lut, &palette[0], palette.size()*2 );
268
269               }
270             }
271           }
272         }
273       }
274 } // end namespace gdcm
275
276
277 // do not pollute namespace:
278 #undef GDCM_TYPENAME
279
280 #endif