File: DicomDir.cpp

package info (click to toggle)
sight 21.1.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 36,592 kB
  • sloc: cpp: 228,341; xml: 19,066; ansic: 9,854; python: 302; sh: 135; makefile: 32
file content (342 lines) | stat: -rw-r--r-- 11,380 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/************************************************************************
 *
 * Copyright (C) 2009-2022 IRCAD France
 * Copyright (C) 2012-2020 IHU Strasbourg
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "io/dicom/helper/DicomDir.hpp"

#include "io/dicom/helper/DicomDataReader.hxx"

#include <core/exceptionmacros.hpp>
#include <core/jobs/IJob.hpp>
#include <core/jobs/Observer.hpp>
#include <core/log/Logger.hpp>
#include <core/spyLog.hpp>

#include <data/DicomSeries.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

#include <gdcmMediaStorage.h>
#include <gdcmReader.h>

#include <filesystem>

namespace sight::io::dicom
{

namespace helper
{

// ----------------------------------------------------------------------------

std::filesystem::path DicomDir::findDicomDir(const std::filesystem::path& root)
{
    std::filesystem::path current = root;

    while(std::filesystem::exists(current) && current != current.root_path())
    {
        std::filesystem::path dicomDirPath = current / "dicomdir";
        if(std::filesystem::exists(dicomDirPath) && !std::filesystem::is_directory(dicomDirPath))
        {
            return dicomDirPath;
        }

        dicomDirPath = current / "DICOMDIR";
        if(std::filesystem::exists(dicomDirPath) && !std::filesystem::is_directory(dicomDirPath))
        {
            return dicomDirPath;
        }

        current = current.parent_path();
    }

    return std::filesystem::path();
}

// ----------------------------------------------------------------------------

void processDirInformation(
    const std::filesystem::path& dicomdir,
    const std::filesystem::path& rootDicomDirPath,
    data::DicomSeries::sptr currentSeries,
    std::map<std::string, data::DicomSeries::sptr>& dicomSeriesMap,
    const core::log::Logger::sptr& logger,
    std::function<void(std::uint64_t)>& progress,
    std::function<bool()>& cancel,
    double& p,
    double& ptotal
)
{
    SIGHT_ASSERT(
        "You must specify a valid dicomdir.",
        std::filesystem::exists(dicomdir)
        && !std::filesystem::is_directory(dicomdir)
    );

    // Try to read the file
    gdcm::Reader reader;
    reader.SetFileName(dicomdir.string().c_str());
    if(!reader.Read())
    {
        return;
    }

    const gdcm::File& gdcmFile   = reader.GetFile();
    const gdcm::DataSet& dataset = gdcmFile.GetDataSet();

    // Check if the file is a DICOMDIR
    gdcm::MediaStorage mediaStorage;
    mediaStorage.SetFromFile(gdcmFile);
    if(mediaStorage != gdcm::MediaStorage::MediaStorageDirectoryStorage)
    {
        SIGHT_ERROR("This file is not a DICOMDIR");
        return;
    }

    // Check the MediaStorageSOPClass
    const gdcm::FileMetaInformation& fileMetaInformation = gdcmFile.GetHeader();
    const std::string& mediaStorageSOP                   =
        io::dicom::helper::DicomDataReader::getTagValue<0x0002, 0x0002>(fileMetaInformation);

    if(mediaStorageSOP != gdcm::MediaStorage::GetMSString(gdcm::MediaStorage::MediaStorageDirectoryStorage))
    {
        SIGHT_ERROR("This file is not a DICOMDIR");
        return;
    }

    // For each root elements
    typedef std::set<gdcm::DataElement> DataElementSet;
    typedef DataElementSet::const_iterator ConstIterator;

    for(ConstIterator it = dataset.GetDES().begin() ; it != dataset.GetDES().end() ; ++it)
    {
        // Directory Record Sequence
        if(it->GetTag() == gdcm::Tag(0x0004, 0x1220))
        {
            gdcm::SmartPointer<gdcm::SequenceOfItems> sequence = it->GetValueAsSQ();
            ptotal += static_cast<double>(sequence->GetNumberOfItems());

            for(unsigned int index = 1 ; index <= sequence->GetNumberOfItems() ; ++index)
            {
                // Retrieve item
                gdcm::Item& item = sequence->GetItem(index);

                // Directory Record Type
                const std::string recordType =
                    io::dicom::helper::DicomDataReader::getTagValue<0x0004, 0x1430>(item.GetNestedDataSet());

                // Check Referenced File ID
                std::string refFileID =
                    io::dicom::helper::DicomDataReader::getTagValue<0x0004, 0x1500>(item.GetNestedDataSet());

                if(recordType == "IMAGE")
                {
                    // Read file path
                    std::string file = io::dicom::helper::DicomDataReader::getTagValue<0x0004, 0x1500>(
                        item.GetNestedDataSet()
                    );
                    std::replace(file.begin(), file.end(), '\\', '/');
                    SIGHT_WARN_IF("Dicom instance doesn't have a referenced file id.", file.empty());

                    const std::filesystem::path path = rootDicomDirPath / file;
                    SIGHT_WARN_IF("Unable to find path :" << path, !std::filesystem::exists(path));
                    SIGHT_WARN_IF("Dicomdir is badly formatted. Skipping path :" << path, !currentSeries);

                    if(!currentSeries || file.empty())
                    {
                        logger->warning("DICOMDIR file is badly formatted. Instances may be missing");
                    }
                    else if(std::filesystem::exists(path))
                    {
                        auto instanceNumber = boost::lexical_cast<unsigned int>(
                            io::dicom::helper::DicomDataReader::getTagValue<0x0020,
                                                                            0x0013>(item.GetNestedDataSet())
                        );
                        currentSeries->addDicomPath(instanceNumber, path);
                    }
                    else
                    {
                        logger->warning("Unable to retrieve file :" + path.string());
                    }
                }
                else
                {
                    // If the record is a series, we select the current series
                    if(recordType == "SERIES")
                    {
                        const std::string& seriesUID =
                            io::dicom::helper::DicomDataReader::getTagValue<0x0020, 0x000e>(item.GetNestedDataSet());
                        if(dicomSeriesMap.find(seriesUID) == dicomSeriesMap.end())
                        {
                            data::DicomSeries::sptr series = data::DicomSeries::New();
                            series->setInstanceUID(seriesUID);
                            dicomSeriesMap[seriesUID] = series;
                        }

                        currentSeries = dicomSeriesMap[seriesUID];
                    }

                    std::replace(refFileID.begin(), refFileID.end(), '\\', '/');
                    auto refFilePath = dicomdir.parent_path() / refFileID;
                    if(refFileID != "" && std::filesystem::exists(refFilePath))
                    {
                        processDirInformation(
                            refFilePath,
                            rootDicomDirPath,
                            currentSeries,
                            dicomSeriesMap,
                            logger,
                            progress,
                            cancel,
                            p,
                            ptotal
                        );
                    }
                }

                if(progress)
                {
                    progress(++p);
                }

                if(cancel && cancel())
                {
                    break;
                }
            }
        }
    }
}

// ----------------------------------------------------------------------------

void DicomDir::retrieveDicomSeries(
    const std::filesystem::path& dicomdir,
    std::vector<SPTR(data::DicomSeries)>& seriesDB,
    const core::log::Logger::sptr& logger,
    std::function<void(std::uint64_t)> progress,
    std::function<bool()> cancel
)
{
    SIGHT_ASSERT(
        "You must specify a valid dicomdir.",
        std::filesystem::exists(dicomdir)
        && !std::filesystem::is_directory(dicomdir)
    );

    // Try to read the file
    gdcm::Reader reader;
    reader.SetFileName(dicomdir.string().c_str());
    if(!reader.Read())
    {
        return;
    }

    const gdcm::File& gdcmFile   = reader.GetFile();
    const gdcm::DataSet& dataset = gdcmFile.GetDataSet();

    // Check if the file is a DICOMDIR
    gdcm::MediaStorage mediaStorage;
    mediaStorage.SetFromFile(gdcmFile);
    if(mediaStorage != gdcm::MediaStorage::MediaStorageDirectoryStorage)
    {
        SIGHT_ERROR("This file is not a DICOMDIR");
        return;
    }

    // Check the MediaStorageSOPClass
    const gdcm::FileMetaInformation& fileMetaInformation = gdcmFile.GetHeader();
    const std::string& mediaStorageSOP                   =
        io::dicom::helper::DicomDataReader::getTagValue<0x0002, 0x0002>(fileMetaInformation);

    if(mediaStorageSOP != gdcm::MediaStorage::GetMSString(gdcm::MediaStorage::MediaStorageDirectoryStorage))
    {
        SIGHT_ERROR("This file is not a DICOMDIR");
        return;
    }

    // For each root elements
    typedef std::set<gdcm::DataElement> DataElementSet;
    typedef DataElementSet::const_iterator ConstIterator;

    double p      = 0.;
    double ptotal = 0.;

    if(progress)
    {
        // Compute total progress
        for(ConstIterator it = dataset.GetDES().begin() ; it != dataset.GetDES().end() ; ++it)
        {
            // Directory Record Sequence
            if(it->GetTag() == gdcm::Tag(0x0004, 0x1220))
            {
                gdcm::SmartPointer<gdcm::SequenceOfItems> sequence = it->GetValueAsSQ();

                ptotal += static_cast<double>(sequence->GetNumberOfItems());
            }
        }
    }

    if(0. == ptotal)
    {
        ptotal = 1.;
    }

    std::map<std::string, data::DicomSeries::sptr> dicomSeriesMap;
    processDirInformation(
        dicomdir,
        dicomdir.parent_path(),
        nullptr,
        dicomSeriesMap,
        logger,
        progress,
        cancel,
        p,
        ptotal
    );

    if(cancel && cancel())
    {
        return;
    }

    for(auto entry : dicomSeriesMap)
    {
        auto series            = entry.second;
        const std::size_t size = series->getDicomContainer().size();
        if(size)
        {
            series->setNumberOfInstances(size);
            seriesDB.push_back(series);
        }
        else
        {
            logger->critical("Unable to retrieve instances for this series : " + series->getInstanceUID());
        }
    }
}

// ----------------------------------------------------------------------------

} //helper

} //fwGdcmIO