shutter 0.0.1

Image processing data structures and algorithms
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
use nalgebra::*;
use ripple::signal::sampling::{self};
use std::ops::{Index, IndexMut, Mul, Add, AddAssign, MulAssign, SubAssign};
use simba::scalar::SubsetOf;
use std::fmt;
use std::fmt::Debug;

#[cfg(feature="opencvlib")]
use opencv::core;

//#[cfg(feature="mkl")]
// mod fft;

/*#[cfg(feature="mkl")]
pub use fft::*;

#[cfg(feature="gsl")]
pub(crate) mod dwt;

#[cfg(feature="gsl")]
pub use dwt::*;*/

// #[cfg(feature="gsl")]
// mod interp;

// #[cfg(feature="gsl")]
// pub use interp::Interpolation2D;

pub mod pgm;

#[cfg(feature="ipp")]
pub mod ipp;

#[cfg(feature="opencvlib")]
pub mod cvutils;

pub mod index;

pub mod draw;

/// Digital image, represented row-wise. Fundamentally, an image differs from a matrix because
/// it is oriented row-wise in memory, while a matrix is oriented column-wise. Also, images are
/// bounded at a low and high end, because they are the product of a saturated digital quantization
/// process. But indexing, following OpenCV convention, happens from the top-left point, following
/// the matrix convention.
#[derive(Debug, Clone)]
pub struct Image<N> 
where
    N : Scalar
{
    buf : Vec<N>,
    ncols : usize
}

