Skip to main content

oa/image/
image.rs

1//! Semantic image values composed over [`Matrix`].
2
3use std::{
4	rc::Rc,
5	sync::atomic::{AtomicU64, Ordering},
6};
7
8use crate::runtime::{EngineHandle, Storage};
9
10use crate::{DType, Error, Matrix, Result};
11
12/// Axis order carried by an [`Image`].
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum ImageLayout {
15	/// Batched channel-first layout: `[batch, channels, height, width]`.
16	Nchw,
17	/// Batched channel-last layout: `[batch, height, width, channels]`.
18	Nhwc,
19	/// Unbatched channel-first layout: `[channels, height, width]`.
20	Chw,
21	/// Unbatched channel-last layout: `[height, width, channels]`.
22	Hwc,
23	/// Unbatched single-channel layout: `[height, width]`.
24	Hw,
25}
26
27impl ImageLayout {
28	/// Return the matrix rank required by this layout.
29	pub const fn rank(self) -> usize {
30		match self {
31			Self::Nchw | Self::Nhwc => 4,
32			Self::Chw | Self::Hwc => 3,
33			Self::Hw => 2,
34		}
35	}
36
37	const fn axes(self) -> ImageAxes {
38		match self {
39			Self::Nchw => ImageAxes {
40				batch: Some(0),
41				channel: Some(1),
42				height: 2,
43				width: 3,
44			},
45			Self::Nhwc => ImageAxes {
46				batch: Some(0),
47				channel: Some(3),
48				height: 1,
49				width: 2,
50			},
51			Self::Chw => ImageAxes {
52				batch: None,
53				channel: Some(0),
54				height: 1,
55				width: 2,
56			},
57			Self::Hwc => ImageAxes {
58				batch: None,
59				channel: Some(2),
60				height: 0,
61				width: 1,
62			},
63			Self::Hw => ImageAxes {
64				batch: None,
65				channel: None,
66				height: 0,
67				width: 1,
68			},
69		}
70	}
71}
72
73/// Logical channel order carried by an [`Image`].
74///
75/// Scalar width and numeric representation remain properties of the backing
76/// [`Matrix`]; this format describes channel meaning only.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum ImageFormat {
79	/// One luminance channel.
80	Gray,
81	/// Luminance followed by alpha.
82	GrayAlpha,
83	/// Red, green, and blue.
84	Rgb,
85	/// Red, green, blue, and alpha.
86	Rgba,
87	/// Blue, green, and red.
88	Bgr,
89	/// Blue, green, red, and alpha.
90	Bgra,
91}
92
93impl ImageFormat {
94	/// Return the channel count required by this format.
95	pub const fn channels(self) -> usize {
96		match self {
97			Self::Gray => 1,
98			Self::GrayAlpha => 2,
99			Self::Rgb | Self::Bgr => 3,
100			Self::Rgba | Self::Bgra => 4,
101		}
102	}
103}
104
105/// Dense pixels with explicit axis-order and channel-order semantics.
106///
107/// `Image` composes a [`Matrix`] instead of erasing its numeric dtype and
108/// storage behavior. Construction validates all metadata once; the matrix is
109/// thereafter exposed immutably so the image contract cannot be invalidated.
110#[derive(Clone)]
111pub struct Image {
112	data: Matrix,
113	layout: ImageLayout,
114	format: ImageFormat,
115	semantic: Rc<ImageSemantic>,
116}
117
118/// Persistent semantic identity shared by clones of one Image value.
119pub(crate) struct ImageSemantic {
120	id: u64,
121}
122
123impl Image {
124	/// Attach checked image semantics to a dense matrix.
125	///
126	/// Zero-sized dimensions are legal. They remain useful for shape propagation
127	/// and carry no special allocation promise beyond the backing matrix contract.
128	///
129	/// # Errors
130	///
131	/// Returns an error when the matrix rank does not match `layout`, the channel
132	/// axis does not match `format`, or an `Hw` image is assigned a non-gray
133	/// format.
134	pub fn new(data: Matrix, layout: ImageLayout, format: ImageFormat) -> Result<Self> {
135		validate_image(&data, layout, format)?;
136		Ok(Self {
137			data,
138			layout,
139			format,
140			semantic: Rc::new(ImageSemantic {
141				id: next_image_value_id()?,
142			}),
143		})
144	}
145
146	/// Borrow the backing dense matrix without copying storage.
147	pub const fn as_matrix(&self) -> &Matrix {
148		&self.data
149	}
150
151	/// Remove image semantics and return the backing matrix.
152	pub fn into_matrix(self) -> Matrix {
153		self.data
154	}
155
156	/// Return the image width.
157	pub fn width(&self) -> usize {
158		self.data.shape()[self.layout.axes().width]
159	}
160
161	/// Return the image height.
162	pub fn height(&self) -> usize {
163		self.data.shape()[self.layout.axes().height]
164	}
165
166	/// Return the number of logical channels.
167	pub const fn channels(&self) -> usize {
168		self.format.channels()
169	}
170
171	/// Return the batch extent, or one for an unbatched layout.
172	pub fn batch_size(&self) -> usize {
173		self
174			.layout
175			.axes()
176			.batch
177			.map_or(1, |axis| self.data.shape()[axis])
178	}
179
180	/// Return the image axis order.
181	pub const fn layout(&self) -> ImageLayout {
182		self.layout
183	}
184
185	/// Return the logical channel order.
186	pub const fn format(&self) -> ImageFormat {
187		self.format
188	}
189
190	/// Return the scalar representation of the backing matrix.
191	pub const fn dtype(&self) -> DType {
192		self.data.dtype()
193	}
194
195	pub(crate) const fn engine_handle(&self) -> &EngineHandle {
196		self.data.engine_handle()
197	}
198
199	pub(crate) fn storage(&self) -> &Storage {
200		self.data.storage()
201	}
202
203	pub(crate) fn value_id(&self) -> u64 {
204		self.semantic.id
205	}
206}
207
208fn next_image_value_id() -> Result<u64> {
209	static NEXT_IMAGE_VALUE_ID: AtomicU64 = AtomicU64::new(1);
210	NEXT_IMAGE_VALUE_ID
211		.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
212			value.checked_add(1)
213		})
214		.map_err(|_| Error::resource_exhausted("image semantic value identity space is exhausted"))
215}
216
217#[derive(Clone, Copy)]
218struct ImageAxes {
219	batch: Option<usize>,
220	channel: Option<usize>,
221	height: usize,
222	width: usize,
223}
224
225fn validate_image(data: &Matrix, layout: ImageLayout, format: ImageFormat) -> Result<()> {
226	if data.shape().len() != layout.rank() {
227		return Err(Error::invalid_argument(format!(
228			"image layout {layout:?} requires rank {}, but the matrix has rank {}",
229			layout.rank(),
230			data.shape().len()
231		)));
232	}
233
234	let axes = layout.axes();
235	if let Some(channel_axis) = axes.channel {
236		let actual = data.shape()[channel_axis];
237		let required = format.channels();
238		if actual != required {
239			return Err(Error::invalid_argument(format!(
240				"image format {format:?} requires {required} channels, but axis {channel_axis} has {actual}"
241			)));
242		}
243	} else if format != ImageFormat::Gray {
244		return Err(Error::invalid_argument(format!(
245			"image layout {layout:?} has no channel axis and requires Gray format"
246		)));
247	}
248
249	Ok(())
250}