1use std::{
4 rc::Rc,
5 sync::atomic::{AtomicU64, Ordering},
6};
7
8use crate::runtime::{RuntimeHandle, Storage};
9
10use crate::{DType, Error, Matrix, Result};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum ImageLayout {
15 Nchw,
17 Nhwc,
19 Chw,
21 Hwc,
23 Hw,
25}
26
27impl ImageLayout {
28 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum ImageFormat {
79 Gray,
81 GrayAlpha,
83 Rgb,
85 Rgba,
87 Bgr,
89 Bgra,
91}
92
93impl ImageFormat {
94 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#[derive(Clone)]
111pub struct Image {
112 data: Matrix,
113 layout: ImageLayout,
114 format: ImageFormat,
115 semantic: Rc<ImageSemantic>,
116}
117
118pub(crate) struct ImageSemantic {
120 id: u64,
121}
122
123impl Image {
124 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 pub const fn as_matrix(&self) -> &Matrix {
148 &self.data
149 }
150
151 pub fn into_matrix(self) -> Matrix {
153 self.data
154 }
155
156 pub fn width(&self) -> usize {
158 self.data.shape()[self.layout.axes().width]
159 }
160
161 pub fn height(&self) -> usize {
163 self.data.shape()[self.layout.axes().height]
164 }
165
166 pub const fn channels(&self) -> usize {
168 self.format.channels()
169 }
170
171 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 pub const fn layout(&self) -> ImageLayout {
182 self.layout
183 }
184
185 pub const fn format(&self) -> ImageFormat {
187 self.format
188 }
189
190 pub const fn dtype(&self) -> DType {
192 self.data.dtype()
193 }
194
195 pub(crate) const fn runtime(&self) -> &RuntimeHandle {
196 self.data.runtime()
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}