impl<N> Image<N>
where
    N : Scalar + Copy
{

    pub fn new_from_slice(source : &[N], ncols : usize) -> Self {
        let mut buf = Vec::with_capacity(source.len());
        unsafe { buf.set_len(source.len()); }
        buf.copy_from_slice(&source);
        Self{ buf, ncols }
    }

    pub fn from_vec(buf : Vec<N>, ncols : usize) -> Self {
        if buf.len() as f64 % ncols as f64 != 0.0 {
            panic!("Invalid image lenght");
        }
        Self { buf, ncols }
    }

    pub fn new_constant(nrows : usize, ncols : usize, value : N) -> Self {
        let mut buf = Vec::with_capacity(nrows * ncols);
        buf.extend((0..(nrows*ncols)).map(|_| value ));
        Self{ buf, ncols }
    }
    
    pub fn shape(&self) -> (usize, usize) {
        (self.buf.len() / self.ncols, self.ncols)
    }
    
    pub fn width(&self) -> usize {
        self.ncols
    }

    pub fn height(&self) -> usize {
        self.buf.len() / self.ncols
    }

    pub fn full_window<'a>(&'a self) -> Window<'a, N> {
        self.window((0, 0), self.shape()).unwrap()
    }
    
    pub fn full_window_mut<'a>(&'a mut self) -> WindowMut<'a, N> {
        let shape = self.shape();
        self.window_mut((0, 0), shape).unwrap()
    }
    
    pub fn window<'a>(&'a self, offset : (usize, usize), sz : (usize, usize)) -> Option<Window<'a, N>> {
        let orig_sz = self.shape();
        if offset.0 + sz.0 <= orig_sz.0 && offset.1 + sz.1 <= orig_sz.1 {
            Some(Window {
                win : &self.buf[..],
                offset,
                orig_sz,
                win_sz : sz
            })
        } else {
            None
        }
    }
    
    pub fn window_mut<'a>(&'a mut self, offset : (usize, usize), sz : (usize, usize)) -> Option<WindowMut<'a, N>> {
        let orig_sz = self.shape();
        if offset.0 + sz.0 <= orig_sz.0 && offset.1 + sz.1 <= orig_sz.1 {
            Some(WindowMut {
                win : &mut self.buf[..],
                offset,
                orig_sz,
                win_sz : sz
            })
        } else {
            None
        }
    }
    
    pub fn downsample(&mut self, src : &Window<N>) {
        assert!(src.is_full());
        let src_ncols = src.orig_sz.1;
        let dst_ncols = self.ncols;
        
        #[cfg(feature="opencvlib")]
        unsafe {
            cvutils::resize(
                src.win,
                &mut self.buf[..], 
                src_ncols, 
                None,
                dst_ncols,
                None
            );
            return;
        }
        
        #[cfg(feature="ipp")]
        unsafe {
            let dst_nrows = self.buf.len() / self.ncols;
            ipp::resize(src.win, &mut self.buf, src.orig_sz, (dst_nrows, dst_ncols));
        }
        
        panic!("Image::downsample requires that crate is compiled with opencv or ipp feature");

        // TODO use resize::resize for native Rust solution
    }
    
    // TODO call this downsample_convert, and leave alias as a second enum argument:
    // AntiAliasing::On OR AntiAliasing::Off. Disabling antialiasing calls this implementation
    // that just iterates over the second buffer; enabling it calls for more costly operations.
    pub fn downsample_aliased<M>(&mut self, src : &Window<M>) 
    where
        M : Scalar + Copy,
        N : Scalar + From<M>
    {
        let (nrows, ncols) = self.shape();
        let step_rows = src.win_sz.0 / nrows;
        let step_cols = src.win_sz.1 / ncols;
        assert!(step_rows == step_cols);
        sampling::slices::subsample_convert_with_offset(
            src.win,
            src.offset,
            src.win_sz, 
            (nrows, ncols),
            step_rows,
            self.buf.chunks_mut(nrows)
        );
    }
    
    pub fn copy_from(&mut self, other : &Image<N>) {
        self.buf.copy_from_slice(other.buf.as_slice());
    }
    
    pub fn as_slice(&self) -> &[N] {
        &self.buf[..]
    }
    
    pub fn as_mut_slice(&mut self) -> &mut [N] {
        &mut self.buf[..]
    }
    
    /*pub fn convert_from(&mut self, other : &Image<N>) {
        self.buf.as_slice_mut().copy_from(other.buf.as_slice());
    }*/
    
    pub fn windows(&self, sz : (usize, usize)) -> impl Iterator<Item=Window<'_, N>> 
    where
        N : Mul<Output=N> + MulAssign
    {
        self.full_window().windows(sz)
    }
    
    // TODO make this generic like impl AsRef<Window<M>>, and make self carry a field Window corresponding
    // to the full window to work as the AsRef implementation, so the user can pass images here as well.
    pub fn convert<M>(&mut self, other : &Window<M>) 
    where
        M : Scalar
    {
        let ncols = self.ncols;
        
        #[cfg(feature="opencvlib")]
        unsafe {
            cvutils::convert(
                other.win, 
                &mut self.buf[..], 
                other.orig_sz.1, 
                Some((other.offset, other.win_sz)),
                ncols,
                None
            );
            return;
        }
        
        #[cfg(feature="ipp")]
        {
            assert!(other.is_full());
            unsafe { ipp::convert(other.win, &mut self.buf[..], ncols); }
            return;
        }
        
        panic!("Either opencvlib or ipp feature should be enabled for image conversion");
    }
    
    pub fn iter(&self) -> impl Iterator<Item=&N> {
        let shape = self.shape();
        iterate_row_wise(&self.buf[..], (0, 0), shape, shape)
    }
    
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    // pub fn windows(&self) -> impl Iterator<Item=Window<'_, N>> {
    //    unimplemented!()
    // }
    
}

impl<N> Image<N>
    where N : Scalar + Copy + RealField 
{

    pub fn scale_by(&mut self, scalar : N)  {
        self.buf.iter_mut().for_each(|val| *val *= scalar);
    }
    
    pub fn unscale_by(&mut self, scalar : N)  {
        self.buf.iter_mut().for_each(|val| *val *= scalar);
    }
    
    /*pub fn iter(&self) -> impl Iterator<Item=&N> {
        self.full_window().clone().iter()
    }*/
    
}

impl Image<u8> {

    pub fn draw(&mut self, mark : Mark) {
        self.full_window_mut().draw(mark);
    }
}

