1use crate::{sys, Error, Mat, PixelFormat, Result};
3
4#[derive(Clone, Copy)]
6pub struct PixelImage<'a> {
7 data: &'a [u8],
8 size: (usize, usize),
9 stride: usize,
10 format: PixelFormat,
11}
12impl<'a> PixelImage<'a> {
13 pub fn new(data: &'a [u8], size: (usize, usize), format: PixelFormat) -> Result<Self> {
15 let stride = size
16 .0
17 .checked_mul(format.channels())
18 .ok_or(Error::invalid("Pixel stride overflow"))?;
19 if stride.checked_mul(size.1) != Some(data.len()) {
20 return Err(Error::invalid("Pixel buffer size mismatch"));
21 }
22 Self::with_stride(data, size, stride, format)
23 }
24 pub fn with_stride(
26 data: &'a [u8],
27 size: (usize, usize),
28 stride: usize,
29 format: PixelFormat,
30 ) -> Result<Self> {
31 let row = size
32 .0
33 .checked_mul(format.channels())
34 .ok_or(Error::invalid("Pixel row overflow"))?;
35 if size.0 == 0
36 || size.1 == 0
37 || stride < row
38 || stride > i32::MAX as usize
39 || size.1 > i32::MAX as usize
40 {
41 return Err(Error::invalid("Invalid image dimensions or stride"));
42 }
43 let count = (size.1 - 1)
44 .checked_mul(stride)
45 .and_then(|n| n.checked_add(row))
46 .ok_or(Error::invalid("Image size overflow"))?;
47 if count > data.len() || count > i32::MAX as usize {
48 return Err(Error::invalid(
49 "Image rows exceed the buffer or native range",
50 ));
51 }
52 Ok(Self {
53 data,
54 size,
55 stride,
56 format,
57 })
58 }
59 pub fn roi(self, origin: (usize, usize), size: (usize, usize)) -> Result<Self> {
61 if origin
62 .0
63 .checked_add(size.0)
64 .filter(|end| *end <= self.size.0)
65 .is_none()
66 || origin
67 .1
68 .checked_add(size.1)
69 .filter(|end| *end <= self.size.1)
70 .is_none()
71 {
72 return Err(Error::invalid("Image region is out of bounds"));
73 }
74 let offset = origin
75 .1
76 .checked_mul(self.stride)
77 .and_then(|n| {
78 origin
79 .0
80 .checked_mul(self.format.channels())
81 .and_then(|x| n.checked_add(x))
82 })
83 .ok_or(Error::invalid("Image offset overflow"))?;
84 let data = self
85 .data
86 .get(offset..)
87 .ok_or(Error::invalid("Image region exceeds its buffer"))?;
88 Self::with_stride(data, size, self.stride, self.format)
89 }
90 fn conversion(self, destination: PixelFormat, target: (usize, usize)) -> Result<i32> {
91 let channels = self.format.channels().max(destination.channels());
92 let count = target
93 .0
94 .checked_mul(target.1)
95 .and_then(|n| n.checked_mul(channels));
96 if target.0 == 0 || target.1 == 0 || count.filter(|n| *n <= i32::MAX as usize).is_none() {
97 return Err(Error::invalid("Target image exceeds native dimensions"));
98 }
99 Ok(if self.format == destination {
100 self.format as i32
101 } else {
102 self.format as i32 | ((destination as i32) << 16)
103 })
104 }
105 pub fn to_mat(self, destination: PixelFormat) -> Result<Mat> {
107 let kind = self.conversion(destination, self.size)?;
108 unsafe {
109 Mat::owned(
110 sys::ncnn_mat_from_pixels(
111 self.data.as_ptr(),
112 kind,
113 self.size.0 as i32,
114 self.size.1 as i32,
115 self.stride as i32,
116 std::ptr::null_mut(),
117 ),
118 true,
119 )
120 }
121 }
122 pub fn resize_to_mat(self, destination: PixelFormat, target: (usize, usize)) -> Result<Mat> {
124 let kind = self.conversion(destination, target)?;
125 if self.size != target && (self.size.0 < 2 || self.size.1 < 2) {
126 return Err(Error::invalid(
127 "Bilinear source dimensions must be at least two",
128 ));
129 }
130 unsafe {
131 Mat::owned(
132 sys::ncnn_mat_from_pixels_resize(
133 self.data.as_ptr(),
134 kind,
135 self.size.0 as i32,
136 self.size.1 as i32,
137 self.stride as i32,
138 target.0 as i32,
139 target.1 as i32,
140 std::ptr::null_mut(),
141 ),
142 true,
143 )
144 }
145 }
146}
147
148fn dimensions(w: usize, h: usize, channels: usize, len: usize) -> Result<(i32, i32)> {
149 if !(1..=4).contains(&channels)
150 || w == 0
151 || h == 0
152 || w > i32::MAX as usize / channels
153 || h > i32::MAX as usize
154 {
155 return Err(Error::invalid("Invalid image dimensions"));
156 }
157 if w.checked_mul(h).and_then(|n| n.checked_mul(channels)) != Some(len)
158 || len > isize::MAX as usize
159 {
160 return Err(Error::invalid("Image byte count mismatch"));
161 }
162 Ok((w as i32, h as i32))
163}
164
165pub fn resize(
167 data: &[u8],
168 size: (usize, usize),
169 channels: usize,
170 target: (usize, usize),
171) -> Result<Vec<u8>> {
172 let (w, h) = dimensions(size.0, size.1, channels, data.len())?;
173 if w < 2 || h < 2 {
174 return Err(Error::invalid(
175 "Bilinear source dimensions must be at least two",
176 ));
177 }
178 let count = target
179 .0
180 .checked_mul(target.1)
181 .and_then(|n| n.checked_mul(channels))
182 .ok_or(Error::invalid("Image size overflow"))?;
183 let (tw, th) = dimensions(target.0, target.1, channels, count)?;
184 let mut out = vec![0; count];
185 unsafe {
186 let call = match channels {
187 1 => sys::ncnn_rs_image_resize_bilinear_c1,
188 2 => sys::ncnn_rs_image_resize_bilinear_c2,
189 3 => sys::ncnn_rs_image_resize_bilinear_c3,
190 _ => sys::ncnn_rs_image_resize_bilinear_c4,
191 };
192 call(data.as_ptr(), w, h, out.as_mut_ptr(), tw, th);
193 }
194 Ok(out)
195}
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201#[non_exhaustive]
202pub enum WarpBorder {
203 Constant = 0,
205 Replicate = 1,
207 Transparent = 2,
209}
210
211pub fn affine_transform(from: &[[f32; 2]], to: &[[f32; 2]]) -> Result<[f32; 6]> {
217 if from.len() != to.len() || from.is_empty() || from.len() > 3 {
218 return Err(Error::invalid(
219 "An affine transform needs one to three matching point pairs",
220 ));
221 }
222 let flatten = |points: &[[f32; 2]]| -> Vec<f32> { points.iter().flatten().copied().collect() };
223 let points_from = flatten(from);
224 let points_to = flatten(to);
225 let mut matrix = [0.0f32; 6];
226 unsafe {
227 sys::ncnn_rs_image_get_affine_transform(
228 points_from.as_ptr(),
229 points_to.as_ptr(),
230 from.len() as i32,
231 matrix.as_mut_ptr(),
232 );
233 }
234 Ok(matrix)
235}
236
237pub fn invert_affine(matrix: &[f32; 6]) -> [f32; 6] {
239 let mut inverted = [0.0f32; 6];
240 unsafe {
241 sys::ncnn_rs_image_invert_affine_transform(matrix.as_ptr(), inverted.as_mut_ptr());
242 }
243 inverted
244}
245
246pub fn warp_affine(
252 data: &[u8],
253 size: (usize, usize),
254 channels: usize,
255 target: (usize, usize),
256 matrix: &[f32; 6],
257 border: WarpBorder,
258 value: u32,
259) -> Result<Vec<u8>> {
260 let (w, h) = dimensions(size.0, size.1, channels, data.len())?;
261 let count = target
262 .0
263 .checked_mul(target.1)
264 .and_then(|n| n.checked_mul(channels))
265 .ok_or(Error::invalid("Image size overflow"))?;
266 let (tw, th) = dimensions(target.0, target.1, channels, count)?;
267 let mut out = vec![0; count];
268 unsafe {
269 let call = match channels {
270 1 => sys::ncnn_rs_image_warpaffine_bilinear_c1,
271 2 => sys::ncnn_rs_image_warpaffine_bilinear_c2,
272 3 => sys::ncnn_rs_image_warpaffine_bilinear_c3,
273 _ => sys::ncnn_rs_image_warpaffine_bilinear_c4,
274 };
275 call(
276 data.as_ptr(),
277 w,
278 h,
279 out.as_mut_ptr(),
280 tw,
281 th,
282 matrix.as_ptr(),
283 border as i32,
284 value,
285 );
286 }
287 Ok(out)
288}
289
290pub fn orient(
292 data: &[u8],
293 size: (usize, usize),
294 channels: usize,
295 orientation: u8,
296) -> Result<(Vec<u8>, (usize, usize))> {
297 let (w, h) = dimensions(size.0, size.1, channels, data.len())?;
298 if !(1..=8).contains(&orientation) {
299 return Err(Error::invalid("Orientation must be 1..=8"));
300 }
301 let target = if orientation >= 5 {
302 (size.1, size.0)
303 } else {
304 size
305 };
306 let mut out = vec![0; data.len()];
307 unsafe {
308 let call = match channels {
309 1 => sys::ncnn_rs_image_kanna_rotate_c1,
310 2 => sys::ncnn_rs_image_kanna_rotate_c2,
311 3 => sys::ncnn_rs_image_kanna_rotate_c3,
312 _ => sys::ncnn_rs_image_kanna_rotate_c4,
313 };
314 call(
315 data.as_ptr(),
316 w,
317 h,
318 out.as_mut_ptr(),
319 target.0 as i32,
320 target.1 as i32,
321 orientation as i32,
322 );
323 }
324 Ok((out, target))
325}