slideforge 0.1.1

Fast whole-slide image (WSI) tile extraction in Rust, with tissue detection, stain normalization, and TFRecord output.
Documentation
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
//! SVS metadata parser.
//!
//! This module contains utility functions for reading WSI
//! metadata from Aperio SVS files.
//!
//! SVS files can have multiple Image File Directories (IFDs) of various types:
//!
//! - PyramidLevel
//! - Thumbnail
//! - Label
//! - etc
//!
//! During parsing, only pyramid levels are converted into [`Level`] instances.
//!
//! Aperio-specific metadata such as objective magnification and microns per
//! pixel (MPP) is extracted from the `ImageDescription` TIFF tag when present.

use std::fs::File;
use std::io::BufReader;
use std::path::Path;

use tiff::decoder::Decoder;
use tiff::tags::Tag;

use crate::tile::TileDirectory;
use crate::{Dimensions, Level, Metadata, TileSize, error::WsiError};

/// Represents the different possible types of IFDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ImageKind {
    PyramidLevel,
    Thumbnail,
    Label,
    Macro,
}

// Represents a parsed level from a SVS/TIFF IFD.
#[derive(Debug)]
struct ParsedIfd {
    description: String,
    tile_size: Option<TileSize>,
    kind: ImageKind,
}

/// The result of parsing an SVS file: its metadata, and each pyramid
/// level's [`TileDirectory`] (in level order, so index `i` corresponds to
/// `metadata.level(i)`). Used by [`Slide::open`](crate::slide::Slide::open)
/// to build a [`Slide`](crate::slide::Slide).
pub struct ParsedSlide {
    pub metadata: Metadata,
    pub tile_directories: Vec<TileDirectory>,
}

// Contains additional metadata attributes derived from Aperio images.
#[derive(Debug, Default)]
struct AperioMetadata {
    objective_power: Option<f32>,
    microns_per_pixel: Option<f64>,
}

/// Classifies the image kind of a IFD from its description.
///
/// # Classification Rules
///
/// - Descriptions containing `"label"` are classified as [`ImageKind::Label`].
/// - Descriptions containing `"macro"` are classified as [`ImageKind::Macro`].
/// - Tiled images are assumed to be pyramid levels.
/// - Remaining images are treated as thumbnails.
///
/// # Arguments
/// * `description` - Description of the IFD as contained in the [`Tag::ImageDescription`] tag.
/// * `tile_size` - Optional tile size object.
///
/// # Returns
/// An [`ImageKind`] instance representing the IFDs type.
fn classify_ifd(description: &str, tile_size: Option<&TileSize>) -> ImageKind {
    let description = description.to_ascii_lowercase();

    if description.contains("label") {
        return ImageKind::Label;
    }

    if description.contains("macro") {
        return ImageKind::Macro;
    }

    if tile_size.is_some() {
        return ImageKind::PyramidLevel;
    }

    ImageKind::Thumbnail
}

/// Extracts metadata from the decoder's current IFD.
///
/// This function does not advance the decoder and only inspects the
/// currently selected image directory.
///
/// /// The resulting [`ParsedIfd`] can be used to determine whether the IFD
/// represents a pyramid level or an auxiliary image.
///
/// # Arguments
/// * `decoder` - The [`Decoder`] instance with the current IFD loaded.
///
/// # Returns
/// The resulting [`ParsedIfd`]
///
/// # Errors
/// Returns an [`WsiError`] if parsing the IFD fails.
fn parse_ifd(decoder: &mut Decoder<BufReader<File>>) -> Result<ParsedIfd, WsiError> {
    let description = decoder.get_tag_ascii_string(Tag::ImageDescription)?;

    let tile_size = match (
        decoder.get_tag_u32(Tag::TileWidth),
        decoder.get_tag_u32(Tag::TileLength),
    ) {
        (Ok(width), Ok(height)) => Some(TileSize::new(width, height)),
        _ => None,
    };

    let kind = classify_ifd(&description, tile_size.as_ref());

    Ok(ParsedIfd {
        description,
        tile_size,
        kind,
    })
}