impl Image<f32> {

    pub fn max(&self) -> ((usize, usize), f32) {
        let (mut max_ix, mut max) = ((0, 0), f32::NEG_INFINITY);
        for (lin_ix, px) in self.iter().enumerate() {
            if *px > max {
                max_ix = index::coordinate_index(lin_ix, self.ncols);
                max = *px
            }
        }
        (max_ix, max)
    }
}

impl<N> Index<(usize, usize)> for Image<N> 
where
    N : Scalar
{

    type Output = N;

    fn index(&self, index: (usize, usize)) -> &Self::Output {
        &self.buf[index::linear_index(index, self.ncols)]
    }
}

/*impl<N> IndexMut<(usize, usize)> for Image<N> 
where
    N : Scalar
{
    
    fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
        &mut self.buf[index]
    }
    
}*/

/*impl<N> AsRef<DMatrix<N>> for Image<N> 
where
    N : Scalar
{
    fn as_ref(&self) -> &DMatrix<N> {
        &self.buf
    }
}

impl<N> AsMut<DMatrix<N>> for Image<N> 
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut DMatrix<N> {
        &mut self.buf
    }
}*/

/// Borrowed subset of an image. Referencing the whole source slice (instead of just its
/// portion of interest) might be useful to represent overlfowing operations (e.g. draw)
/// as long as the operation does not violate bounds of the original image. We just have
/// to be careful to not expose the rest of the image in the API.
#[derive(Debug, Clone)]
pub struct Window<'a, N> 
where
    N : Scalar
{
    // Window offset, with respect to the top-left point (row, col).
    offset : (usize, usize),
    
    // Original image dimensions (height, width).
    orig_sz : (usize, usize),
    
    // This window size.
    win_sz : (usize, usize),
    
    // Original image full slice. Might refer to an actual pre-allocated image
    // buffer slice; or a slice from an external source (which is why we don't
    // simply reference image here).
    win : &'a [N],
    
    // Stack-allocated arrays which keep the slices for the chunks(.) method.
    // chunks : ([&[N]; 2], [&[N]; 4], [&[N]; 8], [&[N]; 16]);
    
    // TODO remove
    // transposed : bool
}

