forked from MRtrix3/mrtrix3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.h
552 lines (416 loc) · 20.3 KB
/
image.h
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/*
* Copyright (c) 2008-2018 the MRtrix3 contributors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/
*
* MRtrix3 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.
*
* For more details, see http://www.mrtrix.org/
*/
#ifndef __image_h__
#define __image_h__
#include <functional>
#include <type_traits>
#include <tuple>
#include "debug.h"
#include "header.h"
#include "image_io/fetch_store.h"
#include "image_helpers.h"
#include "formats/mrtrix_utils.h"
#include "algo/copy.h"
#include "algo/threaded_copy.h"
namespace MR
{
constexpr int SpatiallyContiguous = -1;
template <typename ValueType>
class Image :
public ImageBase<Image<ValueType>, ValueType>
{ MEMALIGN (Image<ValueType>)
public:
using value_type = ValueType;
class Buffer;
Image ();
FORCE_INLINE Image (const Image&) = default;
FORCE_INLINE Image (Image&&) = default;
FORCE_INLINE Image& operator= (const Image& image) = default;
FORCE_INLINE Image& operator= (Image&&) = default;
~Image();
//! used internally to instantiate Image objects
Image (const std::shared_ptr<Buffer>&, const Stride::List& = Stride::List());
FORCE_INLINE bool valid () const { return bool(buffer); }
FORCE_INLINE bool operator! () const { return !valid(); }
//! get generic key/value text attributes
FORCE_INLINE const std::map<std::string, std::string>& keyval () const { return buffer->keyval(); }
FORCE_INLINE const std::string& name() const { return buffer->name(); }
FORCE_INLINE const transform_type& transform() const { return buffer->transform(); }
FORCE_INLINE size_t ndim () const { return buffer->ndim(); }
FORCE_INLINE ssize_t size (size_t axis) const { return buffer->size (axis); }
FORCE_INLINE default_type spacing (size_t axis) const { return buffer->spacing (axis); }
FORCE_INLINE ssize_t stride (size_t axis) const { return strides[axis]; }
//! offset to current voxel from start of data
FORCE_INLINE size_t offset () const { return data_offset; }
//! reset index to zero (origin)
FORCE_INLINE void reset () {
for (size_t n = 0; n < ndim(); ++n)
this->index(n) = 0;
}
//! get position of current voxel location along \a axis
FORCE_INLINE ssize_t get_index (size_t axis) const { return x[axis]; }
//! move position of current voxel location along \a axis
FORCE_INLINE void move_index (size_t axis, ssize_t increment) { data_offset += stride (axis) * increment; x[axis] += increment; }
FORCE_INLINE bool is_direct_io () const { return data_pointer; }
//! get voxel value at current location
FORCE_INLINE ValueType get_value () const {
if (data_pointer) return Raw::fetch_native<ValueType> (data_pointer, data_offset);
return buffer->get_value (data_offset);
}
//! set voxel value at current location
FORCE_INLINE void set_value (ValueType val) {
if (data_pointer) Raw::store_native<ValueType> (val, data_pointer, data_offset);
else buffer->set_value (data_offset, val);
}
//! use for debugging
friend std::ostream& operator<< (std::ostream& stream, const Image& V) {
stream << "\"" << V.name() << "\", datatype " << DataType::from<Image::value_type>().specifier() << ", index [ ";
for (size_t n = 0; n < V.ndim(); ++n) stream << V.index(n) << " ";
stream << "], current offset = " << V.offset() << ", ";
if (is_out_of_bounds(V))
stream << "outside FoV";
else
stream << "value = " << V.value();
if (!V.data_pointer) stream << " (using indirect IO)";
else stream << " (using direct IO, data at " << V.data_pointer << ")";
return stream;
}
//! write out the contents of a direct IO image to file
/*!
* returns the name of the image - needed by display() to get the
* name of the temporary file to supply to MRView.
*
* \note this is \e not the recommended way to save an image - only use
* this function when you absolutely need to minimise RAM usage on
* write-out (this avoids any further buffering before write-out).
*
* \note this will only work for images accessed using direct IO (i.e.
* opened as a scratch image, or using with_direct_io(), and only
* supports output to MRtrix format images (*.mif / *.mih). There is a
* chance that images opened in other ways may also use direct IO (e.g.
* if the datatype & strides match, and the image is single-file), you
* can check using the is_direct_io() method. If there is any
* possibility that this image might use indirect IO, you should use
* the save() function instead (and even then, it should only be used
* for debugging purposes). */
std::string dump_to_mrtrix_file (std::string filename, bool use_multi_threading = true) const;
//! return a new Image using direct IO
/*!
* this will preload the data into RAM if the datatype on file doesn't
* match that on file (or if any scaling is applied to the data). The
* optional \a with_strides argument is used to additionally enforce
* preloading if the strides aren't compatible with those specified.
*
* Example:
* \code
* auto image = Header::open (argument[0]).get_image().with_direct_io();
* \endcode
* \note this invalidate the invoking Image - do not use the original
* image in subsequent code.*/
Image with_direct_io (Stride::List with_strides = Stride::List());
//! return a new Image using direct IO
/*!
* this is a convenience function, performing the same function as
* with_direct_io(Stride::List). The difference is that the \a axis
* argument specifies which axis should be contiguous, or if \a axis is
* negative, that the spatial axes should be contiguous (the \c
* SpatiallyContiguous constexpr, set to -1, is provided for clarity).
* In other words:
* \code
* auto image = Image<float>::open (filename).with_direct_io (3);
* \endcode
* is equivalent to:
* \code
* auto header = Header::open (filename);
* auto image = header.get_image<float>().with_direct_io (Stride::contiguous_along_axis (3, header));
* \endcode
* and
* \code
* auto image = Image<float>::open (filename).with_direct_io (-1);
* // or;
* auto image = Image<float>::open (filename).with_direct_io (SpatiallyContiguous);
* \endcode
* is equivalent to:
* \code
* auto header = Header::open (filename);
* auto image = header.get_image<float>().with_direct_io (Stride::contiguous_along_spatial_axes (header));
* \endcode
*/
Image with_direct_io (int axis) {
return with_direct_io ( axis < 0 ?
Stride::contiguous_along_spatial_axes (*buffer) :
Stride::contiguous_along_axis (axis, *buffer) );
}
//! return RAM address of current voxel
/*! \note this will only work if image access is direct (i.e. for a
* scratch image, with preloading, or when the data type is native and
* without scaling. */
ValueType* address () const {
assert (data_pointer != nullptr && "Image::address() can only be used when image access is via direct RAM access");
return data_pointer ? static_cast<ValueType*>(data_pointer) + data_offset : nullptr; }
static Image open (const std::string& image_name, bool read_write_if_existing = false) {
return Header::open (image_name).get_image<ValueType> (read_write_if_existing);
}
static Image create (const std::string& image_name, const Header& template_header) {
return Header::create (image_name, template_header).get_image<ValueType>();
}
static Image scratch (const Header& template_header, const std::string& label = "scratch image") {
return Header::scratch (template_header, label).get_image<ValueType>();
}
//! shared reference to header/buffer
std::shared_ptr<Buffer> buffer;
protected:
//! pointer to data address whether in RAM or MMap
void* data_pointer;
//! voxel indices
vector<ssize_t> x;
//! voxel indices
Stride::List strides;
//! offset to currently pointed-to voxel
size_t data_offset;
};
CHECK_MEM_ALIGN (Image<float>);
template <typename ValueType>
class Image<ValueType>::Buffer : public Header { MEMALIGN (Image<ValueType>::Buffer)
public:
Buffer() {} // TODO: delete this line! Only for testing memory alignment issues.
//! construct a Buffer object to access the data in the image specified
Buffer (Header& H, bool read_write_if_existing = false);
Buffer (Buffer&&) = default;
Buffer& operator= (const Buffer&) = delete;
Buffer& operator= (Buffer&&) = default;
Buffer (const Buffer& b) :
Header (b), fetch_func (b.fetch_func), store_func (b.store_func) { }
FORCE_INLINE ValueType get_value (size_t offset) const {
ssize_t nseg = offset / io->segment_size();
return fetch_func (io->segment (nseg), offset - nseg*io->segment_size(), intensity_offset(), intensity_scale());
}
FORCE_INLINE void set_value (size_t offset, ValueType val) const {
ssize_t nseg = offset / io->segment_size();
store_func (val, io->segment (nseg), offset - nseg*io->segment_size(), intensity_offset(), intensity_scale());
}
std::unique_ptr<uint8_t[]> data_buffer;
void* get_data_pointer ();
FORCE_INLINE ImageIO::Base* get_io () const { return io.get(); }
protected:
std::function<ValueType(const void*,size_t,default_type,default_type)> fetch_func;
std::function<void(ValueType,void*,size_t,default_type,default_type)> store_func;
void set_fetch_store_functions () {
__set_fetch_store_functions (fetch_func, store_func, datatype());
}
};
CHECK_MEM_ALIGN (Image<float>::Buffer);
//! \cond skip
namespace
{
// lightweight struct to copy data into:
template <typename ValueType>
struct TmpImage :
public ImageBase<TmpImage<ValueType>, ValueType>
{ MEMALIGN (TmpImage<ValueType>)
using value_type = ValueType;
TmpImage (const typename Image<ValueType>::Buffer& b, void* const data,
vector<ssize_t> x, const Stride::List& strides, size_t offset) :
b (b), data (data), x (x), strides (strides), offset (offset) { }
const typename Image<ValueType>::Buffer& b;
void* const data;
vector<ssize_t> x;
const Stride::List& strides;
size_t offset;
bool valid () const { return true; }
const std::string name () const { return "direct IO buffer"; }
FORCE_INLINE size_t ndim () const { return b.ndim(); }
FORCE_INLINE ssize_t size (size_t axis) const { return b.size(axis); }
FORCE_INLINE ssize_t stride (size_t axis) const { return strides[axis]; }
FORCE_INLINE ssize_t get_index (size_t axis) const { return x[axis]; }
FORCE_INLINE void move_index (size_t axis, ssize_t increment) { offset += stride (axis) * increment; x[axis] += increment; }
FORCE_INLINE value_type get_value () const { return Raw::fetch_native<ValueType> (data, offset); }
FORCE_INLINE void set_value (ValueType val) { Raw::store_native<ValueType> (val, data, offset); }
};
CHECK_MEM_ALIGN (TmpImage<float>);
}
template <typename ValueType>
Image<ValueType>::Buffer::Buffer (Header& H, bool read_write_if_existing) :
Header (H) {
assert (H.valid() && "IO handler must be set when creating an Image");
assert ((H.is_file_backed() ? is_data_type<ValueType>::value : true) && "class types cannot be stored on file using the Image class");
acquire_io (H);
io->set_readwrite_if_existing (read_write_if_existing);
io->open (*this, footprint<ValueType> (voxel_count (*this)));
if (io->is_file_backed())
set_fetch_store_functions ();
}
template <typename ValueType>
void* Image<ValueType>::Buffer::get_data_pointer ()
{
if (data_buffer) // already allocated via with_direct_io()
return data_buffer.get();
assert (io && "data pointer will only be set for valid Images");
if (!io->is_file_backed()) // this is a scratch image
return io->segment(0);
// check whether we can still do direct IO
// if so, return address where mapped
if (io->nsegments() == 1 && datatype() == DataType::from<ValueType>() && intensity_offset() == 0.0 && intensity_scale() == 1.0)
return io->segment(0);
// can't do direct IO
return nullptr;
}
template <typename ValueType>
Image<ValueType> Header::get_image (bool read_write_if_existing)
{
if (!valid())
throw Exception ("FIXME: don't invoke get_image() with invalid Header!");
std::shared_ptr<typename Image<ValueType>::Buffer> buffer (new typename Image<ValueType>::Buffer (*this, read_write_if_existing));
return { buffer };
}
template <typename ValueType>
FORCE_INLINE Image<ValueType>::Image () :
data_pointer (nullptr),
data_offset (0) { }
template <typename ValueType>
Image<ValueType>::Image (const std::shared_ptr<Image<ValueType>::Buffer>& buffer_p, const Stride::List& desired_strides) :
buffer (buffer_p),
data_pointer (buffer->get_data_pointer()),
x (ndim(), 0),
strides (desired_strides.size() ? desired_strides : Stride::get (*buffer)),
data_offset (Stride::offset (*this))
{
assert (buffer);
assert (data_pointer || buffer->get_io());
DEBUG ("image \"" + name() + "\" initialised with strides = " + str(strides) + ", start = " + str(data_offset)
+ ", using " + ( is_direct_io() ? "" : "in" ) + "direct IO");
}
template <typename ValueType>
Image<ValueType>::~Image ()
{
if (buffer.unique()) {
// was image preloaded and read/write? If so,need to write back:
if (buffer->get_io()) {
if (buffer->get_io()->is_image_readwrite() && buffer->data_buffer) {
auto data_buffer = std::move (buffer->data_buffer);
TmpImage<ValueType> src = { *buffer, data_buffer.get(), vector<ssize_t> (ndim(), 0), strides, Stride::offset (*this) };
Image<ValueType> dest (buffer);
threaded_copy_with_progress_message ("writing back direct IO buffer for \"" + name() + "\"", src, dest);
}
}
}
}
template <typename ValueType>
Image<ValueType> Image<ValueType>::with_direct_io (Stride::List with_strides)
{
if (buffer->data_buffer)
throw Exception ("FIXME: don't invoke 'with_direct_io()' on images already using direct IO!");
if (!buffer->get_io())
throw Exception ("FIXME: don't invoke 'with_direct_io()' on non-validated images!");
if (!buffer.unique())
throw Exception ("FIXME: don't invoke 'with_direct_io()' on images if other copies exist!");
bool preload = ( buffer->datatype() != DataType::from<ValueType>() ) || ( buffer->get_io()->files.size() > 1 );
if (with_strides.size()) {
auto new_strides = Stride::get_actual (Stride::get_nearest_match (*this, with_strides), *this);
preload |= ( new_strides != Stride::get (*this) );
with_strides = new_strides;
}
else
with_strides = Stride::get (*this);
if (!preload)
return std::move (*this);
// do the preload:
// the buffer into which to copy the data:
const auto buffer_size = footprint<ValueType> (voxel_count (*this));
buffer->data_buffer = std::unique_ptr<uint8_t[]> (new uint8_t [buffer_size]);
if (buffer->get_io()->is_image_new()) {
// no need to preload if data is zero anyway:
memset (buffer->data_buffer.get(), 0, buffer_size);
}
else {
auto src (*this);
TmpImage<ValueType> dest = { *buffer, buffer->data_buffer.get(), vector<ssize_t> (ndim(), 0), with_strides, Stride::offset (with_strides, *this) };
threaded_copy_with_progress_message ("preloading data for \"" + name() + "\"", src, dest);
}
return Image (buffer, with_strides);
}
template <typename ValueType>
std::string Image<ValueType>::dump_to_mrtrix_file (std::string filename, bool) const
{
if (!data_pointer || ( !Path::has_suffix (filename, ".mih") && !Path::has_suffix (filename, ".mif") ))
throw Exception ("FIXME: image not suitable for use with 'Image::dump_to_mrtrix_file()'");
// try to dump file to mrtrix format if possible (direct IO)
if (filename == "-")
filename = File::create_tempfile (0, "mif");
DEBUG ("dumping image \"" + name() + "\" to file \"" + filename + "\"...");
File::OFStream out (filename, std::ios::out | std::ios::binary);
out << "mrtrix image\n";
Formats::write_mrtrix_header (*buffer, out);
const bool single_file = Path::has_suffix (filename, ".mif");
std::string data_filename = filename;
int64_t offset = 0;
out << "file: ";
if (single_file) {
offset = out.tellp() + int64_t(18);
offset += ((4 - (offset % 4)) % 4);
out << ". " << offset << "\nEND\n";
}
else {
data_filename = filename.substr (0, filename.size()-4) + ".dat";
out << Path::basename (data_filename) << "\n";
out.close();
out.open (data_filename, std::ios::out | std::ios::binary);
}
const int64_t data_size = footprint (*buffer);
out.seekp (offset, out.beg);
out.write ((const char*) data_pointer, data_size);
if (!out.good())
throw Exception ("error writing back contents of file \"" + data_filename + "\": " + strerror(errno));
out.close();
// If data_size exceeds some threshold, ostream artificially increases the file size beyond that required at close()
// TODO check whether this is still needed...?
File::resize (data_filename, offset + data_size);
return filename;
}
template <class ImageType>
std::string __save_generic (ImageType& x, const std::string& filename, bool use_multi_threading) {
auto out = Image<typename ImageType::value_type>::create (filename, x);
if (use_multi_threading)
threaded_copy (x, out);
else
copy (x, out);
return out.name();
}
//! \endcond
//! save contents of an existing image to file (for debugging only)
template <class ImageType>
typename std::enable_if<is_adapter_type<typename std::remove_reference<ImageType>::type>::value, std::string>::type
save (ImageType&& x, const std::string& filename, bool use_multi_threading = true)
{
return __save_generic (x, filename, use_multi_threading);
}
//! save contents of an existing image to file (for debugging only)
template <class ImageType>
typename std::enable_if<is_pure_image<typename std::remove_reference<ImageType>::type>::value, std::string>::type
save (ImageType&& x, const std::string& filename, bool use_multi_threading = true)
{
try { return x.dump_to_mrtrix_file (filename, use_multi_threading); }
catch (...) { }
return __save_generic (x, filename, use_multi_threading);
}
//! display the contents of an image in MRView (for debugging only)
template <class ImageType>
typename enable_if_image_type<ImageType,void>::type display (ImageType& x) {
std::string filename = save (x, "-");
CONSOLE ("displaying image \"" + filename + "\"");
if (system (("bash -c \"mrview " + filename + "\"").c_str()))
WARN (std::string("error invoking viewer: ") + strerror(errno));
}
}
#endif