vtkimagereader.cpp 12.5 KB
Newer Older
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
// ================================================================================================
// 
// This file is part of the CAMPVis Software Framework.
// 
// If not explicitly stated otherwise: Copyright (C) 2012, all rights reserved,
//      Christian Schulte zu Berge <christian.szb@in.tum.de>
//      Chair for Computer Aided Medical Procedures
//      Technische Universitt Mnchen
//      Boltzmannstr. 3, 85748 Garching b. Mnchen, Germany
// For a full list of authors and contributors, please refer to the file "AUTHORS.txt".
// 
// The licensing of this softare is not yet resolved. Until then, redistribution in source or
// binary forms outside the CAMP chair is not permitted, unless explicitly stated in legal form.
// However, the names of the original authors and the above copyright notice must retain in its
// original state in any case.
// 
// Legal disclaimer provided by the BSD license:
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// 
// ================================================================================================

#include "vtkimagereader.h"

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

#include "tgt/filesystem.h"
#include "core/datastructures/imagedata.h"
#include "core/datastructures/imagerepresentationdisk.h"
40
#include "core/datastructures/indexedmeshgeometry.h"
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "core/datastructures/genericimagerepresentationlocal.h"
#include "core/tools/stringutils.h"

/*
 * Full format specification at http://www.vtk.org/VTK/img/file-formats.pdf
 */

namespace campvis {
    const std::string VtkImageReader::loggerCat_ = "CAMPVis.modules.io.VtkImageReader";

    VtkImageReader::VtkImageReader() 
        : AbstractProcessor()
        , p_url("url", "Image URL", "")
        , p_targetImageID("targetImageName", "Target Image ID", "VtkImageReader.output", DataNameProperty::WRITE)
55
56
        , p_imageOffset("ImageOffset", "Image Offset in mm", tgt::vec3(0.f), tgt::vec3(-10000.f), tgt::vec3(10000.f), tgt::vec3(0.1f))
        , p_voxelSize("VoxelSize", "Voxel Size in mm", tgt::vec3(1.f), tgt::vec3(-100.f), tgt::vec3(100.f), tgt::vec3(0.1f))
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    {
        addProperty(&p_url);
        addProperty(&p_targetImageID);
        addProperty(&p_imageOffset);
        addProperty(&p_voxelSize);
    }

    VtkImageReader::~VtkImageReader() {

    }

    std::string getTrimmedLine(std::ifstream& file, char delim = '\n') {
        std::string toReturn;
        std::getline(file, toReturn, delim);
        return StringUtils::trim(toReturn);
    }