impl<'a, N> Window<'a, N>
where
    N : Scalar
{
    pub fn is_full(&'a self) -> bool {
        self.orig_sz == self.win_sz
    }
    
    /*pub fn shape(&self) -> (usize, usize) {
        self.win_sz
    }

    pub fn width(&self) -> usize {
        self.shape().0
    }

    pub fn height(&self) -> usize {
        self.shape().1
    }*/

    pub fn sub_window(&'a self, offset : (usize, usize), dims : (usize, usize)) -> Option<Window<'a, N>> {
        let new_offset = (self.offset.0 + offset.0, self.offset.1 + offset.1);
        if new_offset.0 + dims.0 <= self.orig_sz.0 && new_offset.1 + dims.1 <= self.orig_sz.1 {
            Some(Self {
                win : self.win,
                offset : new_offset,
                orig_sz : self.orig_sz,
                // transposed : self.transposed,
                win_sz : dims
            })
        } else {
            None
        }
    }

}

impl<'a, N> Window<'a, N>
where
    N : Scalar + Mul<Output=N> + MulAssign
{

    /// Creates a window that cover the whole slice src, assuming it represents a square image.
    pub fn from_square_slice(src : &'a [N]) -> Self {
        Self::from_slice(src, (src.len() as f64).sqrt() as usize)
    }
    
    /*pub fn from_slice(
        src : &'a [N], 
        img_shape : (usize, usize), 
        offset : (usize, usize), 
        win_shape : (usize, usize), 
        transposed : bool
    ) {
    
    }*/
    
    /// Creates a window that cover the whole slice src. The slice is assumed to be in
    /// row-major order, but matrices are assumed to be 
    pub fn from_slice(src : &'a [N], ncols : usize) -> Self {
        let nrows = src.len() / ncols;
        Self{ 
            // win : DMatrixSlice::from_slice_generic(src, Dynamic::new(nrows),
            // Dynamic::new(ncols)),
            win : src,
            offset : (0, 0),
            orig_sz : (nrows, ncols),
            win_sz : (nrows, ncols),
            // transposed : true
        }
    }
    
    pub fn shape(&self) -> (usize, usize) {
        // self.win.shape()
        self.win_sz
    }
    
    pub fn width(&self) -> usize {
        // self.win.ncols()
        self.win_sz.1
    }
    
    pub fn height(&self) -> usize {
        // self.win.nrows()
        self.win_sz.0
    }
    
    pub fn len(&self) -> usize {
        self.win_sz.0 * self.win_sz.1
    }

    /*pub fn linear_index(&self, ix : usize) -> &N {
        let offset = self.orig_sz.1 * offset.0 + offset.1;
        let row = ix / self.orig_sz.1;
        unsafe{ self.win.get_unchecked(offset + ix) }
    }*/

    /// Iterate over windows of the given size. This iterator consumes the original window
    /// so that we can implement windows(.) for Image by using move semantics, without
    /// requiring the user to call full_windows(.).
    pub fn windows(self, sz : (usize, usize)) -> impl Iterator<Item=Window<'a, N>> {
        let (step_v, step_h) = sz;
        if sz.0 >= self.win_sz.0 || sz.1 >= self.win_sz.1 {
            panic!("Child window size bigger than parent window size");
        }
        if self.height() % sz.0 != 0 || self.width() % sz.1 != 0 {
            panic!("Image size should be a multiple of window size (Required window {:?} over parent window {:?})", sz, self.win_sz);
        }
        let offset = self.offset;
        WindowIterator::<'a, N> {
            source : self,
            size : sz,
            curr_pos : offset,
            step_v,
            step_h
        }
    }
    
    pub fn row(&self, ix : usize) -> Option<&[N]> {
        if ix > self.win_sz.0 {
            return None;
        }
        let stride = self.orig_sz.1;
        let tl = self.offset.0 * stride + self.offset.1;
        let start = tl + ix*stride;
        Some(&self.win[start..(start+self.win_sz.1)])
    }

    pub fn rows(&self) -> impl Iterator<Item=&[N]> + Clone {
        let stride = self.orig_sz.1;
        let tl = self.offset.0 * stride + self.offset.1;
        (0..self.win_sz.0).map(move |i| {
            let start = tl + i*stride;
            &self.win[start..(start+self.win_sz.1)]
        })
    }

    pub fn iter(&self) -> impl Iterator<Item=&N> {
        iterate_row_wise(self.win, self.offset, self.win_sz, self.orig_sz)
    }
    
    pub fn clone_owned(&self) -> Image<N>
    where
        N : Copy
    {
        let mut buf = Vec::new();
        self.rows().for_each(|row| buf.extend(row.iter().cloned()) );
        Image::from_vec(buf, self.win_sz.1)
    }

    /*pub fn row_slices(&'a self) -> Vec<&'a [N]> {
        let mut rows = Vec::new();
        for r in (self.offset.0)..(self.offset.0+self.win_sz.0) {
            let begin = self.win_sz.1*r + self.offset.1;
            rows.push(&self.src[begin..begin+self.win_sz.1]);
        }
        rows
    }*/
    
}

#[test]
fn window_iter() {
    let img : Window<'_, u8> = Window::from_square_slice(&[
        1, 1, 1, 1, 0, 0, 0, 0,
        1, 1, 1, 1, 0, 0, 0, 0,
        1, 1, 1, 1, 0, 0, 0, 0,
        1, 1, 1, 1, 0, 0, 0, 0,
        0, 0, 0, 0, 1, 1, 1, 1,
        0, 0, 0, 0, 1, 1, 1, 1,
        0, 0, 0, 0, 1, 1, 1, 1,
        0, 0, 0, 0, 1, 1, 1, 1,
    ]);

    for win in img.windows((4,4)) {
        println!("Outer: {:?}", win);
        for win_inner in win.windows((2,2)) {
            println!("\tInner : {:?}", win_inner);
        }
        println!("")
    }
}

