v2.0.0
Loading...
Searching...
No Matches
mri_mgh_io.cpp
Go to the documentation of this file.
1//=============================================================================================================
25
26//=============================================================================================================
27// INCLUDES
28//=============================================================================================================
29
30#include "mri_mgh_io.h"
31
34#include <fiff/fiff_constants.h>
35#include <fiff/fiff_file.h>
36
37//=============================================================================================================
38// QT INCLUDES
39//=============================================================================================================
40
41#include <QFile>
42#include <QFileInfo>
43#include <QDataStream>
44#include <QDebug>
45#include <QDebug>
46
47#include <zlib.h>
48
49//=============================================================================================================
50// EIGEN INCLUDES
51//=============================================================================================================
52
53#include <Eigen/Core>
54
55//=============================================================================================================
56// USED NAMESPACES
57//=============================================================================================================
58
59using namespace MRILIB;
60using namespace FIFFLIB;
61using namespace Eigen;
62
63//=============================================================================================================
64// DEFINE MEMBER METHODS
65//=============================================================================================================
66
67bool MriMghIO::read(const QString& mgzFile,
68 MriVolData& volData,
69 QVector<FiffCoordTrans>& additionalTrans,
70 const QString& subjectMriDir,
71 bool verbose)
72{
73 volData.fileName = mgzFile;
74
75 // Step 1: Get raw (decompressed) bytes
76 bool isCompressed = mgzFile.endsWith(".mgz", Qt::CaseInsensitive);
77 QByteArray fileData;
78
79 if (isCompressed) {
80 if (!decompress(mgzFile, fileData)) {
81 return false;
82 }
83 } else {
84 QFile file(mgzFile);
85 if (!file.open(QIODevice::ReadOnly)) {
86 qCritical() << "MriMghIO::read - Could not open" << mgzFile;
87 return false;
88 }
89 fileData = file.readAll();
90 file.close();
91 }
92
93 if (fileData.size() < MRI_MGH_DATA_OFFSET) {
94 qCritical() << "MriMghIO::read - File" << mgzFile
95 << "is too small to be a valid MGH file ("
96 << fileData.size() << "bytes)";
97 return false;
98 }
99
100 // Step 2: Parse header
101 if (!parseHeader(fileData, volData, verbose)) {
102 return false;
103 }
104
105 // Step 3: Build the voxel -> surface RAS transform
106 Matrix4f vox2ras = volData.computeVox2Ras();
108 FIFFV_COORD_MRI_SLICE, FIFFV_COORD_MRI, vox2ras, true);
109
110 if (verbose) {
111 qInfo("Voxel -> FsSurface RAS transform:\n");
112 for (int r = 0; r < 4; ++r) {
113 qInfo(" %10.6f %10.6f %10.6f %10.6f\n",
114 vox2ras(r, 0), vox2ras(r, 1), vox2ras(r, 2), vox2ras(r, 3));
115 }
116 }
117
118 // Surface RAS -> scanner RAS: a shift by the volume centre (MNE-C mne_mri_add_transforms).
119 additionalTrans.append(FiffCoordTrans(FIFFV_COORD_MRI, FIFFV_MNE_COORD_RAS, Matrix3f::Identity(), Vector3f(volData.c_ras / 1000.0f)));
120
121 // Step 4: Read voxel data
122 if (!readVoxelData(fileData, volData)) {
123 return false;
124 }
125
126 // Step 5: Parse footer (optional)
127 parseFooter(fileData, volData, additionalTrans, subjectMriDir, verbose);
128
129 if (verbose) {
130 qInfo("Read %d slices from %s (%dx%d pixels)\n",
131 static_cast<int>(volData.slices.size()), qPrintable(mgzFile),
132 volData.width, volData.height);
133 }
134
135 return true;
136}
137
138//=============================================================================================================
139
140bool MriMghIO::decompress(const QString& mgzFile, QByteArray& rawData)
141{
142 QFile file(mgzFile);
143 if (!file.open(QIODevice::ReadOnly)) {
144 qCritical() << "MriMghIO::decompress - Could not open" << mgzFile;
145 return false;
146 }
147 QByteArray compressedData = file.readAll();
148 file.close();
149
150 if (compressedData.isEmpty()) {
151 qCritical() << "MriMghIO::decompress - File is empty:" << mgzFile;
152 return false;
153 }
154
155 // Use zlib to decompress gzip data in memory
156 z_stream strm = {};
157
158 // MAX_WBITS + 16 tells zlib to detect and handle gzip headers
159 int ret = inflateInit2(&strm, MAX_WBITS + 16);
160 if (ret != Z_OK) {
161 qCritical() << "MriMghIO::decompress - inflateInit2 failed";
162 return false;
163 }
164
165 strm.next_in = reinterpret_cast<Bytef*>(compressedData.data());
166 strm.avail_in = static_cast<uInt>(compressedData.size());
167
168 const int chunkSize = 256 * 1024; // 256 KB chunks
169 rawData.clear();
170
171 do {
172 rawData.resize(rawData.size() + chunkSize);
173 strm.next_out = reinterpret_cast<Bytef*>(rawData.data() + rawData.size() - chunkSize);
174 strm.avail_out = chunkSize;
175
176 ret = inflate(&strm, Z_NO_FLUSH);
177 if (ret == Z_STREAM_ERROR || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR) {
178 qCritical() << "MriMghIO::decompress - inflate failed for" << mgzFile
179 << "- zlib error:" << ret;
180 inflateEnd(&strm);
181 return false;
182 }
183 } while (ret != Z_STREAM_END);
184
185 // Trim to actual decompressed size
186 rawData.resize(rawData.size() - static_cast<int>(strm.avail_out));
187 inflateEnd(&strm);
188
189 return true;
190}
191
192//=============================================================================================================
193
194bool MriMghIO::parseHeader(const QByteArray& data, MriVolData& volData, bool verbose)
195{
196 //
197 // MGH header layout (all big-endian):
198 // Bytes 0-3: version (int32)
199 // Bytes 4-7: width (int32)
200 // Bytes 8-11: height (int32)
201 // Bytes 12-15: depth (int32)
202 // Bytes 16-19: nframes (int32)
203 // Bytes 20-23: type (int32)
204 // Bytes 24-27: dof (int32)
205 // Bytes 28-29: goodRASflag (int16)
206 // Bytes 30-41: spacingX/Y/Z (3×float32) — only if goodRASflag > 0
207 // Bytes 42-77: Mdc (9×float32) — direction cosines, only if goodRASflag > 0
208 // Bytes 78-89: c_ras (3×float32) — center RAS, only if goodRASflag > 0
209 // Bytes 90-283: unused (padding)
210 //
211
212 QDataStream stream(data);
213 stream.setByteOrder(QDataStream::BigEndian);
214 stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
215
216 qint32 version, width, height, depth, nframes, type, dof;
217 stream >> version >> width >> height >> depth >> nframes >> type >> dof;
218
219 if (version != MRI_MGH_VERSION) {
220 qCritical() << "MriMghIO::parseHeader - Unknown MGH version:" << version;
221 return false;
222 }
223
224 volData.version = version;
225 volData.width = width;
226 volData.height = height;
227 volData.depth = depth;
228 volData.nframes = nframes;
229 volData.type = type;
230 volData.dof = dof;
231
232 if (verbose) {
233 qInfo("MGH file: %dx%dx%d, %d frame(s), type=%d\n",
234 width, height, depth, nframes, type);
235 }
236
237 // goodRASflag (2 bytes short)
238 qint16 goodRASflag;
239 stream >> goodRASflag;
240 volData.rasGood = (goodRASflag > 0);
241
242 if (goodRASflag > 0) {
243 // Voxel sizes
244 stream >> volData.xsize >> volData.ysize >> volData.zsize;
245
246 // Direction cosines (Mdc matrix):
247 // xr, xa, xs (x-direction cosines)
248 // yr, ya, ys (y-direction cosines)
249 // zr, za, zs (z-direction cosines)
250 stream >> volData.x_ras[0] >> volData.x_ras[1] >> volData.x_ras[2];
251 stream >> volData.y_ras[0] >> volData.y_ras[1] >> volData.y_ras[2];
252 stream >> volData.z_ras[0] >> volData.z_ras[1] >> volData.z_ras[2];
253
254 // Center RAS
255 stream >> volData.c_ras[0] >> volData.c_ras[1] >> volData.c_ras[2];
256 }
257 // Else: default values from MriVolData constructor are used
258
259 if (verbose) {
260 qInfo("Voxel sizes: %.4f x %.4f x %.4f mm\n",
261 volData.xsize, volData.ysize, volData.zsize);
262 qInfo("goodRAS: %d\n", goodRASflag);
263 qInfo("c_ras: %.4f %.4f %.4f\n",
264 volData.c_ras[0], volData.c_ras[1], volData.c_ras[2]);
265 }
266
267 return true;
268}
269
270//=============================================================================================================
271
272bool MriMghIO::readVoxelData(const QByteArray& data, MriVolData& volData)
273{
274 //
275 // Read voxel data starting at byte 284 (MRI_MGH_DATA_OFFSET).
276 // Data layout in MGH: [width][height][depth][frames] in Fortran order (x fastest).
277 // Only the first frame is read.
278 //
279
280 int bpv = bytesPerVoxel(volData.type);
281 if (bpv == 0) {
282 qCritical() << "MriMghIO::readVoxelData - Unsupported MGH data type:" << volData.type;
283 return false;
284 }
285
286 qint64 frameSize = static_cast<qint64>(volData.width) * volData.height * volData.depth * bpv;
287 if (data.size() < MRI_MGH_DATA_OFFSET + frameSize) {
288 qCritical() << "MriMghIO::readVoxelData - File too small for expected data size";
289 return false;
290 }
291
292 QDataStream stream(data);
293 stream.setByteOrder(QDataStream::BigEndian);
294 stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
295 stream.device()->seek(MRI_MGH_DATA_OFFSET);
296
297 int nslice = volData.depth;
298 int nPixels = volData.width * volData.height;
299 volData.slices.resize(nslice);
300
301 // Build the vox2ras transform for per-slice transforms
302 Matrix4f vox2ras = volData.computeVox2Ras();
303
304 for (int k = 0; k < nslice; ++k) {
305 MriSlice& slice = volData.slices[k];
306 slice.width = volData.width;
307 slice.height = volData.height;
308 slice.dimx = volData.xsize / 1000.0f; // mm -> meters
309 slice.dimy = volData.ysize / 1000.0f;
310
311 // Read pixel data for this slice
312 switch (volData.type) {
313 case MRI_UCHAR: {
315 slice.pixels.resize(nPixels);
316 for (int p = 0; p < nPixels; ++p) {
317 quint8 val;
318 stream >> val;
319 slice.pixels[p] = val;
320 }
321 slice.scale = 1.0f;
322 break;
323 }
324 case MRI_SHORT: {
326 slice.pixelsWord.resize(nPixels);
327 for (int p = 0; p < nPixels; ++p) {
328 qint16 val;
329 stream >> val;
330 slice.pixelsWord[p] = static_cast<unsigned short>(val < 0 ? 0 : val);
331 }
332 slice.scale = 1.0f;
333 break;
334 }
335 case MRI_INT: {
336 // Convert INT to FLOAT
338 slice.pixelsFloat.resize(nPixels);
339 for (int p = 0; p < nPixels; ++p) {
340 qint32 val;
341 stream >> val;
342 slice.pixelsFloat[p] = static_cast<float>(val);
343 }
344 slice.scale = 1.0f;
345 break;
346 }
347 case MRI_FLOAT: {
349 slice.pixelsFloat.resize(nPixels);
350 for (int p = 0; p < nPixels; ++p) {
351 float val;
352 stream >> val;
353 slice.pixelsFloat[p] = val;
354 }
355 slice.scale = 1.0f;
356 break;
357 }
358 }
359
360 //
361 // Build per-slice coordinate transform (slice -> MRI surface RAS).
362 // For each slice k:
363 // sliceOrigin = vox2ras * [0, 0, k, 1]^T
364 // sliceRot = vox2ras rotation columns (x, y, z pixel axes)
365 //
366 Vector3f sliceOrigin;
367 sliceOrigin(0) = vox2ras(0, 2) * k + vox2ras(0, 3);
368 sliceOrigin(1) = vox2ras(1, 2) * k + vox2ras(1, 3);
369 sliceOrigin(2) = vox2ras(2, 2) * k + vox2ras(2, 3);
370
371 Matrix3f sliceRot;
372 sliceRot.col(0) = vox2ras.block<3, 1>(0, 0); // x-pixel direction
373 sliceRot.col(1) = vox2ras.block<3, 1>(0, 1); // y-pixel direction
374 sliceRot.col(2) = vox2ras.block<3, 1>(0, 2); // z (normal) direction
375
376 Vector3f sliceMove;
377 sliceMove << sliceOrigin(0), sliceOrigin(1), sliceOrigin(2);
378
379 slice.trans = FiffCoordTrans(FIFFV_COORD_MRI_SLICE, FIFFV_COORD_MRI, sliceRot, sliceMove);
380 }
381
382 return true;
383}
384
385//=============================================================================================================
386
387bool MriMghIO::parseFooter(const QByteArray& data,
388 MriVolData& volData,
389 QVector<FiffCoordTrans>& additionalTrans,
390 const QString& subjectMriDir,
391 bool verbose)
392{
393 //
394 // The footer starts after the voxel data.
395 // It contains (in order):
396 // 1. Scan parameters: TR(f32), flipAngle(f32), TE(f32), TI(f32), FoV(f32)
397 // 2. Tags: tagType(i32) + tagLen(i32 or i64) + tagData
398 //
399
400 int bpv = bytesPerVoxel(volData.type);
401 if (bpv == 0) {
402 bpv = 1; // Fallback for footer calculation
403 }
404
405 qint64 frameSize = static_cast<qint64>(volData.width) * volData.height * volData.depth * bpv;
406 qint64 footerPos = MRI_MGH_DATA_OFFSET + frameSize;
407
408 if (data.size() <= footerPos) {
409 // No footer — that's fine
410 return true;
411 }
412
413 QDataStream stream(data);
414 stream.setByteOrder(QDataStream::BigEndian);
415 stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
416 stream.device()->seek(footerPos);
417
418 // Read scan parameters (5 × float32 = 20 bytes)
419 constexpr int kScanParamBytes = 5 * sizeof(float);
420 qint64 remainingBytes = data.size() - footerPos;
421 if (remainingBytes >= kScanParamBytes) {
422 stream >> volData.TR >> volData.flipAngle >> volData.TE >> volData.TI >> volData.FoV;
423 } else {
424 return true;
425 }
426
427 // Parse tags
428 while (!stream.atEnd()) {
429 qint32 tagType;
430 stream >> tagType;
431 if (stream.atEnd())
432 break;
433
434 qint64 tagLen;
435 // For TAG_OLD_SURF_GEOM (20) and TAG_OLD_MGH_XFORM (30), length is 4 bytes
436 // For newer tags, length is 8 bytes
437 if (tagType == MGH_TAG_OLD_SURF_GEOM || tagType == MGH_TAG_OLD_MGH_XFORM) {
438 qint32 len32;
439 stream >> len32;
440 tagLen = len32;
441 } else {
442 qint64 len64;
443 stream >> len64;
444 tagLen = len64;
445 }
446
447 if (tagLen <= 0 || tagLen > data.size())
448 break;
449
450 QByteArray tagData(tagLen, '\0');
451 if (stream.readRawData(tagData.data(), tagLen) != tagLen)
452 break;
453
454 if (tagType == MGH_TAG_MGH_XFORM) {
455 // TAG_MGH_XFORM: contains path to talairach.xfm
456 QString xfmPath = QString::fromLatin1(tagData).trimmed();
457 volData.talairachXfmPath = xfmPath;
458
459 if (verbose) {
460 qInfo("Found Talairach transform reference: %s\n", qPrintable(xfmPath));
461 }
462
463 // Resolve relative paths using subject MRI directory
464 if (!QFileInfo(xfmPath).isAbsolute() && !subjectMriDir.isEmpty()) {
465 xfmPath = subjectMriDir + "/transforms/" + xfmPath;
466 }
467
468 FiffCoordTransSet talairach;
469 if (talairach.addTalairach(xfmPath)) {
470 additionalTrans.append(talairach.RAS_MNI_tal_t);
471 additionalTrans.append(talairach.MNI_tal_tal_gtz_t);
472 additionalTrans.append(talairach.MNI_tal_tal_ltz_t);
473 if (verbose) {
474 qInfo("Read Talairach transform from %s\n", qPrintable(xfmPath));
475 }
476 } else if (verbose) {
477 qWarning("Talairach transform not readable: %s\n", qPrintable(xfmPath));
478 }
479 }
480 }
481
482 return true;
483}
484
485//=============================================================================================================
486
487int MriMghIO::bytesPerVoxel(int type)
488{
489 switch (type) {
490 case MRI_UCHAR:
491 return 1;
492 case MRI_SHORT:
493 return 2;
494 case MRI_INT:
495 return 4;
496 case MRI_FLOAT:
497 return 4;
498 default:
499 return 0;
500 }
501}
Symbolic FIFF tag, block, value, unit and channel-type constants shared across FIFFLIB.
#define FIFFV_COORD_MRI_SLICE
#define FIFFV_COORD_MRI
#define FIFFV_MNE_COORD_RAS
The MNE-C transform chain from MEG head coordinates to MNI and FreeSurfer Talairach coordinates.
4x4 affine FIFF coordinate transform (FIFF_COORD_TRANS) annotated with source/destination coordinate-...
FIFF tag-kind, block-kind and type-code numerical definitions, authoritative for FIFFLIB.
#define FIFFV_MRI_PIXEL_BYTE
Definition fiff_file.h:695
#define FIFFV_MRI_PIXEL_FLOAT
Definition fiff_file.h:698
#define FIFFV_MRI_PIXEL_WORD
Definition fiff_file.h:696
return FiffCoordTrans(from_frame, to_frame, R, moveVec)
FreeSurfer MGH / MGZ volume reader: byte-level decoder for the 284-byte fixed header,...
FIFF file I/O, in-memory data structures and high-level readers/writers.
Volume I/O, voxel geometry and slice resampling for structural MRI data inside mne-cpp.
constexpr int MRI_MGH_VERSION
Definition mri_types.h:51
constexpr int MGH_TAG_OLD_MGH_XFORM
Definition mri_types.h:119
constexpr int MRI_MGH_DATA_OFFSET
Definition mri_types.h:101
constexpr int MGH_TAG_OLD_SURF_GEOM
Definition mri_types.h:118
constexpr int MGH_TAG_MGH_XFORM
Definition mri_types.h:120
constexpr int MRI_SHORT
Definition mri_types.h:73
constexpr int MRI_UCHAR
Definition mri_types.h:69
constexpr int MRI_INT
Definition mri_types.h:70
constexpr int MRI_FLOAT
Definition mri_types.h:72
bool addTalairach(const QString &xfmPath)
static bool read(const QString &mgzFile, MriVolData &volData, QVector< FIFFLIB::FiffCoordTrans > &additionalTrans, const QString &subjectMriDir=QString(), bool verbose=false)
QVector< unsigned char > pixels
FIFFLIB::FiffCoordTrans trans
QVector< unsigned short > pixelsWord
QVector< float > pixelsFloat
Format-agnostic 3D MRI volume: header geometry, voxel buffer (as a vector of MriSlice),...
FIFFLIB::FiffCoordTrans voxelSurfRasT
Eigen::Vector3f y_ras
Eigen::Vector3f x_ras
QVector< MriSlice > slices
Eigen::Matrix4f computeVox2Ras() const
Eigen::Vector3f z_ras
Eigen::Vector3f c_ras