-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathimage_pipeline.rs
More file actions
69 lines (61 loc) · 2.53 KB
/
Copy pathimage_pipeline.rs
File metadata and controls
69 lines (61 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//! Example: Image preprocessing pipeline with transforms.
//!
//! Demonstrates:
//! 1. Creating a Compose pipeline with Resize, Normalize, and ScaleValues
//! 2. Applying the pipeline to a dummy image tensor
//! 3. Wrapping a model in an InferencePipeline with pre/postprocessing
//! 4. Running end-to-end inference
//!
//! Usage: cargo run --example image_pipeline
use yscv_autograd::Graph;
use yscv_model::{
Compose, InferencePipeline, Normalize, Resize, ScaleValues, SequentialModel, Transform,
};
use yscv_tensor::Tensor;
fn main() {
// Step 1: Build a preprocessing pipeline.
// Resize to 4x4, scale pixel values by 1/255, then channel-normalize.
let preprocess = Compose::new()
.add(Resize::new(4, 4))
.add(ScaleValues::new(1.0 / 255.0))
.add(Normalize::new(
vec![0.485, 0.456, 0.406],
vec![0.229, 0.224, 0.225],
));
// Step 2: Create a dummy 8x8 RGB image (values in [0, 255]).
let h = 8;
let w = 8;
let c = 3;
let data: Vec<f32> = (0..(h * w * c)).map(|i| (i % 256) as f32).collect();
let image = Tensor::from_vec(vec![h, w, c], data).expect("image tensor");
println!("Input image shape: {:?}", image.shape());
// Step 3: Apply the preprocessing pipeline.
let preprocessed = preprocess.apply(&image).expect("preprocessing failed");
println!("Preprocessed shape: {:?}", preprocessed.shape());
println!(
"First 6 values: [{:.4}, {:.4}, {:.4}, {:.4}, {:.4}, {:.4}]",
preprocessed.data()[0],
preprocessed.data()[1],
preprocessed.data()[2],
preprocessed.data()[3],
preprocessed.data()[4],
preprocessed.data()[5],
);
// Step 4: Build a simple model and wrap in InferencePipeline.
let graph = Graph::new();
let mut model = SequentialModel::new(&graph);
// A minimal model: just flatten + identity-like pass-through.
model.add_flatten();
model.add_relu();
let pipeline = InferencePipeline::new(model).with_preprocess(move |input| {
// Apply the same Compose transform chain
let resized = Resize::new(4, 4).apply(input)?;
let scaled = ScaleValues::new(1.0 / 255.0).apply(&resized)?;
Normalize::new(vec![0.485, 0.456, 0.406], vec![0.229, 0.224, 0.225]).apply(&scaled)
});
// Step 5: Run the full pipeline.
let output = pipeline.run(&image).expect("pipeline inference failed");
println!("\nInferencePipeline output shape: {:?}", output.shape());
println!("Output length: {}", output.data().len());
println!("\nDone!");
}