impl<N> Index<(usize, usize)> for Window<'_, N>
where
    N : Scalar
{

    type Output = N;

    fn index(&self, index: (usize, usize)) -> &Self::Output {
        let off_ix = (self.offset.0 + index.0, self.offset.1 + index.1);
        let (limit_row, limit_col) = (self.offset.0 + self.win_sz.0, self.offset.1 + self.win_sz.1);
        if off_ix.0 < limit_row && off_ix.1 < limit_col {
            &self.win[index::linear_index(off_ix, self.orig_sz.1)]
        } else {
            panic!("Invalid window index: {:?}", index);
        }
    }
}

pub fn iterate_row_wise<N>(
    src : &[N], 
    offset : (usize, usize), 
    win_sz : (usize, usize), 
    orig_sz : (usize, usize)
) -> impl Iterator<Item=&N> {
    let start = orig_sz.1 * offset.0 + offset.1;
    (0..win_sz.0).map(move |i| {
        let row_offset = start + i*orig_sz.1;
        &src[row_offset..(row_offset+win_sz.1)]
    }).flatten()
}

pub struct WindowIterator<'a, N>
where
    N : Scalar,
{
    source : Window<'a, N>,
    
    // This child window size
    size : (usize, usize),

    // Index the most ancestral window possible.
    curr_pos : (usize, usize),

    /// Vertical increment. Either U1 or Dynamic.
    step_v : usize,

    /// Horizontal increment. Either U1 or Dynamic.
    step_h : usize,

}

impl<'a, N> Iterator for WindowIterator<'a, N>
where
    N : Scalar
{

    type Item = Window<'a, N>;

    fn next(&mut self) -> Option<Self::Item> {
        let within_horiz = self.curr_pos.0  + self.size.0 <= (self.source.offset.0 + self.source.win_sz.0);
        let within_vert = self.curr_pos.1 + self.size.1 <= (self.source.offset.1 + self.source.win_sz.1);
        let within_bounds = within_horiz && within_vert;
        let win = if within_bounds {
            Some(Window { 
                offset : self.curr_pos,
                win_sz : self.size,
                orig_sz : self.source.orig_sz,
                win : &self.source.win
            })
        } else {
            None
        };
        self.curr_pos.1 += self.step_h;
        if self.curr_pos.1 + self.size.1 > (self.source.offset.1 + self.source.win_sz.1) {
            self.curr_pos.1 = self.source.offset.1;
            self.curr_pos.0 += self.step_v;
        }
        win
    }

}

#[cfg(feature="opencvlib")]
impl<N> Into<core::Mat> for Window<'_, N> 
where
    N : Scalar + Copy
{

    fn into(self) -> core::Mat {
        let sub_slice = Some((self.offset, self.win_sz));
        let stride = self.orig_sz.1;
        unsafe{ cvutils::slice_to_mat(self.win, stride, sub_slice) }
    }
}

#[cfg(feature="opencvlib")]
impl<N> Into<core::Mat> for WindowMut<'_, N>
where
    N : Scalar + Copy
{

    fn into(self) -> core::Mat {
        let sub_slice = Some((self.offset, self.win_sz));
        let stride = self.orig_sz.1;
        unsafe{ cvutils::slice_to_mat(self.win, stride, sub_slice) }
    }
}

pub enum Mark {

    // Position, square lenght and color
    Cross((usize, usize), usize, u8),
    
    // Position, square lenght and color
    Corner((usize, usize), usize, u8),
    
    // Start and end positions and color
    Line((usize, usize), (usize, usize), u8),
    
    // Position, digit value, digit size and color
    Digit((usize, usize), usize, usize, u8),

