Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Use zero-copy views for pet crops

laurenspriem8ee82e71bce0
diff --git a/rust/crates/photos/src/ml/pet/align.rs b/rust/crates/photos/src/ml/pet/align.rs
index bd96dcc3b8..8f8f29219e 100644
--- a/rust/crates/photos/src/ml/pet/align.rs
+++ b/rust/crates/photos/src/ml/pet/align.rs
@@ -1,6 +1,3 @@
-use fast_image_resize::{
- FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, images::Image as FirImage,
-};
use image::{ImageBuffer, Rgb, RgbImage};
use crate::ml::{
@@ -8,6 +5,8 @@ use crate::ml::{
types::{DecodedImage, PetAlignmentResult, PetFaceDetection, PetFaceResult, to_face_id},
};
+use super::preprocess::{PixelCrop, resize_rgb_crop};
+
const PET_FACE_CROP_SIZE: u32 = 224;
/// Minimum eye distance in pixels below which alignment is skipped.
const MIN_EYE_DISTANCE: f32 = 5.0;
@@ -96,7 +95,7 @@ pub fn run_pet_face_alignment(
continue;
}
- let region = extract_rgb_region(decoded, region_x1, region_y1, region_w, region_h)?;
+ let region = RgbRegion::new(decoded, region_x1, region_y1, region_w, region_h)?;
// Face center relative to the extracted region
let local_cx = (box_x1 + box_x2) as f64 / 2.0 - region_x1 as f64;
@@ -151,9 +150,9 @@ pub fn run_pet_face_alignment(
/// Rotate an image around a center point using bilinear interpolation
/// with BORDER_REPLICATE behaviour (clamp to nearest edge pixel).
-fn rotate_around_center(source: &RgbImage, angle_rad: f64, cx: f64, cy: f64) -> RgbImage {
- let w = source.width();
- let h = source.height();
+fn rotate_around_center(source: &RgbRegion<'_>, angle_rad: f64, cx: f64, cy: f64) -> RgbImage {
+ let w = source.width;
+ let h = source.height;
let cos_a = angle_rad.cos();
let sin_a = angle_rad.sin();
@@ -184,10 +183,10 @@ fn rotate_around_center(source: &RgbImage, angle_rad: f64, cx: f64, cy: f64) ->
let fx = (sx - sx.floor()) as f32;
let fy = (sy - sy.floor()) as f32;
- let p00 = source.get_pixel(x0, y0).0;
- let p10 = source.get_pixel(x1, y0).0;
- let p01 = source.get_pixel(x0, y1).0;
- let p11 = source.get_pixel(x1, y1).0;
+ let p00 = source.get_pixel(x0, y0);
+ let p10 = source.get_pixel(x1, y0);
+ let p01 = source.get_pixel(x0, y1);
+ let p11 = source.get_pixel(x1, y1);
let mut px = [0u8; 3];
for c in 0..3 {
@@ -206,7 +205,6 @@ fn rotate_around_center(source: &RgbImage, angle_rad: f64, cx: f64, cy: f64) ->
/// Crop a region from an RGB image and resize to 224Γ—224 using bilinear interpolation.
fn crop_and_resize_rgb(source: &RgbImage, x: u32, y: u32, w: u32, h: u32) -> MlResult<RgbImage> {
- // Extract crop bytes
let src_w = source.width();
let src_h = source.height();
// Clamp crop region to source bounds to avoid edge-replication artifacts.
@@ -217,91 +215,98 @@ fn crop_and_resize_rgb(source: &RgbImage, x: u32, y: u32, w: u32, h: u32) -> MlR
"crop_and_resize_rgb: crop region extends beyond source image".to_string(),
));
}
- let mut crop_bytes = Vec::with_capacity((clamped_w as usize) * (clamped_h as usize) * 3);
- for row in y..(y + clamped_h) {
- for col in x..(x + clamped_w) {
- let px = source.get_pixel(col, row).0;
- crop_bytes.extend_from_slice(&px);
- }
- }
-
- let src_img = FirImage::from_vec_u8(clamped_w, clamped_h, crop_bytes, PixelType::U8x3)
- .map_err(|e| MlError::Preprocess(format!("FIR source: {e}")))?;
-
- let mut dst_img = FirImage::new(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, PixelType::U8x3);
- let mut resizer = Resizer::new();
- let opts = ResizeOptions::new().resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear));
- resizer
- .resize(&src_img, &mut dst_img, Some(&opts))
- .map_err(|e| MlError::Preprocess(format!("FIR resize: {e}")))?;
-
- let buf = dst_img.into_vec();
- ImageBuffer::<Rgb<u8>, _>::from_raw(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, buf)
- .ok_or_else(|| MlError::Preprocess("failed to build aligned face image".to_string()))
+ resize_crop_to_image(
+ source.as_raw(),
+ src_w,
+ src_h,
+ PixelCrop {
+ x,
+ y,
+ width: clamped_w,
+ height: clamped_h,
+ },
+ )
}
-/// Extract a rectangular region from the decoded image without cloning
-/// the entire buffer.
-fn extract_rgb_region(
+/// Crop directly from decoded image bytes and resize β€” avoids building a
+/// full-size RgbImage when no rotation is needed.
+fn crop_and_resize_decoded(
decoded: &DecodedImage,
x: u32,
y: u32,
w: u32,
h: u32,
) -> MlResult<RgbImage> {
- let img_w = decoded.dimensions.width as usize;
- let mut buf = Vec::with_capacity((w as usize) * (h as usize) * 3);
- for row in y..(y + h) {
- let start = ((row as usize) * img_w + (x as usize)) * 3;
- let end = start + (w as usize) * 3;
- if end > decoded.rgb.len() {
- return Err(MlError::Preprocess(format!(
- "region row {row} out of bounds (end={end}, len={})",
- decoded.rgb.len()
- )));
- }
- buf.extend_from_slice(&decoded.rgb[start..end]);
- }
- ImageBuffer::<Rgb<u8>, _>::from_raw(w, h, buf)
- .ok_or_else(|| MlError::Preprocess("failed to build region image".to_string()))
+ resize_crop_to_image(
+ &decoded.rgb,
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ PixelCrop {
+ x,
+ y,
+ width: w,
+ height: h,
+ },
+ )
}
-/// Crop directly from decoded image bytes and resize β€” avoids building a
-/// full-size RgbImage when no rotation is needed.
-fn crop_and_resize_decoded(
- decoded: &DecodedImage,
+fn resize_crop_to_image(
+ rgb: &[u8],
+ source_width: u32,
+ source_height: u32,
+ crop: PixelCrop,
+) -> MlResult<RgbImage> {
+ let buf = resize_rgb_crop(rgb, source_width, source_height, crop, PET_FACE_CROP_SIZE)?;
+ ImageBuffer::<Rgb<u8>, _>::from_raw(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, buf)
+ .ok_or_else(|| MlError::Preprocess("failed to build aligned face image".to_string()))
+}
+
+/// A row-strided view into a rectangular region of the decoded RGB buffer.
+struct RgbRegion<'a> {
+ rgb: &'a [u8],
+ image_width: usize,
x: u32,
y: u32,
- w: u32,
- h: u32,
-) -> MlResult<RgbImage> {
- let img_w = decoded.dimensions.width as usize;
- let mut crop_bytes = Vec::with_capacity((w as usize) * (h as usize) * 3);
- for row in y..(y + h) {
- let start = ((row as usize) * img_w + (x as usize)) * 3;
- let end = start + (w as usize) * 3;
- if end > decoded.rgb.len() {
- return Err(MlError::Preprocess(format!(
- "crop row {row} out of bounds (end={end}, len={})",
- decoded.rgb.len()
- )));
- }
- crop_bytes.extend_from_slice(&decoded.rgb[start..end]);
- }
+ width: u32,
+ height: u32,
+}
- let src_img = FirImage::from_vec_u8(w, h, crop_bytes, PixelType::U8x3)
- .map_err(|e| MlError::Preprocess(format!("FIR source: {e}")))?;
+impl<'a> RgbRegion<'a> {
+ fn new(decoded: &'a DecodedImage, x: u32, y: u32, width: u32, height: u32) -> MlResult<Self> {
+ if width == 0
+ || height == 0
+ || x > decoded.dimensions.width.saturating_sub(width)
+ || y > decoded.dimensions.height.saturating_sub(height)
+ {
+ return Err(MlError::Preprocess(
+ "RGB region extends beyond decoded image".to_string(),
+ ));
+ }
+ let expected_len = (decoded.dimensions.width as usize)
+ .checked_mul(decoded.dimensions.height as usize)
+ .and_then(|pixels| pixels.checked_mul(3))
+ .ok_or_else(|| MlError::Preprocess("decoded RGB dimensions overflow".to_string()))?;
+ if decoded.rgb.len() < expected_len {
+ return Err(MlError::Preprocess(
+ "decoded RGB buffer is shorter than its dimensions".to_string(),
+ ));
+ }
- let mut dst_img = FirImage::new(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, PixelType::U8x3);
- let mut resizer = Resizer::new();
- let opts = ResizeOptions::new().resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear));
- resizer
- .resize(&src_img, &mut dst_img, Some(&opts))
- .map_err(|e| MlError::Preprocess(format!("FIR resize: {e}")))?;
+ Ok(Self {
+ rgb: &decoded.rgb,
+ image_width: decoded.dimensions.width as usize,
+ x,
+ y,
+ width,
+ height,
+ })
+ }
- let buf = dst_img.into_vec();
- ImageBuffer::<Rgb<u8>, _>::from_raw(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, buf)
- .ok_or_else(|| MlError::Preprocess("failed to build aligned face image".to_string()))
+ #[inline]
+ fn get_pixel(&self, x: u32, y: u32) -> [u8; 3] {
+ let pixel = ((self.y + y) as usize * self.image_width + (self.x + x) as usize) * 3;
+ [self.rgb[pixel], self.rgb[pixel + 1], self.rgb[pixel + 2]]
+ }
}
/// Convert an aligned pet face image to ImageNet-normalized CHW tensor.
diff --git a/rust/crates/photos/src/ml/pet/embed.rs b/rust/crates/photos/src/ml/pet/embed.rs
index 5c4b020bf5..4eee6ec631 100644
--- a/rust/crates/photos/src/ml/pet/embed.rs
+++ b/rust/crates/photos/src/ml/pet/embed.rs
@@ -5,7 +5,7 @@ use crate::ml::{
types::{DecodedImage, PetBodyResult, PetFaceResult},
};
-use super::preprocess::{extract_crop, preprocess_pet_embedding};
+use super::preprocess::preprocess_pet_embedding;
const FACE_EMBED_INPUT_SIZE: i64 = 224;
const BODY_EMBED_INPUT_SIZE: i64 = 224;
@@ -148,9 +148,7 @@ pub fn run_pet_body_embedding(
let mut cat_indices = Vec::new();
let mut preprocessed: Vec<Option<Vec<f32>>> = Vec::with_capacity(body_results.len());
for (i, body_result) in body_results.iter().enumerate() {
- let crop = extract_crop(decoded, &body_result.detection.box_xyxy).and_then(
- |(crop_data, crop_w, crop_h)| preprocess_pet_embedding(&crop_data, crop_w, crop_h),
- );
+ let crop = preprocess_pet_embedding(decoded, &body_result.detection.box_xyxy);
match crop {
Ok(input) => {
preprocessed.push(Some(input));
diff --git a/rust/crates/photos/src/ml/pet/preprocess.rs b/rust/crates/photos/src/ml/pet/preprocess.rs
index 2f17b2f255..bc5d4844b8 100644
--- a/rust/crates/photos/src/ml/pet/preprocess.rs
+++ b/rust/crates/photos/src/ml/pet/preprocess.rs
@@ -1,5 +1,6 @@
use fast_image_resize::{
- FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, images::Image as FirImage,
+ FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer,
+ images::{CroppedImage, Image as FirImage, ImageRef as FirImageRef},
};
use crate::ml::{
@@ -13,6 +14,14 @@ const PET_EMBED_INPUT_SIZE: usize = 224;
const IMAGENET_MEAN: [f32; 3] = [0.485, 0.456, 0.406];
const IMAGENET_STD: [f32; 3] = [0.229, 0.224, 0.225];
+#[derive(Clone, Copy)]
+pub(super) struct PixelCrop {
+ pub(super) x: u32,
+ pub(super) y: u32,
+ pub(super) width: u32,
+ pub(super) height: u32,
+}
+
/// Preprocess a cropped pet face/body image for embedding extraction.
///
/// Steps:
@@ -27,32 +36,15 @@ const IMAGENET_STD: [f32; 3] = [0.229, 0.224, 0.225];
/// img = (img - IMAGENET_MEAN) / IMAGENET_STD
/// img = img.transpose(2, 0, 1) # HWC -> CHW
/// ```
-pub fn preprocess_pet_embedding(
- rgb_crop: &[u8],
- crop_width: u32,
- crop_height: u32,
-) -> MlResult<Vec<f32>> {
- if crop_width == 0 || crop_height == 0 {
- return Err(MlError::Preprocess(
- "crop dimensions cannot be zero".to_string(),
- ));
- }
-
- let target_w = PET_EMBED_INPUT_SIZE as u32;
- let target_h = PET_EMBED_INPUT_SIZE as u32;
-
- let src_image =
- FirImage::from_vec_u8(crop_width, crop_height, rgb_crop.to_vec(), PixelType::U8x3)
- .map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;
-
- let mut resized_image = FirImage::new(target_w, target_h, PixelType::U8x3);
- let mut resizer = Resizer::new();
- let options = ResizeOptions::new().resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear));
- resizer
- .resize(&src_image, &mut resized_image, Some(&options))
- .map_err(|e| MlError::Preprocess(format!("failed to resize pet embedding input: {e}")))?;
-
- let resized = resized_image.buffer();
+pub fn preprocess_pet_embedding(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<Vec<f32>> {
+ let crop = relative_crop(decoded, box_xyxy)?;
+ let resized = resize_rgb_crop(
+ &decoded.rgb,
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ crop,
+ PET_EMBED_INPUT_SIZE as u32,
+ )?;
let pixel_count = PET_EMBED_INPUT_SIZE * PET_EMBED_INPUT_SIZE;
let mut output = vec![0.0f32; 3 * pixel_count];
@@ -79,11 +71,7 @@ pub fn preprocess_pet_embedding(
Ok(output)
}
-/// Extract a cropped region from a decoded image given a bounding box.
-///
-/// The bounding box is in relative coordinates [0, 1].
-/// Returns the crop as RGB bytes and its dimensions.
-pub fn extract_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<(Vec<u8>, u32, u32)> {
+fn relative_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<PixelCrop> {
let img_w = decoded.dimensions.width;
let img_h = decoded.dimensions.height;
@@ -102,30 +90,95 @@ pub fn extract_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<(Ve
.round()
.clamp(0.0, img_h as f32) as u32;
- let crop_w = x2.saturating_sub(x1);
- let crop_h = y2.saturating_sub(y1);
+ let width = x2.saturating_sub(x1);
+ let height = y2.saturating_sub(y1);
- if crop_w == 0 || crop_h == 0 {
+ if width == 0 || height == 0 {
return Err(MlError::Preprocess("crop region has zero area".to_string()));
}
- let mut crop = Vec::with_capacity((crop_w as usize) * (crop_h as usize) * 3);
- for row in y1..y2 {
- let row_start = (row as usize) * (img_w as usize) + (x1 as usize);
- let row_end = (row as usize) * (img_w as usize) + (x2 as usize);
- let row_start = row_start * 3;
- let row_end = row_end * 3;
- if row_end > decoded.rgb.len() || row_start > decoded.rgb.len() {
- return Err(MlError::Preprocess(format!(
- "crop row {} out of bounds: start={}, end={}, buffer_len={}",
- row,
- row_start,
- row_end,
- decoded.rgb.len()
- )));
- }
- crop.extend_from_slice(&decoded.rgb[row_start..row_end]);
+ Ok(PixelCrop {
+ x: x1,
+ y: y1,
+ width,
+ height,
+ })
+}
+
+/// Resize a rectangular view of an RGB buffer without materializing the crop.
+pub(super) fn resize_rgb_crop(
+ rgb: &[u8],
+ source_width: u32,
+ source_height: u32,
+ crop: PixelCrop,
+ output_size: u32,
+) -> MlResult<Vec<u8>> {
+ if crop.width == 0 || crop.height == 0 {
+ return Err(MlError::Preprocess(
+ "crop dimensions cannot be zero".to_string(),
+ ));
+ }
+ if crop.x > source_width.saturating_sub(crop.width)
+ || crop.y > source_height.saturating_sub(crop.height)
+ {
+ return Err(MlError::Preprocess(
+ "crop region extends beyond source image".to_string(),
+ ));
}
- Ok((crop, crop_w, crop_h))
+ let source = FirImageRef::new(source_width, source_height, rgb, PixelType::U8x3)
+ .map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;
+ let source = CroppedImage::new(&source, crop.x, crop.y, crop.width, crop.height)
+ .map_err(|e| MlError::Preprocess(format!("failed to create FIR crop view: {e}")))?;
+ let mut resized = FirImage::new(output_size, output_size, PixelType::U8x3);
+ let options = ResizeOptions::new().resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear));
+ Resizer::new()
+ .resize(&source, &mut resized, Some(&options))
+ .map_err(|e| MlError::Preprocess(format!("failed to resize RGB crop: {e}")))?;
+
+ Ok(resized.into_vec())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{PixelCrop, resize_rgb_crop};
+
+ #[test]
+ fn cropped_view_resize_matches_a_materialized_crop() {
+ let width = 6u32;
+ let height = 5u32;
+ let rgb = (0..(width * height * 3))
+ .map(|value| (value % 251) as u8)
+ .collect::<Vec<_>>();
+ let crop = PixelCrop {
+ x: 1,
+ y: 1,
+ width: 4,
+ height: 3,
+ };
+
+ let direct = resize_rgb_crop(&rgb, width, height, crop, 7).unwrap();
+
+ let mut materialized = Vec::new();
+ for row in crop.y..crop.y + crop.height {
+ let start = ((row * width + crop.x) * 3) as usize;
+ let end = start + (crop.width * 3) as usize;
+ materialized.extend_from_slice(&rgb[start..end]);
+ }
+ let baseline = resize_rgb_crop(
+ &materialized,
+ crop.width,
+ crop.height,
+ PixelCrop {
+ x: 0,
+ y: 0,
+ width: crop.width,
+ height: crop.height,
+ },
+ 7,
+ )
+ .unwrap();
+
+ assert_eq!(direct, baseline);
+ }
}