    void VtkImageReader::process(DataContainer& data) {
        try {
schultezub's avatar
schultezub committed
76
            std::ifstream file(p_url.getValue().c_str(), std::ifstream::in);
77
78
79
80
81
82
83
84
85
86
87
88
            if (!file.is_open() || file.bad())
                throw tgt::FileException("Could not open file " + p_url.getValue() + " for reading.", p_url.getValue());

            std::string curLine = getTrimmedLine(file);
            if (curLine.find("# vtk DataFile Version") != 0)
                throw tgt::FileException("Unknown identifier in vtk file.", p_url.getValue());

            // next line is the header - contains only unimportant data
            curLine = getTrimmedLine(file);

            // this line is the format
            curLine = StringUtils::lowercase(getTrimmedLine(file));
89
90
91
            if (curLine == "binary")
                throw tgt::FileException("Binary data format currently unsupported.", p_url.getValue());
            else if (curLine != "ascii")
92
93
94
95
96
                throw tgt::FileException("Unsupported format in vtk file - expected binary or ascii.", p_url.getValue());

            // now comes the dataset structure
            curLine = StringUtils::lowercase(getTrimmedLine(file));
            std::vector<std::string> splitted = StringUtils::split(curLine, " ");
97
98
99
100
101
102
103
104
105
106
            if (splitted.size() == 2 && splitted[0] == "dataset") {
                if (splitted[1] == "structured_points")
                    parseStructuredPoints(data, file);
                else if (splitted[1] == "polydata")
                    parsePolydata(data, file);
                else 
                    throw tgt::FileException("Unsupported dataset structure in vtk file - expected \"DATASET STRUCTURED_POINTS\" or \"DATASET POLYDATA\".", p_url.getValue());
            }
            else {
                throw tgt::FileException("Unexpected tokens in vtk file.", p_url.getValue());
107
108
            }

109
110
111
112
113
114
115
116
117
        }
        catch (tgt::Exception& e) {
            LERROR("Error while parsing VTK file: " << e.what());
            return;
        }
        catch (std::exception& e) {
            LERROR("Error while parsing VTK file: " << e.what());
            return;
        }
118

119
120
        validate(INVALID_RESULT);
    }
121

122
123
124
125
126
    void VtkImageReader::parseStructuredPoints(DataContainer& data, std::ifstream& file) throw (tgt::Exception, std::exception) {
        // init optional parameters with sane default values
        std::string url;
        size_t dimensionality = 3;
        tgt::svec3 size(static_cast<size_t>(0));
127

128
129
        tgt::vec3 voxelSize(1.f);
        tgt::vec3 imageOffset(0.f);
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
        std::string curLine;
        std::vector<std::string> splitted;

        // now comes dimensions, spacing and origin:
        for (size_t i = 0; i < 3; ++i) {
            std::stringstream ss(StringUtils::lowercase(getTrimmedLine(file)));
            ss >> curLine;
            if (curLine == "dimensions") {
                ss >> size.x >> size.y >> size.z;
                if (size.z == 1)
                    dimensionality = 2;
                if (size.y == 1)
                    dimensionality = 1;
            }
            else if (curLine == "spacing") {
                ss >> voxelSize.x >> voxelSize.y >> voxelSize.z;
            }
            else if (curLine == "origin") {
                ss >> imageOffset.x >> imageOffset.y >> imageOffset.z;
            }
            else {
                throw tgt::FileException("Unsupported dataset structure field '" + curLine + "' in vtk file.", p_url.getValue());
            }
        }

        // now come the dataset attributes "POINT_DATA ..."
        curLine = StringUtils::lowercase(getTrimmedLine(file));
        splitted = StringUtils::split(curLine, " ");
        if (splitted.size() != 2 || splitted[0] != "point_data")
            throw tgt::FileException("Unsupported dataset attribute '" + splitted[0] + "' in vtk file - expected \"POINT_DATA n\".", p_url.getValue());
        size_t numPoints = StringUtils::fromString<size_t>(splitted[1]);
162

163
164
        if (numPoints < tgt::hmul(size))
            throw tgt::FileException("Number of points in dataset (" + splitted[0] + ") doesn't match dimensions: " + StringUtils::toString(size), p_url.getValue());
165

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        // now comes the data description block "FIELD ..."
        curLine = StringUtils::lowercase(getTrimmedLine(file));
        splitted = StringUtils::split(curLine, " ");
        if (splitted.size() != 3 || splitted[0] != "field")
            throw tgt::FileException("Unsupported dataset attribute '" + splitted[0] + "' in vtk file - expected \"FIELD ...\".", p_url.getValue());
        size_t numArrays = StringUtils::fromString<size_t>(splitted[2]);

        if (numArrays != 1)
            throw tgt::FileException("Multiple arrays in data set currently not supported - too lazy...", p_url.getValue());

        curLine = StringUtils::lowercase(getTrimmedLine(file));
        splitted = StringUtils::split(curLine, " ");
        size_t numTuples = StringUtils::fromString<size_t>(splitted[1]);
        size_t numComponents = StringUtils::fromString<size_t>(splitted[2]);

        if (numTuples * numComponents != numPoints)
            throw tgt::FileException("Number of points in dataset doesn't match dimensions of data field", p_url.getValue());

        ImageData* image = new ImageData(dimensionality, size, 1);
        ImageRepresentationLocal* rep = 0;
186
187
188
189

#define DISPATCH_PARSING(VTK_TYPE, C_TYPE, TMP_TYPE) \
    do { \
        if (splitted[3] == VTK_TYPE) { \
190
            C_TYPE* dataArray = new C_TYPE[numPoints]; \
191
192
193
            TMP_TYPE tmp; \
            for (size_t i = 0; i < numPoints && file.good(); ++i) { \
                file >> tmp; \
194
                dataArray[i] = static_cast<C_TYPE>(tmp); \
195
            } \
196
            rep = GenericImageRepresentationLocal<C_TYPE, 1>::create(image, dataArray); \
197
198
199
        } \
    } while (0)

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
        DISPATCH_PARSING("unsigned_char"    , uint8_t, uint16_t);
        DISPATCH_PARSING("char"             , int8_t, int16_t);
        DISPATCH_PARSING("unsigned_short"   , uint16_t, uint16_t);
        DISPATCH_PARSING("short"            , int16_t, int16_t);
        DISPATCH_PARSING("unsigned_int"     , uint32_t, uint32_t);
        DISPATCH_PARSING("int"              , int32_t, int32_t);
        DISPATCH_PARSING("float"            , float, float);

        if (rep != 0) {
            // all parsing done - lets create the image:
            image->setMappingInformation(ImageMappingInformation(size, imageOffset + p_imageOffset.getValue(), voxelSize + p_voxelSize.getValue()));
            data.addData(p_targetImageID.getValue(), image);
            p_targetImageID.issueWrite();
        }
        else {
            throw tgt::FileException("Error while parsing the data.", p_url.getValue());
        }
    }