    // Position, label, digit value, size and color
    Label((usize, usize), &'static str, usize, u8),

    // Center, radius and color
    Circle((usize, usize), usize, u8)
    
}

#[derive(Debug)]
pub struct WindowMut<'a, N> 
where
    N : Scalar + Copy
{
    // Window offset, with respect to the top-left point (row, col).
    offset : (usize, usize),
    
    // Original image size.
    orig_sz : (usize, usize),
    
    // This window size.
    win_sz : (usize, usize),
    
    // Original image full slice.
    win : &'a mut [N],
}

impl<'a, N> WindowMut<'a, N>
where
    N : Scalar + Copy + Debug
{

    pub fn from_slice(src : &'a mut [N], ncols : usize) -> Self {
        /*let nrows = src.len() / ncols;
        Self {
            win : DMatrixSliceMut::from_slice_generic(src, Dynamic::new(nrows),
            Dynamic::new(ncols)),
            offset : (0, 0),
            orig_sz : (nrows, ncols)
        }*/
        let nrows = src.len() / ncols;
        Self{
            // win : DMatrixSlice::from_slice_generic(src, Dynamic::new(nrows),
            // Dynamic::new(ncols)),
            win : src,
            offset : (0, 0),
            orig_sz : (nrows, ncols),
            win_sz : (nrows, ncols),
        }
    }

    pub fn sub_window_mut(&'a mut self, offset : (usize, usize), dims : (usize, usize)) -> Option<WindowMut<'a, N>> {
        let new_offset = (self.offset.0 + offset.0, self.offset.1 + offset.1);
        if new_offset.0 + dims.0 <= self.orig_sz.0 && new_offset.1 + dims.1 <= self.orig_sz.1 {
            Some(Self {
                win : self.win,
                offset : (self.offset.0 + offset.0, self.offset.1 + offset.1),
                orig_sz : self.orig_sz,
                // transposed : self.transposed,
                win_sz : dims
            })
        } else {
            None
        }
    }

    /// Creates a window that cover the whole slice src, assuming it represents a square image.
    pub fn from_square_slice(src : &'a mut [N]) -> Self {
        Self::from_slice(src, (src.len() as f64).sqrt() as usize)
    }

}

impl WindowMut<'_, u8> {

    pub fn draw(&mut self, mark : Mark) {
        /*let slice_ptr = self.win.data.as_mut_slice().as_mut_ptr();
        let ptr_offset = slice_ptr as u64 - (self.orig_sz.0*(self.offset.1 - 1)) as u64 - self.offset.0 as u64;
        let orig_ptr = ptr_offset as *mut u8;
        let orig_slice = unsafe { std::slice::from_raw_parts_mut(orig_ptr, self.orig_sz.0 * self.orig_sz.1) };*/
        match mark {
            Mark::Cross(pos, sz, col) => {
                let cross_pos = (self.offset.0 + pos.0, self.offset.1 + pos.1);
                draw::draw_cross(
                    self.win,
                    self.orig_sz,
                    cross_pos,
                    col,
                    sz
                );
            },
            Mark::Corner(pos, sz, col) => {
                let center_pos = (self.offset.0 + pos.0, self.offset.1 + pos.1);
                draw::draw_corners(
                    self.win,
                    self.orig_sz,
                    center_pos,
                    col,
                    sz
                );
            },
            Mark::Line(src, dst, color) => {
                let src_pos = (self.offset.0 + src.0, self.offset.1 + src.1);
                let dst_pos = (self.offset.0 + dst.0, self.offset.1 + dst.1);
                
                #[cfg(feature="opencvlib")]
                unsafe {
                    cvutils::draw_line(self.win, self.orig_sz.1, src_pos, dst_pos, color);
                    return;
                }
                
                draw::draw_line(
                    self.win,
                    self.orig_sz,
                    src_pos,
                    dst_pos,
                    color
                );
            },
            Mark::Digit(pos, val, sz, color) => {
                let tl_pos = (self.offset.0 + pos.0, self.offset.1 + pos.1);

                #[cfg(feature="opencvlib")]
                unsafe {
                    cvutils::write_text(self.win, self.orig_sz.1, tl_pos, &val.to_string()[..], color);
                    return;
                }
                
                draw::draw_digit_native(self.win, self.orig_sz.1, tl_pos, val, sz, color);
            },
            Mark::Label(pos, msg, sz, color) => {
                let tl_pos = (self.offset.0 + pos.0, self.offset.1 + pos.1);

                #[cfg(feature="opencvlib")]
                unsafe {
                    cvutils::write_text(self.win, self.orig_sz.1, tl_pos, msg, color);
                    return;
                }

                panic!("Label draw require 'opencvlib' feature");
            },
            Mark::Circle(pos, radius, color) => {
                let center_pos = (self.offset.0 + pos.0, self.offset.1 + pos.1);

                #[cfg(feature="opencvlib")]
                unsafe {
                    cvutils::draw_circle(self.win, self.orig_sz.1, center_pos, radius, color);
                    return;
                }

                panic!("Circle draw require 'opencvlib' feature");
            }
        }
    }
    
}

impl<'a, N> WindowMut<'a, N> 
where
    N : Scalar + Copy
{

    pub fn shape(&self) -> (usize, usize) {
        self.win_sz
    }

    pub fn width(&self) -> usize {
        self.shape().0
    }

    pub fn height(&self) -> usize {
        self.shape().1
    }

}

impl<'a, N> WindowMut<'a, N>
where
    N : Scalar + Copy + MulAssign + AddAssign + Add<Output=N> + Mul<Output=N> + SubAssign + Field + SimdPartialOrd,
    f64 : SubsetOf<N>
{
    
    pub fn component_scale(&mut self, _other : &Window<N>) {
        // self.win.component_mul_mut(&other.win);
        unimplemented!()
    }

}

impl<N> Index<(usize, usize)> for WindowMut<'_, N> 
where
    N : Scalar + Copy
{

    type Output = N;

    fn index(&self, _index: (usize, usize)) -> &Self::Output {
        // &self.win[index]
        unimplemented!()
    }
}

impl<N> IndexMut<(usize, usize)> for WindowMut<'_, N> 
where
    N : Scalar + Copy
{
    
    fn index_mut(&mut self, _index: (usize, usize)) -> &mut Self::Output {
        //&mut self.win[index]
        unimplemented!()
    }
    
}

impl<'a, N> AsRef<DMatrixSlice<'a, N>> for Window<'a, N> 
where
    N : Scalar + Copy
{
    fn as_ref(&self) -> &DMatrixSlice<'a, N> {
        // &self.win
        unimplemented!()
    }
}

