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