    void VtkImageReader::parsePolydata(DataContainer& data, std::ifstream& file) throw (tgt::Exception, std::exception) {
        std::string curLine;
        std::vector<std::string> splitted;

        std::vector<uint16_t> indices;
        std::vector<tgt::vec3> vertices;
        std::vector<tgt::vec3> normals;

        while (file.good()) {
            curLine = StringUtils::lowercase(getTrimmedLine(file));
            splitted = StringUtils::split(curLine, " ");

            if (splitted.size() == 3 && splitted[0] == "points") {
                size_t numVertices = StringUtils::fromString<size_t>(splitted[1]);
                vertices.resize(numVertices, tgt::vec3(0.f));

                // TODO: make parsing more robust...
                for (size_t i = 0; i < numVertices; ++i) {
                    file >> vertices[i].x >> vertices[i].y >> vertices[i].z;
238
                }
239
240
241
242
243
244
245
246
247
248
249
250
251
            }
            else if (splitted.size() == 3 && splitted[0] == "polygons") {
                size_t numPolygons = StringUtils::fromString<size_t>(splitted[1]);
                size_t numIndices = StringUtils::fromString<size_t>(splitted[2]);
                indices.resize(numIndices, 0);
                size_t i = 0;

                // TODO: make parsing more robust...
                for (size_t j = 0; j < numPolygons && i < numIndices; ++j) {
                    int tmp;
                    file >> tmp >> indices[i++];
                    file >> indices[i++];
                    file >> indices[i++];
252
253
                }
            }
254
255
256
257
258
259
260
261
262
263
264
265
266
267
            if (splitted.size() == 2 && splitted[0] == "point_data") {
                size_t numPoints = StringUtils::fromString<size_t>(splitted[1]);

                curLine = StringUtils::lowercase(getTrimmedLine(file));
                splitted = StringUtils::split(curLine, " ");

                if (splitted.size() == 3 && splitted[0] == "normals") {
                    normals.resize(numPoints, tgt::vec3(0.f));

                    // TODO: make parsing more robust...
                    for (size_t i = 0; i < numPoints; ++i) {
                        file >> normals[i].x >> normals[i].y >> normals[i].z;
                    }
                }
268
269
270
            }
        }

271
272
273
274
        // all parsing done - lets create the image:
        IndexedMeshGeometry* g = new IndexedMeshGeometry(indices, vertices, std::vector<tgt::vec3>(), std::vector<tgt::vec4>(), normals);
        data.addData(p_targetImageID.getValue(), g);
        p_targetImageID.issueWrite();
275
    }
276

277
}