/*impl<'a, M, N> Downsample<Image<N>> for Window<'a, M> 
where
    M : Scalar + Copy,
    N : Scalar + From<M>
{

    fn downsample(&self, dst : &mut Image<N>) {
        // let (nrows, ncols) = dst.shape();
        /*let step_rows = self.win_sz.0 / dst.nrows;
        let step_cols = self.win_sz.1 / dst.ncols;
        assert!(step_rows == step_cols);
        sampling::slices::subsample_convert_window(
            self.src,
            self.offset,
            self.win_sz, 
            (dst.nrows, dst.ncols),
            step_rows,
            dst.buf.as_mut_slice().chunks_mut(dst.nrows)
        );*/
        unimplemented!()
    }
    
}*/

/*/// Data is assumed to live on the matrix in a column-order fashion, not row-ordered.
impl<N> From<DMatrix<N>> for Image<N> 
where
    N : Scalar + Copy
{
    fn from(buf : DMatrix<N>) -> Self {
        /*let (nrows, ncols) = s.shape();
        let data : Vec<N> = s.data.into();
        let buf = DVector::from_vec(data);
        Self{ buf, nrows, ncols }*/
        let ncols = buf.ncols();
        Self{ buf, ncols }
    }
}*/

/*impl<N> From<(Vec<N>, usize)> for Image<N> 
where
    N : Scalar
{
    fn from(s : (Vec<N>, usize)) -> Self {
        let (nrows, ncols) = (s.1, s.0.len() - s.1);
        Self{ buf : DVector::from_vec(s.0), nrows, ncols  }
    }
}*/

