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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Bounding box based image cropping utilities.
use crate::core::OCRError;
use crate::processors::BoundingBox;
use crate::utils::transform::get_rotate_crop_image;
use image::{RgbImage, imageops};
/// Bounding box based image cropping utilities.
pub struct BBoxCrop;
impl BBoxCrop {
/// Crops an image based on a bounding box.
///
/// This function calculates the bounding rectangle of a polygonal bounding box
/// and crops the image to that region. It handles edge cases like empty bounding
/// boxes and ensures the crop region is within the image boundaries.
///
/// # Arguments
///
/// * `image` - The source image
/// * `bbox` - The bounding box defining the crop region
///
/// # Returns
///
/// A Result containing the cropped image or an OCRError
pub fn crop_bounding_box(image: &RgbImage, bbox: &BoundingBox) -> Result<RgbImage, OCRError> {
// Check if the bounding box is empty
if bbox.points.is_empty() {
return Err(OCRError::image_processing_error("Empty bounding box"));
}
// Calculate the bounding rectangle of the polygon
let min_x = bbox
.points
.iter()
.map(|p| p.x)
.fold(f32::INFINITY, f32::min)
.max(0.0);
let max_x = bbox
.points
.iter()
.map(|p| p.x)
.fold(f32::NEG_INFINITY, f32::max);
let min_y = bbox
.points
.iter()
.map(|p| p.y)
.fold(f32::INFINITY, f32::min)
.max(0.0);
let max_y = bbox
.points
.iter()
.map(|p| p.y)
.fold(f32::NEG_INFINITY, f32::max);
// Convert to integer coordinates, ensuring they're within image bounds
let x1 = (min_x as u32).min(image.width().saturating_sub(1));
let y1 = (min_y as u32).min(image.height().saturating_sub(1));
let x2 = (max_x as u32).min(image.width());
let y2 = (max_y as u32).min(image.height());
// Validate the crop region
if x2 <= x1 || y2 <= y1 {
return Err(OCRError::image_processing_error(format!(
"Invalid crop region: ({x1}, {y1}) to ({x2}, {y2})"
)));
}
let coords = (x1, y1, x2, y2);
Ok(Self::slice_rgb_image(image, coords))
}
/// Slices an RGB image based on coordinates.
///
/// This function creates a new image by copying pixels from a rectangular
/// region of the source image. It performs bounds checking to ensure
/// that only valid pixels are copied.
///
/// # Arguments
///
/// * `img` - The source image
/// * `coords` - The coordinates as (x1, y1, x2, y2)
///
/// # Returns
///
/// The sliced image
fn slice_rgb_image(img: &RgbImage, coords: (u32, u32, u32, u32)) -> RgbImage {
let (x1, y1, x2, y2) = coords;
let width = x2 - x1;
let height = y2 - y1;
// Use library-provided immutable crop (zero-copy view) and then materialize
imageops::crop_imm(img, x1, y1, width, height).to_image()
}
/// Crops multiple bounding boxes from the same source image.
///
/// Processes all bounding boxes for batch cropping operations, such as extracting
/// multiple text regions from a document image.
///
/// # Arguments
///
/// * `image` - The source image
/// * `bboxes` - A slice of bounding boxes to crop
///
/// # Returns
///
/// A vector of Results, each containing either a cropped image or an OCRError.
/// The order corresponds to the input bounding boxes.
pub fn batch_crop_bounding_boxes(
image: &RgbImage,
bboxes: &[BoundingBox],
) -> Vec<Result<RgbImage, OCRError>> {
bboxes
.iter()
.map(|bbox| Self::crop_bounding_box(image, bbox))
.collect()
}
/// Crops multiple rotated bounding boxes from the same source image.
///
/// Processes batch cropping operations with perspective correction.
///
/// # Arguments
///
/// * `image` - The source image
/// * `bboxes` - A slice of bounding boxes to crop with rotation
///
/// # Returns
///
/// A vector of Results, each containing either a cropped image or an OCRError.
/// The order corresponds to the input bounding boxes.
pub fn batch_crop_rotated_bounding_boxes(
image: &RgbImage,
bboxes: &[BoundingBox],
) -> Vec<Result<RgbImage, OCRError>> {
bboxes
.iter()
.map(|bbox| Self::crop_rotated_bounding_box(image, bbox))
.collect()
}
/// Crops and rectifies an image region using rotated crop with perspective transformation.
///
/// This function implements the same functionality as OpenCV's GetRotateCropImage.
/// It takes a bounding box (quadrilateral) and applies perspective transformation
/// to rectify it into a rectangular image. This is particularly useful for text
/// regions that may be rotated or have perspective distortion.
///
/// # Arguments
///
/// * `image` - The source image
/// * `bbox` - The bounding box defining the quadrilateral region
///
/// # Returns
///
/// A Result containing the rotated and cropped image or an OCRError
pub fn crop_rotated_bounding_box(
image: &RgbImage,
bbox: &BoundingBox,
) -> Result<RgbImage, OCRError> {
// Check if the bounding box has exactly 4 points
if bbox.points.len() != 4 {
return Err(OCRError::image_processing_error(format!(
"Bounding box must have exactly 4 points, got {}",
bbox.points.len()
)));
}
let box_points = bbox.points.clone();
// Fast path: if the quadrilateral is axis-aligned rectangle, use simple crop
if let [p0, p1, p2, p3] = &box_points[..] {
let is_axis_aligned = (p0.y == p1.y && p2.y == p3.y && p0.x == p3.x && p1.x == p2.x)
|| (p0.x == p1.x && p2.x == p3.x && p0.y == p3.y && p1.y == p2.y);
if is_axis_aligned {
let min_x = p0.x.min(p1.x).min(p2.x).min(p3.x).max(0.0) as u32;
let min_y = p0.y.min(p1.y).min(p2.y).min(p3.y).max(0.0) as u32;
let max_x = p0.x.max(p1.x).max(p2.x).max(p3.x).min(image.width() as f32) as u32;
let max_y =
p0.y.max(p1.y)
.max(p2.y)
.max(p3.y)
.min(image.height() as f32) as u32;
if max_x > min_x && max_y > min_y {
use image::imageops;
let w = max_x - min_x;
let h = max_y - min_y;
return Ok(imageops::crop_imm(image, min_x, min_y, w, h).to_image());
}
}
}
// Apply rotated crop transformation
get_rotate_crop_image(image, &box_points)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::processors::Point;
use image::{ImageBuffer, Rgb};
fn create_test_image(width: u32, height: u32) -> RgbImage {
let mut img = ImageBuffer::new(width, height);
for y in 0..height {
for x in 0..width {
// Create a pattern for testing
let r = (x * 255 / width.max(1)) as u8;
let g = (y * 255 / height.max(1)) as u8;
let b = 128;
img.put_pixel(x, y, Rgb([r, g, b]));
}
}
img
}
#[test]
fn test_crop_bounding_box_valid_rectangle() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![
Point { x: 10.0, y: 10.0 },
Point { x: 50.0, y: 10.0 },
Point { x: 50.0, y: 40.0 },
Point { x: 10.0, y: 40.0 },
],
};
let result = BBoxCrop::crop_bounding_box(&img, &bbox);
assert!(result.is_ok());
let cropped = match result {
Ok(cropped) => cropped,
Err(err) => panic!("expected crop to succeed: {err}"),
};
assert_eq!(cropped.width(), 40); // 50 - 10
assert_eq!(cropped.height(), 30); // 40 - 10
}
#[test]
fn test_crop_bounding_box_empty_points() {
let img = create_test_image(100, 100);
let bbox = BoundingBox { points: vec![] };
let result = BBoxCrop::crop_bounding_box(&img, &bbox);
assert!(result.is_err());
let error_msg = result.unwrap_err().to_string();
assert!(error_msg.contains("Empty bounding box"));
}
#[test]
fn test_crop_bounding_box_single_point() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![Point { x: 50.0, y: 50.0 }],
};
let result = BBoxCrop::crop_bounding_box(&img, &bbox);
assert!(result.is_err());
let error_msg = result.unwrap_err().to_string();
assert!(error_msg.contains("Invalid crop region"));
}
#[test]
fn test_crop_bounding_box_negative_coordinates() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![
Point { x: -10.0, y: -5.0 },
Point { x: 30.0, y: -5.0 },
Point { x: 30.0, y: 25.0 },
Point { x: -10.0, y: 25.0 },
],
};
let result = BBoxCrop::crop_bounding_box(&img, &bbox);
assert!(result.is_ok());
let cropped = match result {
Ok(cropped) => cropped,
Err(err) => panic!("expected crop to succeed: {err}"),
};
// Should clamp negative coordinates to 0
assert_eq!(cropped.width(), 30); // 30 - 0 (clamped from -10)
assert_eq!(cropped.height(), 25); // 25 - 0 (clamped from -5)
}
#[test]
fn test_crop_bounding_box_out_of_bounds() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![
Point { x: 80.0, y: 80.0 },
Point { x: 150.0, y: 80.0 }, // Beyond image width
Point { x: 150.0, y: 120.0 }, // Beyond image height
Point { x: 80.0, y: 120.0 },
],
};
let result = BBoxCrop::crop_bounding_box(&img, &bbox);
assert!(result.is_ok());
let cropped = match result {
Ok(cropped) => cropped,
Err(err) => panic!("expected crop to succeed: {err}"),
};
// Should clamp to image boundaries
assert_eq!(cropped.width(), 20); // 100 - 80
assert_eq!(cropped.height(), 20); // 100 - 80
}
#[test]
fn test_crop_bounding_box_irregular_polygon() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![
Point { x: 20.0, y: 30.0 },
Point { x: 60.0, y: 10.0 },
Point { x: 80.0, y: 50.0 },
Point { x: 40.0, y: 70.0 },
Point { x: 10.0, y: 40.0 },
],
};
let result = BBoxCrop::crop_bounding_box(&img, &bbox);
assert!(result.is_ok());
let cropped = match result {
Ok(cropped) => cropped,
Err(err) => panic!("expected crop to succeed: {err}"),
};
// Should use bounding rectangle of the polygon
assert_eq!(cropped.width(), 70); // 80 - 10
assert_eq!(cropped.height(), 60); // 70 - 10
}
#[test]
fn test_crop_rotated_bounding_box_valid() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![
Point { x: 20.0, y: 20.0 },
Point { x: 60.0, y: 20.0 },
Point { x: 60.0, y: 40.0 },
Point { x: 20.0, y: 40.0 },
],
};
let result = BBoxCrop::crop_rotated_bounding_box(&img, &bbox);
assert!(result.is_ok());
let cropped = match result {
Ok(cropped) => cropped,
Err(err) => panic!("expected crop to succeed: {err}"),
};
assert!(cropped.width() > 0);
assert!(cropped.height() > 0);
}
#[test]
fn test_crop_rotated_bounding_box_wrong_point_count() {
let img = create_test_image(100, 100);
let bbox = BoundingBox {
points: vec![
Point { x: 20.0, y: 20.0 },
Point { x: 60.0, y: 20.0 },
Point { x: 60.0, y: 40.0 },
], // Only 3 points instead of 4
};
let result = BBoxCrop::crop_rotated_bounding_box(&img, &bbox);
assert!(result.is_err());
let error_msg = result.unwrap_err().to_string();
assert!(error_msg.contains("must have exactly 4 points"));
}
#[test]
fn test_crop_rotated_bounding_box_axis_aligned_fast_path() {
let img = create_test_image(100, 100);
// Define an axis-aligned rectangle with 4 points
let bbox = BoundingBox {
points: vec![
Point { x: 10.0, y: 20.0 },
Point { x: 60.0, y: 20.0 },
Point { x: 60.0, y: 50.0 },
Point { x: 10.0, y: 50.0 },
],
};
let cropped_fast = match BBoxCrop::crop_rotated_bounding_box(&img, &bbox) {
Ok(cropped_fast) => cropped_fast,
Err(err) => panic!("expected rotated crop to succeed: {err}"),
};
// Expected via simple crop
let expected = imageops::crop_imm(&img, 10, 20, 50, 30).to_image();
assert_eq!(cropped_fast.dimensions(), expected.dimensions());
// Sample a couple of pixels to ensure identical content
assert_eq!(cropped_fast.get_pixel(0, 0), expected.get_pixel(0, 0));
assert_eq!(cropped_fast.get_pixel(49, 29), expected.get_pixel(49, 29));
}
#[test]
fn test_slice_rgb_image() {
let img = create_test_image(100, 100);
let coords = (10, 20, 50, 60);
let sliced = BBoxCrop::slice_rgb_image(&img, coords);
assert_eq!(sliced.width(), 40); // 50 - 10
assert_eq!(sliced.height(), 40); // 60 - 20
// Check that the pixel values are correctly copied
let original_pixel = img.get_pixel(10, 20);
let sliced_pixel = sliced.get_pixel(0, 0);
assert_eq!(original_pixel, sliced_pixel);
}
}