Skip to content

armgit / ente

Public Imported from GitHub
0

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

Flatten pet embedding preprocessing batches

laurenspriem34f29761870a
diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rs
index 021181cb34..8527bd97b6 100644
--- a/rust/crates/photos/src/ml/indexing.rs
+++ b/rust/crates/photos/src/ml/indexing.rs
@@ -110,7 +110,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
let pet_face_results = if !pet_face_detections.is_empty() {
let (aligned, mut pet_results) =
run_pet_face_alignment(file_id, &decoded, &pet_face_detections)?;
- run_pet_face_embedding(runtime, &aligned, &mut pet_results)?;
+ run_pet_face_embedding(runtime, aligned, &mut pet_results)?;
pet_results
} else {
Vec::new()
diff --git a/rust/crates/photos/src/ml/pet/align.rs b/rust/crates/photos/src/ml/pet/align.rs
index 8f8f29219e..5fff953f58 100644
--- a/rust/crates/photos/src/ml/pet/align.rs
+++ b/rust/crates/photos/src/ml/pet/align.rs
@@ -1,11 +1,14 @@
-use image::{ImageBuffer, Rgb, RgbImage};
+use image::{Rgb, RgbImage};
use crate::ml::{
error::{MlError, MlResult},
types::{DecodedImage, PetAlignmentResult, PetFaceDetection, PetFaceResult, to_face_id},
};
-use super::preprocess::{PixelCrop, resize_rgb_crop};
+use super::{
+ embed::PetFaceEmbeddingInputs,
+ preprocess::{PixelCrop, RgbCropResizer, append_imagenet_tensor},
+};
const PET_FACE_CROP_SIZE: u32 = 224;
/// Minimum eye distance in pixels below which alignment is skipped.
@@ -23,18 +26,24 @@ const CROP_EXPAND: f32 = 0.1;
/// 3. Otherwise rotate around face center, then crop with 10% expand
/// 4. Resize to 224Γ—224
/// 5. Apply ImageNet normalization (CHW)
-pub fn run_pet_face_alignment(
+pub(crate) fn run_pet_face_alignment(
file_id: i64,
decoded: &DecodedImage,
detections: &[PetFaceDetection],
-) -> MlResult<(Vec<Vec<f32>>, Vec<PetFaceResult>)> {
+) -> MlResult<(PetFaceEmbeddingInputs, Vec<PetFaceResult>)> {
let img_w = decoded.dimensions.width;
let img_h = decoded.dimensions.height;
let img_wf = img_w as f32;
let img_hf = img_h as f32;
- let mut aligned_inputs = Vec::with_capacity(detections.len());
+ let cat_capacity = detections
+ .iter()
+ .filter(|detection| detection.class_id == 1)
+ .count();
+ let dog_capacity = detections.len() - cat_capacity;
+ let mut aligned_inputs = PetFaceEmbeddingInputs::new(dog_capacity, cat_capacity);
let mut face_results = Vec::with_capacity(detections.len());
+ let mut crop_resizer = RgbCropResizer::new(PET_FACE_CROP_SIZE);
for detection in detections {
// Convert relative keypoints to absolute
@@ -78,7 +87,7 @@ pub fn run_pet_face_alignment(
if crop_w == 0 || crop_h == 0 {
continue;
}
- crop_and_resize_decoded(decoded, cx1, cy1, crop_w, crop_h)?
+ crop_and_resize_decoded(&mut crop_resizer, decoded, cx1, cy1, crop_w, crop_h)?
} else {
// Rotate only a padded region around the face, not the full image.
let bw = (box_x2 - box_x1) as f32;
@@ -115,10 +124,13 @@ pub fn run_pet_face_alignment(
if crop_w == 0 || crop_h == 0 {
continue;
}
- crop_and_resize_rgb(&rotated, nx1, ny1, crop_w, crop_h)?
+ crop_and_resize_rgb(&mut crop_resizer, &rotated, nx1, ny1, crop_w, crop_h)?
};
- let normalized = aligned_face_to_tensor(&aligned_rgb);
+ let result_index = face_results.len();
+ let batch = aligned_inputs.batch_mut(detection.class_id);
+ append_imagenet_tensor(aligned_rgb, &mut batch.input);
+ batch.indices.push(result_index);
let base_id = to_face_id(file_id, detection.box_xyxy);
let pet_face_id = format!("{base_id}_c{}", detection.class_id);
@@ -135,7 +147,6 @@ pub fn run_pet_face_alignment(
crop_size,
};
- aligned_inputs.push(normalized);
face_results.push(PetFaceResult {
detection: detection.clone(),
species: 0, // will be set after embedding
@@ -204,7 +215,14 @@ fn rotate_around_center(source: &RgbRegion<'_>, 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> {
+fn crop_and_resize_rgb<'a>(
+ resizer: &'a mut RgbCropResizer,
+ source: &RgbImage,
+ x: u32,
+ y: u32,
+ w: u32,
+ h: u32,
+) -> MlResult<&'a [u8]> {
let src_w = source.width();
let src_h = source.height();
// Clamp crop region to source bounds to avoid edge-replication artifacts.
@@ -215,7 +233,8 @@ 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(),
));
}
- resize_crop_to_image(
+ resize_crop(
+ resizer,
source.as_raw(),
src_w,
src_h,
@@ -230,14 +249,16 @@ fn crop_and_resize_rgb(source: &RgbImage, x: u32, y: u32, w: u32, h: u32) -> MlR
/// Crop directly from decoded image bytes and resize β€” avoids building a
/// full-size RgbImage when no rotation is needed.
-fn crop_and_resize_decoded(
+fn crop_and_resize_decoded<'a>(
+ resizer: &'a mut RgbCropResizer,
decoded: &DecodedImage,
x: u32,
y: u32,
w: u32,
h: u32,
-) -> MlResult<RgbImage> {
- resize_crop_to_image(
+) -> MlResult<&'a [u8]> {
+ resize_crop(
+ resizer,
&decoded.rgb,
decoded.dimensions.width,
decoded.dimensions.height,
@@ -250,15 +271,14 @@ fn crop_and_resize_decoded(
)
}
-fn resize_crop_to_image(
+fn resize_crop<'a>(
+ resizer: &'a mut RgbCropResizer,
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()))
+) -> MlResult<&'a [u8]> {
+ resizer.resize(rgb, source_width, source_height, crop)
}
/// A row-strided view into a rectangular region of the decoded RGB buffer.
@@ -308,28 +328,3 @@ impl<'a> RgbRegion<'a> {
[self.rgb[pixel], self.rgb[pixel + 1], self.rgb[pixel + 2]]
}
}
-
-/// Convert an aligned pet face image to ImageNet-normalized CHW tensor.
-fn aligned_face_to_tensor(face_image: &RgbImage) -> Vec<f32> {
- let w = face_image.width() as usize;
- let h = face_image.height() as usize;
- let pixel_count = w * h;
- let mut output = vec![0.0f32; 3 * pixel_count];
-
- const MEAN: [f32; 3] = [0.485, 0.456, 0.406];
- const STD: [f32; 3] = [0.229, 0.224, 0.225];
-
- let r_off = 0;
- let g_off = pixel_count;
- let b_off = 2 * pixel_count;
-
- let raw = face_image.as_raw();
- for i in 0..pixel_count {
- let src_idx = i * 3;
- output[r_off + i] = (raw[src_idx] as f32 / 255.0 - MEAN[0]) / STD[0];
- output[g_off + i] = (raw[src_idx + 1] as f32 / 255.0 - MEAN[1]) / STD[1];
- output[b_off + i] = (raw[src_idx + 2] as f32 / 255.0 - MEAN[2]) / STD[2];
- }
-
- output
-}
diff --git a/rust/crates/photos/src/ml/pet/embed.rs b/rust/crates/photos/src/ml/pet/embed.rs
index 4eee6ec631..fd6dadfd18 100644
--- a/rust/crates/photos/src/ml/pet/embed.rs
+++ b/rust/crates/photos/src/ml/pet/embed.rs
@@ -5,13 +5,55 @@ use crate::ml::{
types::{DecodedImage, PetBodyResult, PetFaceResult},
};
-use super::preprocess::preprocess_pet_embedding;
+use super::preprocess::PetEmbeddingPreprocessor;
const FACE_EMBED_INPUT_SIZE: i64 = 224;
const BODY_EMBED_INPUT_SIZE: i64 = 224;
const FACE_EMBED_CHANNELS: i64 = 3;
const BODY_EMBED_CHANNELS: i64 = 3;
+pub(super) struct IndexedEmbeddingBatch {
+ pub(super) indices: Vec<usize>,
+ pub(super) input: Vec<f32>,
+}
+
+impl IndexedEmbeddingBatch {
+ fn new(item_capacity: usize, floats_per_item: usize) -> Self {
+ Self {
+ indices: Vec::with_capacity(item_capacity),
+ input: Vec::with_capacity(item_capacity * floats_per_item),
+ }
+ }
+
+ fn is_empty(&self) -> bool {
+ self.indices.is_empty()
+ }
+}
+
+pub(crate) struct PetFaceEmbeddingInputs {
+ pub(super) dog: IndexedEmbeddingBatch,
+ pub(super) cat: IndexedEmbeddingBatch,
+}
+
+impl PetFaceEmbeddingInputs {
+ pub(super) fn new(dog_capacity: usize, cat_capacity: usize) -> Self {
+ let floats_per_face =
+ (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;
+ Self {
+ dog: IndexedEmbeddingBatch::new(dog_capacity, floats_per_face),
+ cat: IndexedEmbeddingBatch::new(cat_capacity, floats_per_face),
+ }
+ }
+
+ pub(super) fn batch_mut(&mut self, class_id: u8) -> &mut IndexedEmbeddingBatch {
+ if class_id == 1 {
+ &mut self.cat
+ } else {
+ &mut self.dog
+ }
+ }
+}
+
/// Run pet face embedding on aligned face inputs.
///
/// The species parameter (0=dog, 1=cat) selects the model to use.
@@ -24,18 +66,19 @@ const BODY_EMBED_CHANNELS: i64 = 3;
///
/// Faces are grouped by species and batched per model to avoid running the
/// wrong embedding model on any detection.
-pub fn run_pet_face_embedding(
+pub(crate) fn run_pet_face_embedding(
runtime: &MlRuntimeView<'_>,
- aligned_faces: &[Vec<f32>],
+ aligned_faces: PetFaceEmbeddingInputs,
face_results: &mut [PetFaceResult],
) -> MlResult<()> {
- if aligned_faces.is_empty() {
+ let aligned_count = aligned_faces.dog.indices.len() + aligned_faces.cat.indices.len();
+ if aligned_count == 0 {
return Ok(());
}
- if aligned_faces.len() != face_results.len() {
+ if aligned_count != face_results.len() {
return Err(MlError::Postprocess(format!(
"aligned pet faces count ({}) does not match face result count ({})",
- aligned_faces.len(),
+ aligned_count,
face_results.len()
)));
}
@@ -43,34 +86,16 @@ pub fn run_pet_face_embedding(
let per_face_len =
(FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;
- // Group indices by species (class_id from detection).
- let mut dog_indices = Vec::new();
- let mut cat_indices = Vec::new();
- for (i, fr) in face_results.iter().enumerate() {
- if fr.detection.class_id == 1 {
- cat_indices.push(i);
- } else {
- dog_indices.push(i);
- }
- }
-
- // Process each species batch.
- for (species, indices) in [(0u8, &dog_indices), (1u8, &cat_indices)] {
- if indices.is_empty() {
+ for (species, batch) in [(0u8, aligned_faces.dog), (1u8, aligned_faces.cat)] {
+ if batch.is_empty() {
continue;
}
-
- let mut input = Vec::with_capacity(per_face_len * indices.len());
- for &idx in indices {
- let aligned = &aligned_faces[idx];
- if aligned.len() != per_face_len {
- return Err(MlError::Preprocess(format!(
- "aligned pet face tensor length {} does not match expected {}",
- aligned.len(),
- per_face_len
- )));
- }
- input.extend_from_slice(aligned);
+ if batch.input.len() != per_face_len * batch.indices.len() {
+ return Err(MlError::Preprocess(format!(
+ "pet face batch tensor length {} does not match expected {}",
+ batch.input.len(),
+ per_face_len * batch.indices.len()
+ )));
}
let mut session = if species == 0 {
@@ -81,9 +106,9 @@ pub fn run_pet_face_embedding(
let (shape, output) = onnx::run_f32(
&mut session,
- input,
+ batch.input,
[
- indices.len() as i64,
+ batch.indices.len() as i64,
FACE_EMBED_CHANNELS,
FACE_EMBED_INPUT_SIZE,
FACE_EMBED_INPUT_SIZE,
@@ -95,22 +120,22 @@ pub fn run_pet_face_embedding(
"pet face embedding output shape is empty".to_string(),
));
}
- let batch = shape[0] as usize;
- if batch != indices.len() {
+ let output_batch = shape[0] as usize;
+ if output_batch != batch.indices.len() {
return Err(MlError::Postprocess(format!(
- "pet face embedding batch mismatch: output={batch}, expected={}",
- indices.len()
+ "pet face embedding batch mismatch: output={output_batch}, expected={}",
+ batch.indices.len()
)));
}
- let embedding_size = output.len() / batch;
- if embedding_size == 0 || output.len() != batch * embedding_size {
+ let embedding_size = output.len() / output_batch;
+ if embedding_size == 0 || output.len() != output_batch * embedding_size {
return Err(MlError::Postprocess(format!(
- "pet face embedding output not evenly divisible: len={}, batch={batch}",
+ "pet face embedding output not evenly divisible: len={}, batch={output_batch}",
output.len()
)));
}
- for (batch_idx, &orig_idx) in indices.iter().enumerate() {
+ for (batch_idx, &orig_idx) in batch.indices.iter().enumerate() {
let start = batch_idx * embedding_size;
let mut embedding = output[start..(start + embedding_size)].to_vec();
normalize_embedding(&mut embedding);
@@ -129,7 +154,7 @@ pub fn run_pet_face_embedding(
/// Bodies are grouped by species and batched per model.
///
/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_body()`.
-pub fn run_pet_body_embedding(
+pub(crate) fn run_pet_body_embedding(
runtime: &MlRuntimeView<'_>,
decoded: &DecodedImage,
body_results: &mut [PetBodyResult],
@@ -144,37 +169,37 @@ pub fn run_pet_body_embedding(
// Preprocess all crops and group by species.
// Skip detections whose crop is invalid (e.g. zero-area edge boxes)
// rather than aborting the whole image.
- let mut dog_indices = Vec::new();
- let mut cat_indices = Vec::new();
- let mut preprocessed: Vec<Option<Vec<f32>>> = Vec::with_capacity(body_results.len());
+ let cat_count = body_results
+ .iter()
+ .filter(|result| result.detection.coco_class == 15)
+ .count();
+ let dog_count = body_results.len() - cat_count;
+ let mut dog_batch = IndexedEmbeddingBatch::new(dog_count, per_body_len);
+ let mut cat_batch = IndexedEmbeddingBatch::new(cat_count, per_body_len);
+ let mut preprocessor = PetEmbeddingPreprocessor::new();
+
for (i, body_result) in body_results.iter().enumerate() {
- let crop = preprocess_pet_embedding(decoded, &body_result.detection.box_xyxy);
- match crop {
- Ok(input) => {
- preprocessed.push(Some(input));
- if body_result.detection.coco_class == 15 {
- cat_indices.push(i);
- } else {
- dog_indices.push(i);
- }
- }
- Err(_) => {
- preprocessed.push(None);
- }
+ let batch = if body_result.detection.coco_class == 15 {
+ &mut cat_batch
+ } else {
+ &mut dog_batch
+ };
+ let original_len = batch.input.len();
+ if preprocessor
+ .append(decoded, &body_result.detection.box_xyxy, &mut batch.input)
+ .is_ok()
+ {
+ batch.indices.push(i);
+ } else {
+ batch.input.truncate(original_len);
}
}
- // Process each species batch.
- for (is_cat, indices) in [(false, &dog_indices), (true, &cat_indices)] {
- if indices.is_empty() {
+ for (is_cat, batch) in [(false, dog_batch), (true, cat_batch)] {
+ if batch.is_empty() {
continue;
}
- let mut input = Vec::with_capacity(per_body_len * indices.len());
- for &idx in indices {
- input.extend_from_slice(preprocessed[idx].as_ref().unwrap());
- }
-
let mut session = if is_cat {
runtime.pet_body_embedding_cat_session()?
} else {
@@ -183,9 +208,9 @@ pub fn run_pet_body_embedding(
let (shape, output) = onnx::run_f32(
&mut session,
- input,
+ batch.input,
[
- indices.len() as i64,
+ batch.indices.len() as i64,
BODY_EMBED_CHANNELS,
BODY_EMBED_INPUT_SIZE,
BODY_EMBED_INPUT_SIZE,
@@ -197,22 +222,22 @@ pub fn run_pet_body_embedding(
"pet body embedding output shape is empty".to_string(),
));
}
- let batch = shape[0] as usize;
- if batch != indices.len() {
+ let output_batch = shape[0] as usize;
+ if output_batch != batch.indices.len() {
return Err(MlError::Postprocess(format!(
- "pet body embedding batch mismatch: output={batch}, expected={}",
- indices.len()
+ "pet body embedding batch mismatch: output={output_batch}, expected={}",
+ batch.indices.len()
)));
}
- let embedding_size = output.len() / batch;
- if embedding_size == 0 || output.len() != batch * embedding_size {
+ let embedding_size = output.len() / output_batch;
+ if embedding_size == 0 || output.len() != output_batch * embedding_size {
return Err(MlError::Postprocess(format!(
- "pet body embedding output not evenly divisible: len={}, batch={batch}",
+ "pet body embedding output not evenly divisible: len={}, batch={output_batch}",
output.len()
)));
}
- for (batch_idx, &orig_idx) in indices.iter().enumerate() {
+ for (batch_idx, &orig_idx) in batch.indices.iter().enumerate() {
let start = batch_idx * embedding_size;
let mut embedding = output[start..(start + embedding_size)].to_vec();
normalize_embedding(&mut embedding);
diff --git a/rust/crates/photos/src/ml/pet/preprocess.rs b/rust/crates/photos/src/ml/pet/preprocess.rs
index bc5d4844b8..c00191b275 100644
--- a/rust/crates/photos/src/ml/pet/preprocess.rs
+++ b/rust/crates/photos/src/ml/pet/preprocess.rs
@@ -36,39 +36,33 @@ pub(super) struct PixelCrop {
/// img = (img - IMAGENET_MEAN) / IMAGENET_STD
/// img = img.transpose(2, 0, 1) # HWC -> CHW
/// ```
-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];
-
- // CHW layout with ImageNet normalization
- let r_offset = 0;
- let g_offset = pixel_count;
- let b_offset = 2 * pixel_count;
-
- for y in 0..PET_EMBED_INPUT_SIZE {
- for x in 0..PET_EMBED_INPUT_SIZE {
- let src_idx = (y * PET_EMBED_INPUT_SIZE + x) * 3;
- let dst_idx = y * PET_EMBED_INPUT_SIZE + x;
-
- let r = resized[src_idx] as f32 / 255.0;
- let g = resized[src_idx + 1] as f32 / 255.0;
- let b = resized[src_idx + 2] as f32 / 255.0;
+pub(super) struct PetEmbeddingPreprocessor {
+ crop_resizer: RgbCropResizer,
+}
- output[r_offset + dst_idx] = (r - IMAGENET_MEAN[0]) / IMAGENET_STD[0];
- output[g_offset + dst_idx] = (g - IMAGENET_MEAN[1]) / IMAGENET_STD[1];
- output[b_offset + dst_idx] = (b - IMAGENET_MEAN[2]) / IMAGENET_STD[2];
+impl PetEmbeddingPreprocessor {
+ pub(super) fn new() -> Self {
+ Self {
+ crop_resizer: RgbCropResizer::new(PET_EMBED_INPUT_SIZE as u32),
}
}
- Ok(output)
+ pub(super) fn append(
+ &mut self,
+ decoded: &DecodedImage,
+ box_xyxy: &[f32; 4],
+ output: &mut Vec<f32>,
+ ) -> MlResult<()> {
+ let crop = relative_crop(decoded, box_xyxy)?;
+ let resized = self.crop_resizer.resize(
+ &decoded.rgb,
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ crop,
+ )?;
+ append_imagenet_tensor(resized, output);
+ Ok(())
+ }
}
fn relative_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<PixelCrop> {
@@ -105,43 +99,74 @@ fn relative_crop(decoded: &DecodedImage, box_xyxy: &[f32; 4]) -> MlResult<PixelC
})
}
-/// 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(),
- ));
+/// Resizes row-strided crop views while retaining FIR's internal workspace.
+pub(super) struct RgbCropResizer {
+ resizer: Resizer,
+ resized: FirImage<'static>,
+ options: ResizeOptions,
+}
+
+impl RgbCropResizer {
+ pub(super) fn new(output_size: u32) -> Self {
+ Self {
+ resizer: Resizer::new(),
+ resized: FirImage::new(output_size, output_size, PixelType::U8x3),
+ options: ResizeOptions::new()
+ .resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear)),
+ }
}
- 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(),
- ));
+
+ pub(super) fn resize(
+ &mut self,
+ rgb: &[u8],
+ source_width: u32,
+ source_height: u32,
+ crop: PixelCrop,
+ ) -> MlResult<&[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(),
+ ));
+ }
+
+ 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}")))?;
+ self.resizer
+ .resize(&source, &mut self.resized, Some(&self.options))
+ .map_err(|e| MlError::Preprocess(format!("failed to resize RGB crop: {e}")))?;
+
+ Ok(self.resized.buffer())
}
+}
- 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())
+pub(super) fn append_imagenet_tensor(resized: &[u8], output: &mut Vec<f32>) {
+ let pixel_count = PET_EMBED_INPUT_SIZE * PET_EMBED_INPUT_SIZE;
+ let start = output.len();
+ output.resize(start + 3 * pixel_count, 0.0);
+ let tensor = &mut output[start..];
+
+ for index in 0..pixel_count {
+ let source = index * 3;
+ tensor[index] = (resized[source] as f32 / 255.0 - IMAGENET_MEAN[0]) / IMAGENET_STD[0];
+ tensor[pixel_count + index] =
+ (resized[source + 1] as f32 / 255.0 - IMAGENET_MEAN[1]) / IMAGENET_STD[1];
+ tensor[2 * pixel_count + index] =
+ (resized[source + 2] as f32 / 255.0 - IMAGENET_MEAN[2]) / IMAGENET_STD[2];
+ }
}
#[cfg(test)]
mod tests {
- use super::{PixelCrop, resize_rgb_crop};
+ use super::{PixelCrop, RgbCropResizer};
#[test]
fn cropped_view_resize_matches_a_materialized_crop() {
@@ -157,7 +182,10 @@ mod tests {
height: 3,
};
- let direct = resize_rgb_crop(&rgb, width, height, crop, 7).unwrap();
+ let direct = RgbCropResizer::new(7)
+ .resize(&rgb, width, height, crop)
+ .unwrap()
+ .to_vec();
let mut materialized = Vec::new();
for row in crop.y..crop.y + crop.height {
@@ -165,19 +193,20 @@ mod tests {
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();
+ let baseline = RgbCropResizer::new(7)
+ .resize(
+ &materialized,
+ crop.width,
+ crop.height,
+ PixelCrop {
+ x: 0,
+ y: 0,
+ width: crop.width,
+ height: crop.height,
+ },
+ )
+ .unwrap()
+ .to_vec();
assert_eq!(direct, baseline);
}