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
use opencv::core::{
no_array, normalize, Mat, Point, Size, BORDER_DEFAULT, CV_8U, CV_8UC3, NORM_MINMAX,
};
use std::path::Path;
use std::sync::mpsc::{channel, Receiver, Sender};
use crate::raw::raw_stream::RawStream;
use crate::transcoder::event_pixel::pixel::EventPixel;
use crate::transcoder::event_pixel::{DeltaT, PixelAddress};
use crate::{Codec, Event};
use opencv::imgproc::{bounding_rect, contour_area, rectangle, resize, RETR_EXTERNAL};
use opencv::{highgui, prelude::*};
use crate::transcoder::d_controller::DecimationMode;
use crate::SourceCamera;
use ndarray::Array3;
use ndarray::Axis;
use rayon::iter::IntoParallelIterator;
use rayon::iter::{IndexedParallelIterator, ParallelIterator};
#[derive(Debug)]
pub enum SourceError {
Open,
BufferEmpty,
BufferChannelClosed,
NoData,
}
pub struct Video {
pub width: u16,
pub height: u16,
pub(crate) event_pixels: Array3<EventPixel>,
pub(crate) ref_time: u32,
pub(crate) delta_t_max: u32,
pub(crate) show_display: bool,
pub(crate) show_live: bool,
pub in_interval_count: u32,
pub(crate) instantaneous_display_frame: Mat,
pub(crate) motion_frame_mat: Mat,
pub(crate) instantaneous_frame: Mat,
pub event_sender: Sender<Vec<Event>>,
pub(crate) write_out: bool,
pub(crate) communicate_events: bool,
pub channels: usize,
pub(crate) stream: RawStream,
}
impl Video {
pub fn new(
width: u16,
height: u16,
output_filename: Option<String>,
channels: usize,
tps: DeltaT,
ref_time: DeltaT,
delta_t_max: DeltaT,
d_mode: DecimationMode,
write_out: bool,
communicate_events: bool,
show_display: bool,
source_camera: SourceCamera,
) -> Video {
if write_out {
assert!(communicate_events);
}
let (event_sender, _event_receiver): (Sender<Vec<Event>>, Receiver<Vec<Event>>) = channel();
let mut stream: RawStream = Codec::new();
match output_filename {
None => {}
Some(name) => {
if write_out {
let path = Path::new(&name);
match stream.open_writer(path) {
Ok(_) => {}
Err(e) => {
panic!("{}", e)
}
};
stream.encode_header(
width,
height,
tps,
ref_time,
delta_t_max,
channels as u8,
1,
source_camera,
);
}
}
}
let mut data = Vec::new();
for y in 0..height {
for x in 0..width {
for c in 0..channels {
let px = EventPixel::new(
y as PixelAddress,
x as PixelAddress,
c as u8,
ref_time,
delta_t_max,
d_mode,
channels.try_into().unwrap(),
);
data.push(px);
}
}
}
let event_pixels: Array3<EventPixel> =
Array3::from_shape_vec((height.into(), width.into(), channels), data).unwrap();
let mut instantaneous_frame = Mat::default();
match channels {
1 => unsafe {
instantaneous_frame
.create_rows_cols(height as i32, width as i32, CV_8U)
.unwrap();
},
_ => unsafe {
instantaneous_frame
.create_rows_cols(height as i32, width as i32, CV_8UC3)
.unwrap();
},
}
let motion_frame_mat = instantaneous_frame.clone();
Video {
width,
height,
event_pixels,
ref_time,
delta_t_max,
show_display,
show_live: false,
in_interval_count: 0,
instantaneous_display_frame: Mat::default(),
motion_frame_mat,
instantaneous_frame,
event_sender,
write_out,
communicate_events,
channels,
stream,
}
}
pub fn inter_d_adjustment(&mut self, instantaneous_frame_prev: &mut Mat) {
let mut instantaneous_frame_difference = Mat::default();
opencv::core::subtract(
&self.instantaneous_frame,
instantaneous_frame_prev,
&mut instantaneous_frame_difference,
&opencv::core::no_array(),
-1,
)
.unwrap();
let mut thresholded = Mat::default();
opencv::imgproc::threshold(
&instantaneous_frame_difference,
&mut thresholded,
10.0 / 255.0,
1.0,
opencv::imgproc::THRESH_BINARY,
)
.unwrap();
let mut contours = opencv::types::VectorOfVectorOfPoint::default();
let mut hierarchy = opencv::core::no_array();
let mut thresholded_u8 = Mat::default();
thresholded
.convert_to(&mut thresholded_u8, opencv::core::CV_8U, 255.0, 0.0)
.unwrap();
show_display("thresh", &thresholded_u8, 1, self);
let dilation_size = 1;
let dilation_element = match opencv::imgproc::get_structuring_element(
opencv::imgproc::MORPH_ELLIPSE,
Size::new(dilation_size * 2 + 1, dilation_size * 2 + 1),
Point::new(dilation_size, dilation_size),
) {
Err(why) => panic!("couldn't get structuring element: {}", why),
Ok(v) => v,
};
let mut thresholded_u8_dilated = Mat::default();
opencv::imgproc::dilate(
&thresholded_u8,
&mut thresholded_u8_dilated,
&dilation_element,
Point::new(-1, -1),
2,
BORDER_DEFAULT,
opencv::core::Scalar::new(255.0, 255.0, 255.0, 255.0),
)
.unwrap();
opencv::imgproc::find_contours_with_hierarchy(
&thresholded_u8_dilated,
&mut contours,
&mut hierarchy,
RETR_EXTERNAL,
opencv::imgproc::CHAIN_APPROX_SIMPLE,
Point::new(0, 0),
)
.unwrap();
let mut roi_image = Mat::zeros(self.height as i32, self.width as i32, CV_8U)
.unwrap()
.to_mat()
.unwrap();
for r in 1..3 {
for i in 0..contours.len() {
let contour = contours.get(i).unwrap();
let area = contour_area(&contour, false).unwrap();
if area > ((self.width as f32 * self.height as f32).sqrt() * 0.2) as f64
&& area < ((self.width as f32 * self.height as f32).sqrt() * 10.0) as f64
{
let rect = bounding_rect(&contour).unwrap();
rectangle(
&mut roi_image,
rect,
opencv::core::Scalar::new(r as f64, r as f64, r as f64, r as f64),
((self.width as f32 * self.height as f32).sqrt() * (1.0 / r as f32) * 0.05)
as i32,
1,
0,
)
.unwrap();
}
}
}
for i in 0..contours.len() {
let contour = contours.get(i).unwrap();
let area = contour_area(&contour, false).unwrap();
if area > ((self.width as f32 * self.height as f32).sqrt() * 0.2) as f64
&& area < ((self.width as f32 * self.height as f32).sqrt() * 10.0) as f64
{
let rect = bounding_rect(&contour).unwrap();
rectangle(
&mut self.instantaneous_display_frame,
rect,
opencv::core::Scalar::new(255.0, 255.0, 255.0, 255.0),
2,
1,
0,
)
.unwrap();
rectangle(
&mut roi_image,
rect,
opencv::core::Scalar::new(6.0, 6.0, 6.0, 6.0),
-1,
1,
0,
)
.unwrap();
}
}
let mut roi_normed = Mat::default();
let scale_factor = self.delta_t_max as f64 / self.ref_time as f64;
normalize(
&roi_image,
&mut roi_normed,
1.0,
scale_factor,
NORM_MINMAX,
-1,
&no_array(),
)
.unwrap();
show_display("roi normed", &roi_normed, 1, self);
let roi_arr = roi_normed.data_bytes().unwrap();
let chunk_rows: usize = 10;
let px_per_chunk: usize = chunk_rows * self.width as usize * self.channels as usize;
self.event_pixels
.axis_chunks_iter_mut(Axis(0), chunk_rows)
.into_par_iter()
.enumerate()
.for_each(|(chunk_idx, mut chunk)| {
for (chunk_px_idx, px) in chunk.iter_mut().enumerate() {
let px_idx = chunk_px_idx + px_per_chunk * chunk_idx;
let factor = &roi_arr[px_idx];
px.d_controller.update_roi_factor(*factor);
}
});
}
pub fn end_write_stream(&mut self) {
self.stream.close_writer();
}
}
pub fn show_display(window_name: &str, mat: &Mat, wait: i32, video: &Video) {
if video.show_display {
let mut tmp = Mat::default();
if mat.rows() != 940 {
let factor = mat.rows() as f32 / 940.0;
resize(
mat,
&mut tmp,
Size {
width: (mat.cols() as f32 / factor) as i32,
height: 940,
},
0.0,
0.0,
0,
)
.unwrap();
highgui::imshow(window_name, &tmp).unwrap();
} else {
highgui::imshow(window_name, mat).unwrap();
}
highgui::wait_key(wait).unwrap();
}
}
pub trait Source {
fn consume(&mut self, view_interval: u32) -> Result<Vec<Vec<Event>>, SourceError>;
fn get_video_mut(&mut self) -> &mut Video;
fn get_video(&self) -> &Video;
}