impl<N> AsRef<[N]> for Image<N> 
where
    N : Scalar
{
    fn as_ref(&self) -> &[N] {
        &self.buf[..]
    }
}

impl<N> AsMut<[N]> for Image<N> 
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut [N] {
        &mut self.buf[..]
    }
}

impl<N> fmt::Display for Window<'_, N> 
where
    N : Scalar + Copy,
    f64 : From<N>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", pgm::build_pgm_string_from_slice(&self.win, self.orig_sz.1))
    }
}

impl<N> fmt::Display for WindowMut<'_, N> 
where
    N : Scalar + Copy,
    f64 : From<N>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", pgm::build_pgm_string_from_slice(&self.win, self.orig_sz.1))
    }
}

impl<N> fmt::Display for Image<N> 
where
    N : Scalar + Copy,
    f64 : From<N>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", pgm::build_pgm_string_from_slice(&self.buf[..], self.ncols))
    }
}

#[test]
fn checkerboard() {
    let src : [u8; 4] = [0, 1, 1, 0];
    let mut converted : Image<f32> = Image::new_constant(4, 4, 0.0);
    let win = Window::from_square_slice(&src);
    //converted.convert_from_window(&win);
    // println!("{}", converted);
}

/*impl<N> AsRef<Vec<N>> for Image<N> 
where
    N : Scalar
{
    fn as_ref(&self) -> &Vec<N> {
        self.buf.data.as_vec()
    }
}

impl<N> AsMut<Vec<N>> for Image<N> 
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut Vec<N> {
        unsafe{ self.buf.data.as_vec_mut() }
    }
}*/

/*impl<N> AsRef<DVector<N>> for Image<N> 
where
    N : Scalar
{
    fn as_ref(&self) -> &DVector<N> {
        &self.buf
    }
}

impl<N> AsMut<DVector<N>> for Image<N> 
where
    N : Scalar
{
    fn as_mut(&mut self) -> &mut DVector<N> {
        &mut self.buf
    }
}*/

/*/// Result of thresholding an image. This structure carries a (row, col) index and
/// a scalar value for this index. Rename to Keypoints.
pub struct SparseImage {

}

/// Subset of a SparseImage
pub struct SparseWindow<'a> {

    /// Source sparse image
    source : &'a SparseImage,
    
    /// Which indices we will use from the source
    ixs : Vec<usize>
}*/

// TODO implement borrow::ToOwned

/*
// Local maxima of the image multiscale transformation
pub struct Keypoint { }

// Object characterized by a set of close keypoints where ordered pairs share close angles. 
pub struct Edge { }

// Low-dimensional approximation of an edge (in terms of lines and curves).
pub struct Shape { }

// Object characterized by a set of shapes.
pub struct Object { }
*/

/*
The match item at procedural macros has the syntax $name:token where token must be one of:
item — an item, like a function, struct, module, etc.
block — a block (i.e. a block of statements and/or an expression, surrounded by braces)
stmt — a statement
pat — a pattern
expr — an expression
ty — a type
ident — an identifier
path — a path (e.g., foo, ::std::mem::replace, transmute::<_, int>, …)
meta — a meta item; the things that go inside #[...] and #![...] attributes
tt — a single token tree
vis — a possibly empty Visibility qualifier

Repeated arguments are treated as (* matches zero or more; + matches zero or one):
macro_rules! add_as{
    ( $($a:expr), )=>{ {  0 $(+$a)* }    }
}

The token type that repeats is enclosed in $(), followed by a separator and a * or a +, indicating the number of times the token will repeat.
*/

/*macro_rules! sql {
 // macth like arm for macro
    ($a:expr) => {
    
    },
    ($a:expr, $b:expr)=>{
 // macro expand to this code
        {
// $a and $b will be templated using the value/variable provided to macro
            $a+$b
        }
    }
}*/