dcmnorm 0.23.2

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
Documentation
//! Region-of-interest rendering: crop a rectangle out of a rendered image before it is scaled.
//!
//! A [`Region`] is `x, y, width, height` in SOURCE pixel coordinates (the frame's own Rows x
//! Columns grid; for an MPR reformat, the output plane's grid; for a whole slide image, the
//! base level's total pixel matrix - see `super::wsi`). It is applied right after the frame is
//! rendered to 8-bit pixels (modality/VOI LUT, color conversion, ICC, overlay), and BEFORE
//! `output_width`/`output_height`/`scale_max_size`, redaction boxes and `pad` - so "this ROI,
//! scaled to fit 512px" is `region` + `scale_max_size: 512`.
//!
//! Out-of-bounds semantics: a region that hangs partly off the image is CLAMPED to the part
//! that overlaps it (the output is that intersection, so it can be smaller than requested). A
//! region with zero width or height, or one that doesn't overlap the image at all, is an error
//! ([`RenderError::InvalidRegion`]) rather than an empty image.

use std::fmt;
use std::str::FromStr;

use super::render::{RenderFrameOutput, RenderedFramePixels};
use super::types::RenderError;
use super::volume::PlaneParams;

/// A rectangle in source pixel coordinates. `x`/`y` may be negative (a region hanging off the
/// top/left edge); see the module docs for how such regions are clamped.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Region {
    /// Left edge (column of the first pixel), 0-based.
    pub x: i64,
    /// Top edge (row of the first pixel), 0-based.
    pub y: i64,
    pub width: u32,
    pub height: u32,
}

impl Region {
    pub fn new(x: i64, y: i64, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Exclusive right edge.
    pub fn right(&self) -> i64 {
        self.x + i64::from(self.width)
    }

    /// Exclusive bottom edge.
    pub fn bottom(&self) -> i64 {
        self.y + i64::from(self.height)
    }

    /// The part of this region inside a `width` x `height` image (always non-negative `x`/`y`,
    /// non-zero size). Errors when the region is empty or doesn't overlap the image at all.
    pub fn clamp_to(&self, width: u64, height: u64) -> Result<Region, RenderError> {
        if self.width == 0 || self.height == 0 {
            return Err(RenderError::InvalidRegion(format!(
                "{self} has zero width or height"
            )));
        }
        let width = i64::try_from(width).unwrap_or(i64::MAX);
        let height = i64::try_from(height).unwrap_or(i64::MAX);
        let left = self.x.clamp(0, width);
        let top = self.y.clamp(0, height);
        let right = self.right().clamp(0, width);
        let bottom = self.bottom().clamp(0, height);
        if right <= left || bottom <= top {
            return Err(RenderError::InvalidRegion(format!(
                "{self} lies entirely outside the {width}x{height} image"
            )));
        }
        Ok(Region::new(
            left,
            top,
            (right - left) as u32,
            (bottom - top) as u32,
        ))
    }

    /// Whether this region covers all of a `width` x `height` image.
    pub fn covers(&self, width: u64, height: u64) -> bool {
        self.x <= 0 && self.y <= 0 && self.right() >= width as i64 && self.bottom() >= height as i64
    }
}

impl fmt::Display for Region {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "region {},{},{},{}",
            self.x, self.y, self.width, self.height
        )
    }
}

impl FromStr for Region {
    type Err = RenderError;

    /// Parses `X,Y,W,H` (integers; `X`/`Y` may be negative, `W`/`H` must be positive).
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let invalid = || {
            RenderError::InvalidRegion(format!(
                "'{text}' is not X,Y,WIDTH,HEIGHT (integers, width and height > 0)"
            ))
        };
        let parts: Vec<&str> = text.split(',').map(str::trim).collect();
        let [x, y, width, height] = parts.as_slice() else {
            return Err(invalid());
        };
        let x = x.parse::<i64>().map_err(|_| invalid())?;
        let y = y.parse::<i64>().map_err(|_| invalid())?;
        let width = width.parse::<u32>().map_err(|_| invalid())?;
        let height = height.parse::<u32>().map_err(|_| invalid())?;
        if width == 0 || height == 0 {
            return Err(invalid());
        }
        Ok(Region::new(x, y, width, height))
    }
}

/// Crops a rendered 8-bit frame to `region` (clamped, see the module docs). `None` is a no-op.
pub(crate) fn crop_rendered_frame(
    frame: RenderedFramePixels,
    region: Option<&Region>,
) -> Result<RenderedFramePixels, RenderError> {
    let Some(region) = region else {
        return Ok(frame);
    };
    let clamped = region.clamp_to(u64::from(frame.width), u64::from(frame.height))?;
    if clamped.covers(u64::from(frame.width), u64::from(frame.height)) {
        return Ok(frame);
    }
    let expected = usize::from(frame.width)
        .checked_mul(usize::from(frame.height))
        .and_then(|pixels| pixels.checked_mul(usize::from(frame.samples_per_pixel)))
        .unwrap_or(usize::MAX);
    if frame.bytes.len() < expected {
        return Err(RenderError::InvalidPixelDataLength {
            expected,
            actual: frame.bytes.len(),
        });
    }
    let bytes = crop_interleaved(
        &frame.bytes,
        usize::from(frame.width),
        usize::from(frame.samples_per_pixel),
        &clamped,
    );
    Ok(RenderedFramePixels {
        width: clamped.width as u16,
        height: clamped.height as u16,
        samples_per_pixel: frame.samples_per_pixel,
        bytes,
    })
}