/// Parses Aperio-specific metadata from an image description string.
///
/// Aperio scanners store slide metadata as key-value pairs inside the TIFF
/// `ImageDescription` tag.
///
/// Currently the following fields are extracted:
///
/// - `AppMag` (objective magnification)
/// - `MPP` (microns per pixel)
///
/// # Arguments
/// * `description` - Description of the IFD as contained in the [`Tag::ImageDescription`] tag.
///
/// # Returns
/// An [`AperioMetadata`] instance containing the extracted metadata.
fn parse_aperio_metadata(description: &str) -> AperioMetadata {
    let mut metadata = AperioMetadata::default();

    for field in description.split('|') {
        let field = field.trim();

        if let Some(value) = field.strip_prefix("AppMag = ") {
            metadata.objective_power = value.parse::<f32>().ok();
        }

        if let Some(value) = field.strip_prefix("MPP = ") {
            metadata.microns_per_pixel = value.parse::<f64>().ok();
        }
    }

    metadata
}

/// Constructs a [`Level`] from the decoder's current pyramid-level IFD.
///
/// The decoder must already be positioned at a tiled image representing
/// a valid pyramid level.
///
/// # Arguments
///
/// * `decoder` - Decoder positioned at a pyramid-level IFD.
/// * `level_idx` - Zero-based pyramid level index.
/// * `base_width` - Width of the highest-resolution level.
/// * `tile_size` - Tile dimensions associated with the current level.
///
/// # Returns
///
/// A populated [`Level`] instance.
///
/// # Errors
///
/// Returns [`WsiError`] if image dimensions cannot be read from the
/// current IFD.
fn read_level(
    decoder: &mut Decoder<BufReader<File>>,
    level_idx: u32,
    base_width: u32,
    tile_size: TileSize,
) -> Result<Level, WsiError> {
    let (width, height) = decoder.dimensions()?;

    let dimensions = Dimensions::new(width, height);

    let downsample_factor = base_width as f64 / width as f64;

    Ok(Level::new(
        level_idx,
        dimensions,
        tile_size,
        downsample_factor,
    ))
}

/// Opens an SVS file and initializes a TIFF decoder.
///
/// # Arguments
///
/// * `path` - Path to the SVS file.
///
/// # Returns
///
/// A TIFF decoder positioned at the first IFD.
///
/// # Errors
///
/// Returns [`WsiError`] if the file cannot be opened or the TIFF decoder
/// cannot be initialized.
pub fn get_decoder(path: &Path) -> Result<Decoder<BufReader<File>>, WsiError> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    Ok(Decoder::new(reader)?)
}

/// Reads metadata from an Aperio SVS file.
///
/// The parser traverses all IFDs contained in the file and extracts:
///
/// - Pyramid levels
/// - Objective magnification (`AppMag`)
/// - Microns per pixel (`MPP`)
///
/// Auxiliary images such as thumbnails, labels, and macro images are
/// ignored.
///
/// # Arguments
///
/// * `path` - Path to the SVS file.
///
/// # Returns
///
/// A [`Metadata`] instance describing the slide pyramid and available
/// slide metadata.
///
/// # Errors
///
/// Returns [`WsiError`] if the file cannot be opened or required TIFF
/// metadata cannot be read.
pub fn read_metadata(path: &Path) -> Result<Metadata, WsiError> {
    let mut decoder = get_decoder(path)?;

    let base_dimensions = Dimensions::from_tuple(decoder.dimensions()?);

    let mut levels = Vec::new();

    let mut objective_power = None;
    let mut microns_per_pixel = None;

    loop {
        let parsed_ifd = parse_ifd(&mut decoder)?;

        // Parse Aperio metadata from the first useful
        // description we encounter.
        if objective_power.is_none() || microns_per_pixel.is_none() {
            let aperio = parse_aperio_metadata(&parsed_ifd.description);

            objective_power = objective_power.or(aperio.objective_power);

            microns_per_pixel = microns_per_pixel.or(aperio.microns_per_pixel);
        }

        if parsed_ifd.kind == ImageKind::PyramidLevel {
            let tile_size = parsed_ifd
                .tile_size
                .expect("Pyramid levels must have tile metadata");

            levels.push(read_level(
                &mut decoder,
                levels.len() as u32,
                base_dimensions.width,
                tile_size,
            )?);
        }

        if !decoder.more_images() {
            break;
        }

        decoder.next_image()?;
    }

    Ok(Metadata::new(levels, objective_power, microns_per_pixel))
}

