]> Creatis software - gdcm.git/blob - src/gdcmSegmentedPalette.h
a0f1ac2d146d5968f797e0d3f5d70f65191d5984
[gdcm.git] / src / gdcmSegmentedPalette.h
1 /*=========================================================================
2  
3   Program:   gdcm
4   Module:    $RCSfile: gdcmSegmentedPalette.h,v $
5   Language:  C++
6   Date:      $Date: 2007/10/23 14:48:26 $
7   Version:   $Revision: 1.10 $
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 // Ref: 
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 class
53 #else
54 #define GDCM_TYPENAME typename
55 #endif
56
57 namespace GDCM_NAME_SPACE
58 {
59     // abstract class for segment.
60     template <GDCM_TYPENAME EntryType>
61     class Segment {
62     public:
63         typedef std::map<const EntryType*, const Segment*> SegmentMap;
64         virtual bool Expand(const SegmentMap& instances,
65             std::vector<EntryType>& expanded) const = 0;
66         const EntryType* First() const { return _first; }
67         const EntryType* Last() const { return _last; }
68         struct ToMap {
69             std::pair<
70                 typename SegmentMap::key_type,
71                 typename SegmentMap::mapped_type
72             >
73                 operator()(const Segment* segment) const
74             { return std::make_pair(segment->First(), segment); }
75         };
76     protected:
77         Segment(const EntryType* first, const EntryType* last) {
78             _first = first; _last = last;
79         }
80         const EntryType* _first;
81         const EntryType* _last;
82     };
83
84     // discrete segment (opcode = 0)
85     template <GDCM_TYPENAME EntryType>
86     class DiscreteSegment : public Segment<EntryType> {
87     public:
88         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
89         DiscreteSegment(const EntryType* first)
90             : Segment<EntryType>(first, first+2+*(first+1)) {}
91         virtual bool Expand(const SegmentMap&,
92             std::vector<EntryType>& expanded) const
93         {
94             std::copy(this->_first + 2, this->_last, std::back_inserter(expanded));
95             return true;
96         }
97     };
98
99     // linear segment (opcode = 1)
100     template <GDCM_TYPENAME EntryType>
101     class LinearSegment : public Segment<EntryType> {
102     public:
103         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
104         LinearSegment(const EntryType* first)
105             : Segment<EntryType>(first, first+3) {}
106         virtual bool Expand(const SegmentMap&,
107             std::vector<EntryType>& expanded) const
108         {
109             if ( expanded.empty() ) {
110                 // linear segment can't be the first segment.
111                 return false;
112             }
113             EntryType length = *(this->_first + 1);
114             EntryType y0 = expanded.back();
115             EntryType y1 = *(this->_first + 2);
116             double y01 = y1 - y0;
117             for ( EntryType i = 0; i <length; ++i ) {
118                 double value_float
119                     = static_cast<double>(y0)
120                     + (static_cast<double>(i)/static_cast<double>(length)) * y01;
121                 EntryType value_int = static_cast<EntryType>(value_float + 0.5);
122                 expanded.push_back(value_int);
123             }
124             return true;
125         }
126     };
127
128     // indirect segment (opcode = 2)
129     template <GDCM_TYPENAME EntryType>
130     class IndirectSegment : public Segment<EntryType> {
131     public:
132         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
133         IndirectSegment(const EntryType* first)
134             : Segment<EntryType>(first, first+2+4/sizeof(EntryType)) {}
135         virtual bool Expand(const SegmentMap& instances,
136             std::vector<EntryType>& expanded) const
137         {
138             if ( instances.empty() ) {
139                 // some other segments are required as references.
140                 return false;
141             }
142             const EntryType* first_segment = instances.begin()->first;
143             const unsigned short* pOffset
144                 = reinterpret_cast<const unsigned short*>(this->_first + 2);
145             unsigned long offsetBytes
146                 = (*pOffset) | (static_cast<unsigned long>(*(pOffset + 1)) << 16);
147             const EntryType* copied_part_head
148                 = first_segment + offsetBytes / sizeof(EntryType);
149             typename SegmentMap::const_iterator ppHeadSeg = instances.find(copied_part_head);
150             if ( ppHeadSeg == instances.end() ) {
151                 // referred segment not found
152                 return false;
153             }
154             EntryType nNumCopies = *(this->_first + 1);
155             typename SegmentMap::const_iterator ppSeg = ppHeadSeg;
156             while ( std::distance(ppHeadSeg, ppSeg) < nNumCopies ) {
157                 assert( ppSeg != instances.end() );
158                 ppSeg->second->Expand(instances, expanded);
159                 ++ppSeg;
160             }
161             return true;
162         }
163     };
164
165     template <GDCM_TYPENAME EntryType>
166     void ExpandPalette(const EntryType* raw_values, uint32_t length,
167         std::vector<EntryType>& palette)
168     {
169         typedef std::deque<Segment<EntryType>*> SegmentList;
170         SegmentList segments;
171         const EntryType* raw_seg = raw_values;
172         while ( (std::distance(raw_values, raw_seg) * sizeof(EntryType)) <length ) {
173             Segment<EntryType>* segment = NULL;
174             if ( *raw_seg == 0 ) {
175                 segment = new DiscreteSegment<EntryType>(raw_seg);
176             } else if ( *raw_seg == 1 ) {
177                 segment = new LinearSegment<EntryType>(raw_seg);
178             } else if ( *raw_seg == 2 ) {
179                 segment = new IndirectSegment<EntryType>(raw_seg);
180             }
181             if ( segment ) {
182                 segments.push_back(segment);
183                 raw_seg = segment->Last();
184             } else {
185                 // invalid opcode
186                 break;
187             }
188         }
189         typename Segment<EntryType>::SegmentMap instances;
190         std::transform(segments.begin(), segments.end(),
191             std::inserter(instances, instances.end()), typename Segment<EntryType>::ToMap());
192         typename SegmentList::iterator ppSeg = segments.begin();
193         typename SegmentList::iterator endOfSegments = segments.end();
194         for ( ; ppSeg != endOfSegments; ++ppSeg ) {
195             (*ppSeg)->Expand(instances, palette);
196         }
197         ppSeg = segments.begin();
198         for ( ; ppSeg != endOfSegments; ++ppSeg ) {
199             delete *ppSeg;
200         }
201     }
202
203     void ReadPaletteInto(GDCM_NAME_SPACE::File* pds, const GDCM_NAME_SPACE::TagKey& descriptor,
204       const GDCM_NAME_SPACE::TagKey& segment, uint8_t* lut)
205       {
206       unsigned int desc_values[3] = {0,0,0};
207       unsigned long count = 0;
208       //if ( pds->findAndGetUint16Array(descriptor, desc_values, &count).good() )
209       std::string desc_values_str = pds->GetEntryString(descriptor.GetGroup(), descriptor.GetElement() );
210       count = sscanf( desc_values_str.c_str(), "%u\\%u\\%u", desc_values, desc_values+1, desc_values+2 );
211         {
212         assert( count == 3 );
213         unsigned int num_entries = desc_values[0];
214         if ( num_entries == 0 ) {
215           num_entries = 0x10000;
216         }
217         unsigned int min_pixel_value = desc_values[1];
218         assert( min_pixel_value == 0 ); // FIXME
219         unsigned int entry_size = desc_values[2];
220         assert( entry_size == 8 || entry_size == 16 );
221         //DcmElement* pe = NULL;
222         GDCM_NAME_SPACE::DataEntry* pe = NULL;
223
224         pe = pds->GetDataEntry(segment.GetGroup(), segment.GetElement() );
225           {
226           //if ( pds->findAndGetElement(segment, pe).good() )
227           unsigned long length = pe->GetLength();
228           if ( entry_size == 8 )
229             {
230             uint8_t* segment_values = NULL;
231             //if ( pe->getUint8Array(segment_values).good() )
232             segment_values = (uint8_t*)pe->GetBinArea();
233               {
234               std::vector<uint8_t> palette;
235               palette.reserve(num_entries);
236               ExpandPalette(segment_values, length, palette);
237               memcpy(lut, &palette[0], palette.size() );
238               }
239             } 
240           else if ( entry_size == 16 ) 
241             {
242             uint16_t* segment_values = NULL;
243             segment_values = (uint16_t*)pe->GetBinArea();
244               {
245               //if ( pe->getUint16Array(segment_values).good() )
246               std::vector<uint16_t> palette;
247               palette.reserve(num_entries);
248               ExpandPalette(segment_values, length, palette);
249               memcpy(lut, &palette[0], palette.size()*2 );
250
251               }
252             }
253           }
254         }
255       }
256 } // end namespace gdcm
257
258
259 // do not pollute namespace:
260 #undef GDCM_TYPENAME
261
262 #endif