/// Crops `Raw` (stored pixel data) output: whole bytes per sample only, so BitsAllocated 1 is
/// rejected. `planar` is true when the bytes are color-by-plane (PlanarConfiguration 1 with
/// more than one sample per pixel); each plane is then cropped on its own and the output keeps
/// the planar layout.
pub(crate) fn crop_raw_output(
    mut output: RenderFrameOutput,
    region: Option<&Region>,
    planar: bool,
) -> Result<RenderFrameOutput, RenderError> {
    let Some(region) = region else {
        return Ok(output);
    };
    let clamped = region.clamp_to(u64::from(output.width), u64::from(output.height))?;
    if clamped.covers(u64::from(output.width), u64::from(output.height)) {
        return Ok(output);
    }
    if !output.bits_allocated.is_multiple_of(8) {
        return Err(RenderError::InvalidRegion(format!(
            "raw output can't be cropped at BitsAllocated {}",
            output.bits_allocated
        )));
    }
    let bytes_per_pixel =
        usize::from(output.samples_per_pixel) * usize::from(output.bits_allocated / 8);
    let expected = usize::from(output.width) * usize::from(output.height) * bytes_per_pixel;
    if output.bytes.len() < expected {
        return Err(RenderError::InvalidPixelDataLength {
            expected,
            actual: output.bytes.len(),
        });
    }
    let samples = usize::from(output.samples_per_pixel);
    output.bytes = if planar && samples > 1 {
        let bytes_per_sample = usize::from(output.bits_allocated / 8);
        let plane_len = expected / samples;
        let mut out =
            Vec::with_capacity(clamped.width as usize * clamped.height as usize * bytes_per_pixel);
        for plane in output.bytes[..expected].chunks_exact(plane_len) {
            out.extend(crop_interleaved(
                plane,
                usize::from(output.width),
                bytes_per_sample,
                &clamped,
            ));
        }
        out
    } else {
        crop_interleaved(
            &output.bytes,
            usize::from(output.width),
            bytes_per_pixel,
            &clamped,
        )
    };
    output.width = clamped.width as u16;
    output.height = clamped.height as u16;
    Ok(output)
}

/// Copies the rows of an already-clamped `region` out of a row-major interleaved buffer of
/// `width` pixels per row, `stride` bytes per pixel.
fn crop_interleaved(bytes: &[u8], width: usize, stride: usize, region: &Region) -> Vec<u8> {
    let row_len = region.width as usize * stride;
    let mut out = Vec::with_capacity(row_len * region.height as usize);
    for row in region.y as usize..region.bottom() as usize {
        let start = (row * width + region.x as usize) * stride;
        out.extend_from_slice(&bytes[start..start + row_len]);
    }
    out
}

/// The MPR equivalent of cropping: a [`PlaneParams`] that reformats exactly the `region`
/// sub-rectangle of `params`' output plane (clamped to `output_width` x `output_height`), by
/// moving the plane center and shrinking the output grid - same spacing and orientation, so
/// pixel `(i, j)` of the result samples the same world point as pixel `(x + i, y + j)` of the
/// full plane, and only the region's pixels are ever sampled.
///
/// One difference from cropping a full render: when no window is given, the automatic min/max
/// normalization (and the out-of-volume background value) is computed over the region alone.
/// Pass an explicit window for identical contrast: MPR applies a given window exactly, with no
/// fallback to normalization (only out-of-volume background pixels can still differ).
pub fn plane_params_for_region(
    params: &PlaneParams,
    region: &Region,
) -> Result<PlaneParams, RenderError> {
    let clamped = region.clamp_to(
        u64::from(params.output_width),
        u64::from(params.output_height),
    )?;
    let normalize = |v: [f64; 3]| {
        let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
        if length > 0.0 {
            [v[0] / length, v[1] / length, v[2] / length]
        } else {
            v
        }
    };
    let row_dir = normalize(params.row_dir);
    let col_dir = normalize(params.col_dir);
    // reformat_plane_values maps output column c to (c - W/2) * spacing from the origin, so the
    // region's own center offset is (x + w/2) - W/2 pixels.
    let dx =
        (clamped.x as f64 + f64::from(clamped.width) / 2.0) - f64::from(params.output_width) / 2.0;
    let dy = (clamped.y as f64 + f64::from(clamped.height) / 2.0)
        - f64::from(params.output_height) / 2.0;
    let mut shifted = params.clone();
    for axis in 0..3 {
        shifted.origin[axis] = params.origin[axis]
            + row_dir[axis] * dx * params.spacing_mm
            + col_dir[axis] * dy * params.spacing_mm;
    }
    shifted.output_width = clamped.width;
    shifted.output_height = clamped.height;
    Ok(shifted)
}