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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use std::io::{Error, ErrorKind, Read};
use image::{GenericImageView, Luma};
use nalgebra::{Point2, Similarity2, Translation2, Vector2};
use rand::distributions::Uniform;
use rand::{Rng, RngCore};
use super::bintest::ImageBintest;
use super::geometry::ISimilarity2;
use super::node::ComparisonNode;
use super::utils::odd_median_mut;
type Tree = Vec<ComparisonNode>;
type Predictions = Vec<Vector2<f32>>;
type Stage = Vec<(Tree, Predictions)>;
type Stages = Vec<Stage>;
pub struct Localizer {
    depth: usize,
    dsize: usize,
    scale: f32,
    stages: Stages,
    distrs: (Uniform<f32>, Uniform<f32>),
}
impl Localizer {
    
    
    
    
    
    
    
    
    
    pub fn localize<I>(&self, image: &I, mut roi: Similarity2<f32>) -> Point2<f32>
    where
        I: GenericImageView<Pixel = Luma<u8>>,
    {
        let scaling = roi.scaling();
        for stage in self.stages.iter() {
            let mut translation = Translation2::identity();
            let roi_i32 = ISimilarity2::from(roi);
            for (codes, preds) in stage.iter() {
                let idx = (0..self.depth).fold(0, |idx, _| {
                    2 * idx + 1 + codes[idx].bintest(image, &roi_i32) as usize
                });
                let lutidx = (idx + 1) - self.dsize;
                translation.vector += preds[lutidx];
            }
            translation.vector.scale_mut(scaling);
            roi.append_translation_mut(&translation);
            roi.prepend_scaling_mut(self.scale);
        }
        Point2::from(roi.isometry.translation.vector)
    }
    
    
    
    
    
    
    
    
    
    
    
    pub fn perturb_localize<I>(
        &self,
        image: &I,
        initial_roi: Similarity2<f32>,
        mut rng: impl RngCore,
        nperturbs: usize,
    ) -> Point2<f32>
    where
        I: GenericImageView<Pixel = Luma<u8>>,
    {
        let mut xs: Vec<f32> = Vec::with_capacity(nperturbs);
        let mut ys: Vec<f32> = Vec::with_capacity(nperturbs);
        let scaling = initial_roi.scaling();
        
        for _ in 0..nperturbs {
            let mut roi = initial_roi.clone();
            roi.prepend_scaling_mut(rng.sample(self.distrs.0));
            roi.isometry.translation.vector.x = scaling.mul_add(
                rng.sample(self.distrs.1),
                initial_roi.isometry.translation.vector.x,
            );
            roi.isometry.translation.vector.y = scaling.mul_add(
                rng.sample(self.distrs.1),
                initial_roi.isometry.translation.vector.y,
            );
            
            let result = self.localize(image, roi);
            xs.push(result.x);
            ys.push(result.y);
        }
        Point2::new(odd_median_mut(&mut xs), odd_median_mut(&mut ys))
    }
    
    pub fn from_readable(mut readable: impl Read) -> Result<Self, Error> {
        let mut buffer: [u8; 4] = [0u8; 4];
        readable.read_exact(&mut buffer)?;
        let nstages = i32::from_le_bytes(buffer) as usize;
        readable.read_exact(&mut buffer)?;
        let scale = f32::from_le_bytes(buffer);
        readable.read_exact(&mut buffer)?;
        let ntrees = i32::from_le_bytes(buffer) as usize;
        readable.read_exact(&mut buffer)?;
        let depth = i32::from_le_bytes(buffer) as usize;
        let pred_size: usize = match 2usize.checked_pow(depth as u32) {
            Some(value) => value,
            None => return Err(Error::new(ErrorKind::Other, "depth overflow")),
        };
        let code_size = pred_size - 1;
        let mut stages: Stages = Vec::with_capacity(nstages);
        for _ in 0..nstages {
            let mut stage: Stage = Vec::with_capacity(ntrees);
            for _ in 0..ntrees {
                let mut tree: Tree = Vec::with_capacity(code_size);
                let mut predictions: Predictions = Vec::with_capacity(pred_size);
                for _ in 0..code_size {
                    readable.read_exact(&mut buffer)?;
                    let node = ComparisonNode::from(buffer);
                    tree.push(node);
                }
                for _ in 0..pred_size {
                    readable.read_exact(&mut buffer)?;
                    let y = f32::from_le_bytes(buffer);
                    readable.read_exact(&mut buffer)?;
                    let x = f32::from_le_bytes(buffer);
                    predictions.push(Vector2::new(x, y));
                }
                stage.push((tree, predictions));
            }
            stages.push(stage);
        }
        Ok(Self {
            depth,
            dsize: pred_size,
            scale,
            stages,
            distrs: (Uniform::new(0.925, 0.94), Uniform::new(-0.075, 0.075)),
        })
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn check_pupil_localizer_model_parsing() {
        let puploc =
            Localizer::from_readable(include_bytes!("../models/puploc.bin").to_vec().as_slice())
                .expect("parsing failed");
        let stages = &puploc.stages;
        let trees = stages[0].len();
        assert_eq!(5, stages.len());
        assert_eq!(20, trees);
        assert_eq!(10, puploc.depth);
        assert_eq!(80, (puploc.scale * 100.0) as u32);
        let dsize = 2usize.pow(puploc.depth as u32);
        let first_node = ComparisonNode::from([30i8, -16i8, 125i8, 14i8]);
        let last_node = ComparisonNode::from([-125i8, 26i8, 15i8, 98i8]);
        assert_eq!(first_node, stages[0][0].0[0]);
        assert_eq!(
            last_node,
            stages[stages.len() - 1][trees - 1].0[dsize - 1 - 1]
        );
        let first_pred_test = Vector2::new(-0.08540829f32, 0.04436668f32);
        let last_pred_test = Vector2::new(0.05820565f32, 0.02249731f32);
        let first_pred = stages[0][0].1[0];
        let last_pred = stages[stages.len() - 1][trees - 1].1[dsize - 1];
        assert_abs_diff_eq!(first_pred_test, first_pred);
        assert_abs_diff_eq!(last_pred_test, last_pred);
    }
}