Skip to main content

adk_vision/geometry/
frame.rs

1//! [`CoordFrame`]: the coordinate frame a backend answers in.
2
3use serde::{Deserialize, Serialize};
4
5use super::BBox;
6
7/// The order of axes in a provider's raw coordinates.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase")]
10pub enum AxisOrder {
11    /// `[x, y]`, boxes as `[x0, y0, x1, y1]`.
12    Xy,
13    /// `[y, x]`, boxes as `[y0, x0, y1, x1]`: Gemini's `box_2d`.
14    Yx,
15}
16
17/// How a backend fits the sent image into its fixed-size model input.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub enum Letterbox {
21    /// Resized to the input size on each axis; aspect ratio not kept, no padding.
22    Stretch,
23    /// Scaled to fit, keeping the aspect ratio, and centred: padding split evenly, the odd
24    /// pixel on the right and bottom.
25    Center,
26    /// Scaled to fit, keeping the aspect ratio, padded on the right and bottom only.
27    TopLeft,
28}
29
30/// The resize and padding that put a sent image into a model input.
31///
32/// A sent pixel `x` lands at model-input pixel `x * scale_x + pad_left`.
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct LetterboxGeometry {
35    /// Horizontal scale from sent to model-input pixels.
36    pub scale_x: f64,
37    /// Vertical scale from sent to model-input pixels.
38    pub scale_y: f64,
39    /// Padding left of the image, in model-input pixels.
40    pub pad_left: u32,
41    /// Padding above the image, in model-input pixels.
42    pub pad_top: u32,
43    /// The image's size inside the model input, before padding.
44    pub resized: (u32, u32),
45}
46
47impl Letterbox {
48    /// The geometry that puts a `sent` image into an `input` tensor.
49    ///
50    /// The resized size is rounded to whole pixels and the scale follows the rounded size,
51    /// so a backend that prepares its tensor with this geometry and the runtime that undoes
52    /// it agree exactly.
53    ///
54    /// # Example
55    ///
56    /// ```
57    /// use adk_vision::Letterbox;
58    ///
59    /// // A 3024x1964 screenshot into a 640x640 input.
60    /// let g = Letterbox::Center.geometry((3024, 1964), (640, 640));
61    /// assert_eq!(g.resized, (640, 416));
62    /// assert_eq!((g.pad_left, g.pad_top), (0, 112));
63    /// ```
64    pub fn geometry(self, sent: (u32, u32), input: (u32, u32)) -> LetterboxGeometry {
65        let (w, h) = (f64::from(sent.0.max(1)), f64::from(sent.1.max(1)));
66        let (iw, ih) = (f64::from(input.0), f64::from(input.1));
67        match self {
68            Self::Stretch => LetterboxGeometry {
69                scale_x: iw / w,
70                scale_y: ih / h,
71                pad_left: 0,
72                pad_top: 0,
73                resized: input,
74            },
75            Self::Center | Self::TopLeft => {
76                let s = (iw / w).min(ih / h);
77                let rw = ((w * s).round() as u32).clamp(1, input.0.max(1));
78                let rh = ((h * s).round() as u32).clamp(1, input.1.max(1));
79                let (pad_left, pad_top) = if self == Self::Center {
80                    ((input.0 - rw) / 2, (input.1 - rh) / 2)
81                } else {
82                    (0, 0)
83                };
84                LetterboxGeometry {
85                    scale_x: f64::from(rw) / w,
86                    scale_y: f64::from(rh) / h,
87                    pad_left,
88                    pad_top,
89                    resized: (rw, rh),
90                }
91            }
92        }
93    }
94}
95
96/// The coordinate frame a backend answers in. It is part of every answer: each backend
97/// descriptor names its frame, and the runtime maps from it to source pixels.
98///
99/// # Example
100///
101/// ```
102/// use adk_vision::{AxisOrder, CoordFrame};
103///
104/// // Gemini's box_2d: [ymin, xmin, ymax, xmax] on 0-1000, for a 2000x1000 sent image.
105/// let gemini = CoordFrame::Normalized { scale: 1000, order: AxisOrder::Yx };
106/// let b = gemini.box_from_raw([100.0, 250.0, 500.0, 750.0]);
107/// let sent = gemini.bbox_to_sent(&b, (2000, 1000));
108/// assert_eq!((sent.x0, sent.y0, sent.x1, sent.y1), (500.0, 100.0, 1500.0, 500.0));
109/// ```
110#[non_exhaustive]
111#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase", tag = "kind")]
113pub enum CoordFrame {
114    /// Pixels of the image as sent: Meta `sam-3.1`, Claude once the runtime has resized the
115    /// image to its limit, and every local backend once it has undone its own letterbox.
116    SentPixels,
117    /// Numbers on a fixed scale with an axis order: Gemini's `box_2d` is
118    /// `[ymin, xmin, ymax, xmax]` on 0–1000.
119    Normalized {
120        /// The value that stands for the full width or height.
121        scale: u32,
122        /// The provider's axis order.
123        order: AxisOrder,
124    },
125    /// Model-input tensor pixels, with the letterbox that put the sent image there.
126    ModelInput {
127        /// The model input's width.
128        width: u32,
129        /// The model input's height.
130        height: u32,
131        /// How the sent image was fitted into the input.
132        letterbox: Letterbox,
133    },
134}
135
136impl CoordFrame {
137    /// Reads a provider's raw `[a0, b0, a1, b1]` box in this frame's axis order into a box
138    /// with x horizontal. Frames other than [`Normalized`](Self::Normalized) are `Xy`.
139    pub fn box_from_raw(&self, raw: [f32; 4]) -> BBox {
140        match self {
141            Self::Normalized { order: AxisOrder::Yx, .. } => {
142                BBox::new(raw[1], raw[0], raw[3], raw[2])
143            }
144            _ => BBox::new(raw[0], raw[1], raw[2], raw[3]),
145        }
146    }
147
148    /// Reads a provider's raw `[a, b]` point in this frame's axis order.
149    pub fn point_from_raw(&self, raw: [f32; 2]) -> [f32; 2] {
150        match self {
151            Self::Normalized { order: AxisOrder::Yx, .. } => [raw[1], raw[0]],
152            _ => raw,
153        }
154    }
155
156    /// Maps a point from this frame to pixels of a `sent` image.
157    pub fn point_to_sent(&self, point: [f64; 2], sent: (u32, u32)) -> [f64; 2] {
158        let (w, h) = (f64::from(sent.0), f64::from(sent.1));
159        match self {
160            Self::SentPixels => point,
161            Self::Normalized { scale, .. } => {
162                let s = f64::from((*scale).max(1));
163                [point[0] / s * w, point[1] / s * h]
164            }
165            Self::ModelInput { width, height, letterbox } => {
166                let g = letterbox.geometry(sent, (*width, *height));
167                [
168                    (point[0] - f64::from(g.pad_left)) / g.scale_x,
169                    (point[1] - f64::from(g.pad_top)) / g.scale_y,
170                ]
171            }
172        }
173    }
174
175    /// Maps a point from pixels of a `sent` image into this frame: the inverse of
176    /// [`point_to_sent`](Self::point_to_sent), for prompts a backend takes in its own frame.
177    pub fn point_from_sent(&self, point: [f64; 2], sent: (u32, u32)) -> [f64; 2] {
178        let (w, h) = (f64::from(sent.0.max(1)), f64::from(sent.1.max(1)));
179        match self {
180            Self::SentPixels => point,
181            Self::Normalized { scale, .. } => {
182                let s = f64::from((*scale).max(1));
183                [point[0] / w * s, point[1] / h * s]
184            }
185            Self::ModelInput { width, height, letterbox } => {
186                let g = letterbox.geometry(sent, (*width, *height));
187                [
188                    point[0] * g.scale_x + f64::from(g.pad_left),
189                    point[1] * g.scale_y + f64::from(g.pad_top),
190                ]
191            }
192        }
193    }
194
195    /// Maps a box from this frame to pixels of a `sent` image.
196    pub fn bbox_to_sent(&self, bbox: &BBox, sent: (u32, u32)) -> BBox {
197        let a = self.point_to_sent([f64::from(bbox.x0), f64::from(bbox.y0)], sent);
198        let b = self.point_to_sent([f64::from(bbox.x1), f64::from(bbox.y1)], sent);
199        BBox::new(a[0] as f32, a[1] as f32, b[0] as f32, b[1] as f32)
200    }
201
202    /// The size of the raster a mask in this frame must have: the sent image for
203    /// `SentPixels`, `scale` × `scale` cells for `Normalized` (Gemini's masks, one cell per
204    /// unit of its 0–1000 grid), the model input for `ModelInput`.
205    pub fn mask_raster(&self, sent: (u32, u32)) -> Option<(u32, u32)> {
206        match self {
207            Self::SentPixels => Some(sent),
208            Self::Normalized { scale, .. } => Some(((*scale).max(1), (*scale).max(1))),
209            Self::ModelInput { width, height, .. } => Some((*width, *height)),
210        }
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn letterbox_round_trips_points() {
220        for letterbox in [Letterbox::Stretch, Letterbox::Center, Letterbox::TopLeft] {
221            let frame = CoordFrame::ModelInput { width: 640, height: 640, letterbox };
222            let p = [1234.5, 777.25];
223            let model = frame.point_from_sent(p, (3024, 1964));
224            let back = frame.point_to_sent(model, (3024, 1964));
225            assert!((back[0] - p[0]).abs() < 1e-6 && (back[1] - p[1]).abs() < 1e-6);
226        }
227    }
228
229    #[test]
230    fn top_left_letterbox_has_no_leading_padding() {
231        let g = Letterbox::TopLeft.geometry((1000, 500), (640, 640));
232        assert_eq!((g.pad_left, g.pad_top, g.resized), (0, 0, (640, 320)));
233    }
234}