/// Parses an SVS file into its metadata and per-level tile directories.
///
/// Like [`read_metadata`], but also reads each pyramid level's
/// [`TileDirectory`] (tile offsets/byte counts/JPEG tables) in the same
/// pass, since both require walking the same IFDs.
///
/// # Errors
/// Returns [`WsiError`] if the file cannot be opened or required TIFF
/// metadata cannot be read.
pub fn parse_slide(path: &Path) -> Result<ParsedSlide, WsiError> {
    let mut decoder = get_decoder(path)?;

    let base_dimensions = Dimensions::from_tuple(decoder.dimensions()?);

    let mut levels = Vec::new();
    let mut tile_directories = Vec::new();

    let mut objective_power = None;
    let mut microns_per_pixel = None;

    loop {
        let parsed_ifd = parse_ifd(&mut decoder)?;

        // Parse Aperio metadata once.
        if objective_power.is_none() || microns_per_pixel.is_none() {
            let aperio = parse_aperio_metadata(&parsed_ifd.description);

            objective_power = objective_power.or(aperio.objective_power);

            microns_per_pixel = microns_per_pixel.or(aperio.microns_per_pixel);
        }

        if parsed_ifd.kind == ImageKind::PyramidLevel {
            let tile_size = parsed_ifd
                .tile_size
                .expect("Pyramid levels must have tile metadata");

            levels.push(read_level(
                &mut decoder,
                levels.len() as u32,
                base_dimensions.width,
                tile_size,
            )?);

            tile_directories.push(TileDirectory::read_tile_directory(&mut decoder)?);
        }

        if !decoder.more_images() {
            break;
        }

        decoder.next_image()?;
    }

    Ok(ParsedSlide {
        metadata: Metadata::new(levels, objective_power, microns_per_pixel),
        tile_directories,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classify_ifd_detects_label_regardless_of_case() {
        assert_eq!(
            classify_ifd(
                "Aperio Image Library LABEL 100x100",
                Some(&TileSize::new(240, 240))
            ),
            ImageKind::Label
        );
    }

    #[test]
    fn classify_ifd_detects_macro() {
        assert_eq!(classify_ifd("macro image", None), ImageKind::Macro);
    }

    #[test]
    fn classify_ifd_treats_tiled_untagged_images_as_pyramid_levels() {
        assert_eq!(
            classify_ifd("", Some(&TileSize::new(240, 240))),
            ImageKind::PyramidLevel
        );
    }

    #[test]
    fn classify_ifd_treats_untiled_untagged_images_as_thumbnails() {
        assert_eq!(classify_ifd("", None), ImageKind::Thumbnail);
    }

    #[test]
    fn parse_aperio_metadata_extracts_known_fields() {
        let description = "Aperio Image Library v1.0|AppMag = 20|MPP = 0.4990|Other = ignored";

        let metadata = parse_aperio_metadata(description);

        assert_eq!(metadata.objective_power, Some(20.0));
        assert_eq!(metadata.microns_per_pixel, Some(0.4990));
    }

    #[test]
    fn parse_aperio_metadata_leaves_missing_fields_as_none() {
        let metadata = parse_aperio_metadata("Aperio Image Library v1.0|MPP = 0.25");

        assert_eq!(metadata.objective_power, None);
        assert_eq!(metadata.microns_per_pixel, Some(0.25));
    }

    #[test]
    fn parse_aperio_metadata_ignores_unparseable_values() {
        let metadata = parse_aperio_metadata("AppMag = not-a-number|MPP = 0.25");

        assert_eq!(metadata.objective_power, None);
        assert_eq!(metadata.microns_per_pixel, Some(0.25));
    }
}