adk_vision/edit/mod.rs
1//! Image edits: [`EditOp`] and the [`DeterministicEditor`] (spec 3.7 §7.5).
2//!
3//! The deterministic editor crops, resizes, blurs, pixelates, redacts and draws overlays on
4//! the `image` crate, with no model: the same image and operation always give the same
5//! pixels. Coordinates in an operation are source pixels; the editor maps them through the
6//! image's transform chain.
7
8mod draw;
9mod editor;
10pub(crate) mod ops;
11
12use serde::{Deserialize, Serialize};
13
14pub use editor::DeterministicEditor;
15
16use crate::error::{Result, VisionError};
17use crate::geometry::{BBox, Mask, Polygon, TransformChain};
18use crate::media::DecodedImage;
19
20/// An RGBA colour.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(transparent)]
23pub struct Rgba(pub [u8; 4]);
24
25impl Rgba {
26 /// Opaque black, the fill for redaction.
27 pub const BLACK: Self = Self([0, 0, 0, 255]);
28 /// Opaque white.
29 pub const WHITE: Self = Self([255, 255, 255, 255]);
30 /// Opaque red.
31 pub const RED: Self = Self([230, 25, 75, 255]);
32 /// Opaque green.
33 pub const GREEN: Self = Self([60, 180, 75, 255]);
34 /// Opaque blue.
35 pub const BLUE: Self = Self([0, 130, 200, 255]);
36}
37
38/// Something drawn over an image.
39#[non_exhaustive]
40#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase", tag = "kind")]
42pub enum Overlay {
43 /// A box outline.
44 Box {
45 /// The box.
46 bbox: BBox,
47 /// Line colour.
48 color: Rgba,
49 /// Line thickness in pixels.
50 thickness: u32,
51 },
52 /// A polygon outline.
53 Polygon {
54 /// The polygon.
55 polygon: Polygon,
56 /// Line colour.
57 color: Rgba,
58 /// Line thickness in pixels.
59 thickness: u32,
60 },
61 /// A mask tinted over the image; the colour's alpha is the tint's opacity.
62 Mask {
63 /// The mask, at source resolution.
64 mask: Mask,
65 /// Tint colour.
66 color: Rgba,
67 },
68 /// A filled dot.
69 Point {
70 /// `[x, y]`.
71 at: [f32; 2],
72 /// Dot colour.
73 color: Rgba,
74 /// Radius in pixels.
75 radius: u32,
76 },
77 /// A numbered mark for set-of-marks prompting: a filled badge with the number in it.
78 Mark {
79 /// The badge's centre, `[x, y]`.
80 at: [f32; 2],
81 /// The number drawn.
82 number: u32,
83 /// Badge colour; the digits are white.
84 color: Rgba,
85 /// Badge size relative to the base size: the device pixel ratio when the marks are
86 /// drawn on a screenshot of a high-density display, so they look the same size in
87 /// points. 1 when unstated.
88 #[serde(default = "unit_scale", skip_serializing_if = "is_unit_scale")]
89 scale: f32,
90 },
91}
92
93fn unit_scale() -> f32 {
94 1.0
95}
96
97fn is_unit_scale(scale: &f32) -> bool {
98 (*scale - 1.0).abs() < f32::EPSILON
99}
100
101/// One edit, with coordinates in source pixels.
102///
103/// Serialized with an `op` tag; its canonical JSON digest names the operation in
104/// `Provenance::Derived`.
105#[non_exhaustive]
106#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
107#[serde(rename_all = "camelCase", tag = "op")]
108pub enum EditOp {
109 /// Keep the pixels inside `bbox`.
110 Crop {
111 /// The box to keep.
112 bbox: BBox,
113 },
114 /// Scale to `width` × `height`.
115 Resize {
116 /// New width.
117 width: u32,
118 /// New height.
119 height: u32,
120 },
121 /// Fill regions with solid colour: the redaction that cannot be reversed.
122 Redact {
123 /// The regions.
124 regions: Vec<BBox>,
125 /// Fill colour.
126 color: Rgba,
127 },
128 /// Gaussian-blur regions. Not a redaction for text, which blur does not hide reliably.
129 Blur {
130 /// The regions.
131 regions: Vec<BBox>,
132 /// The blur's standard deviation in pixels.
133 sigma: f32,
134 },
135 /// Pixelate regions into square blocks.
136 Pixelate {
137 /// The regions.
138 regions: Vec<BBox>,
139 /// Block size in pixels.
140 block: u32,
141 },
142 /// Draw overlays.
143 Annotate {
144 /// The overlays, drawn in order.
145 overlays: Vec<Overlay>,
146 },
147 /// A generative edit, which only a model-backed editor performs.
148 Generative {
149 /// What to change.
150 prompt: String,
151 },
152}
153
154impl EditOp {
155 /// The operation's identifier: the digest of its canonical JSON form.
156 pub fn digest(&self) -> crate::Digest {
157 crate::Digest::of_json(self)
158 }
159}
160
161/// Applies `op` to `pixels`, whose transform chain from the source is `chain`. The
162/// operation's coordinates are source pixels.
163///
164/// # Errors
165///
166/// [`VisionError::Unsupported`] for a generative edit, [`VisionError::InvalidInput`] for a
167/// crop with no pixels, a resize to zero or a mask that is not at source resolution.
168///
169/// # Example
170///
171/// ```
172/// use adk_vision::{BBox, DecodedImage, EditOp, Rgba, TransformChain, apply_edit};
173///
174/// let image = DecodedImage::filled(10, 10, [255, 255, 255, 255]);
175/// let op = EditOp::Redact { regions: vec![BBox::new(2.0, 2.0, 4.0, 4.0)], color: Rgba::BLACK };
176/// let out = apply_edit(&image, &TransformChain::new(10, 10), &op).unwrap();
177/// assert_eq!(out.pixel(3, 3), [0, 0, 0, 255]);
178/// assert_eq!(out.pixel(5, 5), [255, 255, 255, 255]);
179/// ```
180pub fn apply_edit(
181 pixels: &DecodedImage,
182 chain: &TransformChain,
183 op: &EditOp,
184) -> Result<DecodedImage> {
185 let to_target = |b: &BBox| chain.bbox_to_target(b);
186 match op {
187 EditOp::Crop { bbox } => {
188 let (w, h) = pixels.size();
189 let (x, y, cw, ch) = to_target(bbox).pixel_bounds(w, h);
190 if cw == 0 || ch == 0 {
191 return Err(VisionError::InvalidInput(format!(
192 "crop {bbox:?} leaves no pixels of the {w}x{h} image"
193 )));
194 }
195 Ok(ops::crop(pixels, x, y, cw, ch))
196 }
197 EditOp::Resize { width, height } => {
198 if *width == 0 || *height == 0 {
199 return Err(VisionError::InvalidInput(format!(
200 "resize to {width}x{height} leaves no pixels"
201 )));
202 }
203 Ok(ops::resize(pixels, *width, *height))
204 }
205 EditOp::Redact { regions, color } => {
206 let mut out = pixels.clone();
207 for region in regions {
208 ops::fill(&mut out, &to_target(region), *color);
209 }
210 Ok(out)
211 }
212 EditOp::Blur { regions, sigma } => {
213 let mut out = pixels.clone();
214 for region in regions {
215 ops::blur(&mut out, &to_target(region), *sigma);
216 }
217 Ok(out)
218 }
219 EditOp::Pixelate { regions, block } => {
220 let mut out = pixels.clone();
221 for region in regions {
222 ops::pixelate(&mut out, &to_target(region), (*block).max(1));
223 }
224 Ok(out)
225 }
226 EditOp::Annotate { overlays } => {
227 let mut out = pixels.clone();
228 for overlay in overlays {
229 draw::overlay(&mut out, chain, overlay)?;
230 }
231 Ok(out)
232 }
233 EditOp::Generative { .. } => Err(VisionError::Unsupported(
234 "generative edits need a model-backed editor; the deterministic editor crops, \
235 resizes, redacts, blurs, pixelates and annotates"
236 .into(),
237 )),
238 }
239}