]> Creatis software - gdcm.git/blob - Example/exExtractSegmentedPalette.cxx
Fix mistypings
[gdcm.git] / Example / exExtractSegmentedPalette.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: exExtractSegmentedPalette.cxx,v $
5   Language:  C++
6   Date:      $Date: 2007/10/03 08:50:48 $
7   Version:   $Revision: 1.2 $
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 #include <gdcm.h>
20 // Ref: 
21 // http://blog.goo.ne.jp/satomi_takeo/e/3643e5249b2a9650f9e10ef1c830e8b8
22 // I bet the code was compiled on VS6. Make it compile on other platform:
23 // * typedef are not inherited
24 // * need to explicitely add typename keyword
25 // * Uint8 / Uint16 are neither C nor C++
26 // * replace all dcmtk code with identical gdcm code
27
28 #include <assert.h>
29 #include <algorithm>
30 #include <deque>
31 #include <map>
32 #include <vector>
33 #include <iterator>
34
35 namespace {
36     // abstract class for segment.
37     template <typename EntryType>
38     class Segment {
39     public:
40         typedef std::map<const EntryType*, const Segment*> SegmentMap;
41         virtual bool Expand(const SegmentMap& instances,
42             std::vector<EntryType>& expanded) const = 0;
43         const EntryType* First() const { return _first; }
44         const EntryType* Last() const { return _last; }
45         struct ToMap {
46             std::pair<
47                 typename SegmentMap::key_type,
48                 typename SegmentMap::mapped_type
49             >
50                 operator()(const Segment* segment) const
51             { return std::make_pair(segment->First(), segment); }
52         };
53     protected:
54         Segment(const EntryType* first, const EntryType* last) {
55             _first = first; _last = last;
56         }
57         const EntryType* _first;
58         const EntryType* _last;
59     };
60
61     // discrete segment (opcode = 0)
62     template <typename EntryType>
63     class DiscreteSegment : public Segment<EntryType> {
64     public:
65         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
66         DiscreteSegment(const EntryType* first)
67             : Segment<EntryType>(first, first+2+*(first+1)) {}
68         virtual bool Expand(const SegmentMap&,
69             std::vector<EntryType>& expanded) const
70         {
71             std::copy(this->_first + 2, this->_last, std::back_inserter(expanded));
72             return true;
73         }
74     };
75
76     // linear segment (opcode = 1)
77     template <typename EntryType>
78     class LinearSegment : public Segment<EntryType> {
79     public:
80         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
81         LinearSegment(const EntryType* first)
82             : Segment<EntryType>(first, first+3) {}
83         virtual bool Expand(const SegmentMap&,
84             std::vector<EntryType>& expanded) const
85         {
86             if ( expanded.empty() ) {
87                 // linear segment can't be the first segment.
88                 return false;
89             }
90             EntryType length = *(this->_first + 1);
91             EntryType y0 = expanded.back();
92             EntryType y1 = *(this->_first + 2);
93             double y01 = y1 - y0;
94             for ( EntryType i = 0; i <length; ++i ) {
95                 double value_float
96                     = static_cast<double>(y0)
97                     + (static_cast<double>(i)/static_cast<double>(length)) * y01;
98                 EntryType value_int = static_cast<EntryType>(value_float + 0.5);
99                 expanded.push_back(value_int);
100             }
101             return true;
102         }
103     };
104
105     // indirect segment (opcode = 2)
106     template <typename EntryType>
107     class IndirectSegment : public Segment<EntryType> {
108     public:
109         typedef typename Segment<EntryType>::SegmentMap SegmentMap;
110         IndirectSegment(const EntryType* first)
111             : Segment<EntryType>(first, first+2+4/sizeof(EntryType)) {}
112         virtual bool Expand(const SegmentMap& instances,
113             std::vector<EntryType>& expanded) const
114         {
115             if ( instances.empty() ) {
116                 // some other segments are required as references.
117                 return false;
118             }
119             const EntryType* first_segment = instances.begin()->first;
120             const unsigned short* pOffset
121                 = reinterpret_cast<const unsigned short*>(this->_first + 2);
122             unsigned long offsetBytes
123                 = (*pOffset) | (static_cast<unsigned long>(*(pOffset + 1)) << 16);
124             const EntryType* copied_part_head
125                 = first_segment + offsetBytes / sizeof(EntryType);
126             typename SegmentMap::const_iterator ppHeadSeg = instances.find(copied_part_head);
127             if ( ppHeadSeg == instances.end() ) {
128                 // referred segment not found
129                 return false;
130             }
131             EntryType nNumCopies = *(this->_first + 1);
132             typename SegmentMap::const_iterator ppSeg = ppHeadSeg;
133             while ( std::distance(ppHeadSeg, ppSeg) <nNumCopies ) {
134                 assert( ppSeg != instances.end() );
135                 ppSeg->second->Expand(instances, expanded);
136                 ++ppSeg;
137             }
138             return true;
139         }
140     };
141
142     template <typename EntryType>
143     void ExpandPalette(const EntryType* raw_values, uint32_t length,
144         std::vector<EntryType>& palette)
145     {
146         typedef std::deque<Segment<EntryType>*> SegmentList;
147         SegmentList segments;
148         const EntryType* raw_seg = raw_values;
149         while ( (std::distance(raw_values, raw_seg) * sizeof(EntryType)) <length ) {
150             Segment<EntryType>* segment = NULL;
151             if ( *raw_seg == 0 ) {
152                 segment = new DiscreteSegment<EntryType>(raw_seg);
153             } else if ( *raw_seg == 1 ) {
154                 segment = new LinearSegment<EntryType>(raw_seg);
155             } else if ( *raw_seg == 2 ) {
156                 segment = new IndirectSegment<EntryType>(raw_seg);
157             }
158             if ( segment ) {
159                 segments.push_back(segment);
160                 raw_seg = segment->Last();
161             } else {
162                 // invalid opcode
163                 break;
164             }
165         }
166         typename Segment<EntryType>::SegmentMap instances;
167         std::transform(segments.begin(), segments.end(),
168             std::inserter(instances, instances.end()), typename Segment<EntryType>::ToMap());
169         typename SegmentList::iterator ppSeg = segments.begin();
170         typename SegmentList::iterator endOfSegments = segments.end();
171         for ( ; ppSeg != endOfSegments; ++ppSeg ) {
172             (*ppSeg)->Expand(instances, palette);
173         }
174         ppSeg = segments.begin();
175         for ( ; ppSeg != endOfSegments; ++ppSeg ) {
176             delete *ppSeg;
177         }
178     }
179
180     void ReadPalette(GDCM_NAME_SPACE::File* pds, const GDCM_NAME_SPACE::TagKey& descriptor,
181       const GDCM_NAME_SPACE::TagKey& segment)
182       {
183       int desc_values[3] = {};
184       unsigned long count = 0;
185       //if ( pds->findAndGetUint16Array(descriptor, desc_values, &count).good() )
186       std::string desc_values_str = pds->GetEntryString(descriptor.GetGroup(), descriptor.GetElement() );
187       count = sscanf( desc_values_str.c_str(), "%d\\%d\\%d", desc_values, desc_values+1, desc_values+2 );
188         {
189         assert( count == 3 );
190         unsigned int num_entries = desc_values[0];
191         if ( num_entries == 0 ) {
192           num_entries = 0x10000;
193         }
194         int min_pixel_value = desc_values[1];
195         unsigned int entry_size = desc_values[2];
196         assert( entry_size == 8 || entry_size == 16 );
197         //DcmElement* pe = NULL;
198         GDCM_NAME_SPACE::DataEntry* pe = NULL;
199
200         pe = pds->GetDataEntry(segment.GetGroup(), segment.GetElement() ); {
201           //if ( pds->findAndGetElement(segment, pe).good() )
202           unsigned long length = pe->GetLength();
203           if ( entry_size == 8 ) {
204             uint8_t* segment_values = NULL;
205             //if ( pe->getUint8Array(segment_values).good() )
206             segment_values = (uint8_t*)pe->GetBinArea(); {
207               std::vector<uint8_t> palette;
208               palette.reserve(num_entries);
209               ExpandPalette(segment_values, length, palette);
210             }
211           } else if ( entry_size == 16 ) {
212             uint16_t* segment_values = NULL;
213             segment_values = (uint16_t*)pe->GetBinArea(); {
214               //if ( pe->getUint16Array(segment_values).good() )
215               std::vector<uint16_t> palette;
216               palette.reserve(num_entries);
217               ExpandPalette(segment_values, length, palette);
218               std::copy(palette.begin(), palette.end(), 
219                 std::ostream_iterator<uint16_t>(std::cout, "\n"));
220
221             }
222           }
223         }
224         }
225       }
226 } // end namespace
227
228 int main(int argc, char* argv[])
229 {
230 //    if ( argc < 2 ) {
231 //        return 1;
232 //    }
233 //    DcmFileFormat ff;
234 //    OFString filename(argv[1]);
235 //    if ( ff.loadFile(filename.c_str()).good() ) {
236 //        DcmDataset* pDataset = ff.getDataset();
237 //        assert( pDataset );
238 //        OFString pi;
239 //        if ( pDataset->findAndGetOFString(DCM_PhotometricInterpretation, pi).good()
240 //            && pi == OFString("PALETTE COLOR") ) {
241 //            ReadPalette(pDataset, DCM_RedPaletteColorLookupTableDescriptor,
242 //                DCM_SegmentedRedPaletteColorLookupTableData);
243 //            ReadPalette(pDataset, DCM_GreenPaletteColorLookupTableDescriptor,
244 //                DCM_SegmentedGreenPaletteColorLookupTableData);
245 //            ReadPalette(pDataset, DCM_BluePaletteColorLookupTableDescriptor,
246 //                DCM_SegmentedBluePaletteColorLookupTableData);
247 //        }
248 //    }
249
250   GDCM_NAME_SPACE::File *f = GDCM_NAME_SPACE::File::New();
251   f->SetFileName( argv[1] );
252   bool res = f->Load();
253   f->Print( std::cout );
254   GDCM_NAME_SPACE::TagKey DCM_RedPaletteColorLookupTableDescriptor (0x0028, 0x1101);
255   GDCM_NAME_SPACE::TagKey DCM_GreenPaletteColorLookupTableDescriptor (0x0028, 0x1102);
256   GDCM_NAME_SPACE::TagKey DCM_BluePaletteColorLookupTableDescriptor (0x0028, 0x1103);
257
258   GDCM_NAME_SPACE::TagKey DCM_SegmentedRedPaletteColorLookupTableData (0x0028, 0x1221);
259   GDCM_NAME_SPACE::TagKey DCM_SegmentedGreenPaletteColorLookupTableData (0x0028, 0x1222);
260   GDCM_NAME_SPACE::TagKey DCM_SegmentedBluePaletteColorLookupTableData (0x0028, 0x1223);
261
262
263   // TODO need to check file is indeed PALETTE COLOR:
264   ReadPalette(f, DCM_RedPaletteColorLookupTableDescriptor,
265     DCM_SegmentedRedPaletteColorLookupTableData);
266   ReadPalette(f, DCM_GreenPaletteColorLookupTableDescriptor,
267     DCM_SegmentedGreenPaletteColorLookupTableData);
268   ReadPalette(f, DCM_BluePaletteColorLookupTableDescriptor,
269     DCM_SegmentedBluePaletteColorLookupTableData);
270
271     return 0;
272 }
273