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
extern crate libc;
extern crate image;
extern crate rayon;
#[macro_use] extern crate itertools;
use std::ptr;
use std::fs::File;
use std::path::Path;
use std::ffi::{CStr, OsStr};
use std::{slice, str, mem};
use rayon::prelude::*;
use libc::{size_t, c_char, c_uchar};
use image::{GenericImage, ImageBuffer, imageops, FilterType, ColorType, ImageDecoder};
mod lazy_load;
#[repr(C)]
#[derive(Clone)]
pub struct Crop {
pub path: *const c_char,
pub crop: *const f32
}
#[repr(C)]
#[derive(Clone)]
pub struct Array {
data: *const libc::c_void,
len: libc::size_t,
}
unsafe impl Send for Array {}
impl Array {
fn from_vec<T>(mut v: Vec<T>) -> Array {
v.shrink_to_fit();
let a = Array {
data: v.as_ptr() as *const libc::c_void,
len: v.len(),
};
mem::forget(v);
a
}
fn into_vec(self) -> Vec<u8> {
unsafe { Vec::from_raw_parts(self.data as *mut u8, self.len, self.len) }
}
}
fn scale_range(val: f32, newmin: f32, newmax: f32) -> f32 {
(((val) * (newmax - newmin)) / (1.0)) + newmin
}
#[no_mangle]
pub fn lazy_crop_and_resize(path: &str, scale: f32, x_crop: f32, y_crop: f32,
max_img_percent: f32, resize_width: u32, resize_height: u32) -> image::DynamicImage
{
assert!(x_crop >= 0f32 && x_crop <= 1f32, "x of crop not bounded in [0, 1]");
assert!(y_crop >= 0f32 && y_crop <= 1f32, "y of crop not bounded in [0, 1]");
let img_size = lazy_load::dimensions(path).unwrap();
let mut x = scale_range(x_crop, 0f32, img_size.0 as f32) as u32;
let mut y = scale_range(y_crop, 0f32, img_size.1 as f32) as u32;
let crop_scale = scale.min(max_img_percent);
let crop_size = ((img_size.0 as f32 * crop_scale).floor().max(2.0) as u32,
(img_size.1 as f32 * crop_scale).floor().max(2.0) as u32);
let max_coords = (img_size.0 - crop_size.0,
img_size.1 - crop_size.1);
x = x.min(max_coords.0);
y = y.min(max_coords.1);
lazy_load::lazy_crop_to_image(path, x, y, crop_size.0, crop_size.1).unwrap().resize_exact(
resize_width, resize_height, FilterType::Nearest
)
}
#[no_mangle]
pub fn crop_and_resize(path: &str, scale: f32, x_crop: f32, y_crop: f32,
max_img_percent: f32, resize_width: u32, resize_height: u32) -> image::DynamicImage
{
assert!(x_crop >= 0f32 && x_crop <= 1f32, "x of crop not bounded in [0, 1]");
assert!(y_crop >= 0f32 && y_crop <= 1f32, "y of crop not bounded in [0, 1]");
let mut img = image::open(&Path::new(&path)).unwrap();
let img_size = img.dimensions();
let mut x = scale_range(x_crop, 0f32, img_size.0 as f32) as u32;
let mut y = scale_range(y_crop, 0f32, img_size.1 as f32) as u32;
let crop_scale = scale.min(max_img_percent);
let crop_size = ((img_size.0 as f32 * crop_scale).floor().max(2.0) as u32,
(img_size.1 as f32 * crop_scale).floor().max(2.0) as u32);
let max_coords = (img_size.0 - crop_size.0,
img_size.1 - crop_size.1);
x = x.min(max_coords.0);
y = y.min(max_coords.1);
img.crop(x, y, crop_size.0, crop_size.1).resize_exact(
resize_width, resize_height, FilterType::Nearest
)
}
#[no_mangle]
pub extern "C" fn parallel_crop_and_resize(image_paths_ptr: *const *const c_char,
return_ptr: *mut u8,
scale_ptr: *const f32,
x_ptr: *const f32,
y_ptr: *const f32,
window_size: u32,
chans: u32,
max_img_percent: f32,
length: size_t)
{
assert!(!scale_ptr.is_null(), "can't operate over null scale vector");
assert!(!x_ptr.is_null(), "can't operate over null x vector");
assert!(!y_ptr.is_null(), "can't operate over null y vector");
assert!(!return_ptr.is_null(), "can't operate over null result vector");
assert!(!image_paths_ptr.is_null(), "can't operate over null list of image paths");
let image_paths_vec: Vec<&str> = unsafe { slice::from_raw_parts(image_paths_ptr, length as usize) }.iter()
.map(|&p| unsafe { CStr::from_ptr(p) })
.map(|cs| cs.to_bytes())
.map(|bs| str::from_utf8(bs).unwrap())
.collect();
let scale_values = unsafe { slice::from_raw_parts(scale_ptr, length as usize) };
let x_values = unsafe { slice::from_raw_parts(x_ptr, length as usize) };
let y_values = unsafe { slice::from_raw_parts(y_ptr, length as usize) };
let mut resultant_vec = vec![];
image_paths_vec.into_par_iter().zip(scale_values)
.zip(x_values.par_iter()).zip(y_values)
.map(|(((path, scale), x), y)| {
Array::from_vec(crop_and_resize(path,
*scale, *x, *y,
max_img_percent,
window_size,
window_size).raw_pixels()
)
}).collect_into_vec(&mut resultant_vec);
let win_size = (window_size * window_size * chans) as usize;
for (begin, rvec) in izip!((0..length*win_size).step_by(win_size), resultant_vec)
{
assert!(rvec.len == win_size, "rvec [{:?}] != window_size [{:?}]", rvec.len, win_size);
unsafe { ptr::copy(rvec.data as *const u8, return_ptr.offset(begin as isize),
win_size) };
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bw_image_crop() {
let center = crop_and_resize("assets/lena_gray.png",
0.25, 0.5, 0.5, 0.25, 32, 32);
println!("dims: {:?}", center.dimensions());
center.save(&Path::new("assets/test_lena_gray_center.png")).unwrap();
assert!(center.dimensions() == (32, 32));
let is_color = match center.color() {
ColorType::Gray(_) => false,
_ => true
};
assert!(is_color == false);
}
#[test]
fn test_image_crops() {
let top_left = crop_and_resize("assets/lena.png",
0.25, 0.25, 0.25, 0.25, 32, 32);
println!("dims: {:?}", top_left.dimensions());
top_left.save(&Path::new("assets/test_lena_top_left.png")).unwrap();
assert!(top_left.dimensions() == (32, 32), "top left was {:?}", top_left.dimensions());
let top_right = crop_and_resize("assets/lena.png",
0.25, 0.75, 0.25, 0.25, 32, 32);
top_right.save(&Path::new("assets/test_lena_top_right.png")).unwrap();
assert!(top_right.dimensions() == (32, 32), "top right was {:?}", top_right.dimensions());
let bottom_left = crop_and_resize("assets/lena.png",
0.25, 0.25, 0.75, 0.25, 32, 32);
bottom_left.save(&Path::new("assets/test_lena_bottom_left.png")).unwrap();
assert!(bottom_left.dimensions() == (32, 32), "bottom left was {:?}", bottom_left.dimensions());
let bottom_right = crop_and_resize("assets/lena.png",
0.25, 0.75, 0.75, 0.25, 32, 32);
bottom_right.save(&Path::new("assets/test_lena_bottom_right.png")).unwrap();
assert!(bottom_right.dimensions() == (32, 32), "bottom right was {:?}", bottom_right.dimensions());
let center = crop_and_resize("assets/lena.png",
0.25, 0.5, 0.5, 0.25, 32, 32);
center.save(&Path::new("assets/test_lena_center.png")).unwrap();
assert!(center.dimensions() == (32, 32), "center right was {:?}", center.dimensions());
}
}