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
//! Image processing, see [OpenCV
//! imgproc](http://docs.opencv.org/3.1.0/d7/dbd/group__imgproc.html).

use super::core::*;
use super::*;
use std::os::raw::{c_double, c_float, c_int};

// =============================================================================
//  Imgproc
// =============================================================================
extern "C" {
    fn cv_line(
        cmat: *mut CMat,
        pt1: Point2i,
        pt2: Point2i,
        color: Scalar,
        thickness: c_int,
        linetype: LineType,
        shift: c_int,
    );

    fn cv_rectangle(cmat: *mut CMat, rect: Rect, color: Scalar, thickness: c_int, linetype: LineType);

    fn cv_ellipse(
        cmat: *mut CMat,
        center: Point2i,
        axes: Size2i,
        angle: c_double,
        start_angle: c_double,
        end_angle: c_double,
        color: Scalar,
        thickness: c_int,
        linetype: LineType,
        shift: c_int,
    );

    fn cv_cvt_color(cmat: *const CMat, output: *mut CMat, code: ColorConversion);
    fn cv_pyr_down(cmat: *const CMat, output: *mut CMat);
    fn cv_threshold(from: *const CMat, to: *mut CMat, thresh: f64, maxval: f64, ttype: ThresholdType);
    fn cv_erode(
        from: *const CMat,
        to: *mut CMat,
        kernel: *const CMat,
        anchor: Point2i,
        iterations: i32,
        border_type: i32,
        border_value: Scalar,
    );
    fn cv_dilate(
        from: *const CMat,
        to: *mut CMat,
        kernel: *const CMat,
        anchor: Point2i,
        iterations: i32,
        border_type: i32,
        border_value: Scalar,
    );
    fn cv_gaussian_blur(
        from: *const CMat,
        to: *mut CMat,
        dsize: Size2i,
        sigma_x: c_double,
        sigma_y: c_double,
        border_type: i32,
    );
    fn cv_resize(
        from: *const CMat,
        to: *mut CMat,
        dsize: Size2i,
        fx: c_double,
        fy: c_double,
        interpolation: InterpolationFlag,
    );
    fn cv_calc_hist(
        cimages: *const CMat,
        nimages: c_int,
        channels: *const c_int,
        cmask: *const CMat,
        chist: *mut CMat,
        dims: c_int,
        hist_size: *const c_int,
        ranges: *const *const c_float,
    );
    fn cv_calc_back_project(
        cimages: *const CMat,
        nimages: c_int,
        channels: *const c_int,
        chist: *const CMat,
        cback_project: *mut CMat,
        ranges: *const *const c_float,
    );

    fn cv_compare_hist(
        first_image: *const CMat,
        second_image: *const CMat,
        method: HistogramComparisionMethod,
        result: *mut CResult<c_double>,
    );

    fn cv_sobel(
        src: *const CMat,
        dst: *mut CMat,
        ddepth: c_int,
        dx: c_int,
        dy: c_int,
        k_size: c_int,
        scale: c_double,
        delta: c_double,
        border_type: c_int,
    );

    fn cv_scharr(
        src: *const CMat,
        dst: *mut CMat,
        ddepth: c_int,
        dx: c_int,
        dy: c_int,
        scale: c_double,
        delta: c_double,
        border_type: c_int,
    );

    fn cv_canny(
        image: *const CMat,
        edges: *mut CMat,
        threshold1: c_double,
        threshold2: c_double,
        aperture_size: c_int,
        l2_gradient: c_int,
    ) -> CEmptyResult;

}

/// Possible methods for histogram comparision method
#[repr(C)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum HistogramComparisionMethod {
    /// HISTCMP_CORREL
    Correlation = 0,
    /// HISTCMP_CHISQR
    ChiSquare = 1,
    /// HISTCMP_INTERSECT
    Intersection = 2,
    /// HISTCMP_BHATTACHARYYA **and** HISTCMP_HELLINGER
    Bhattacharyya = 3,
    /// HISTCMP_CHISQR_ALT
    ChiSquareAlternative = 4,
    /// HISTCMP_KL_DIV
    KullbackLeiblerDivergence = 5,
}

/// ThresholdTypes used in
/// [threshold](../struct.Mat.html#method.threshold).
#[repr(C)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[allow(missing_docs)]
pub enum ThresholdType {
    Binary = 0,
    BinaryInv = 1,
    Trunc = 2,
    ToZero = 3,
    ToZeroInv = 4,
    Mask = 7,
    Otsu = 8,
    Triangle = 16,
}

/// Color conversion code used in
/// [cvt_color](../struct.Mat.html#method.cvt_color).
#[repr(C)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[allow(non_camel_case_types, missing_docs)]
pub enum ColorConversion {
    BGR2BGRA = 0,
    BGRA2BGR = 1,
    BGR2RGBA = 2,
    RGBA2BGR = 3,
    BGR2RGB = 4,
    BGRA2RGBA = 5,
    BGR2GRAY = 6,
    RGB2GRAY = 7,
    GRAY2BGR = 8,
    GRAY2BGRA = 9,
    BGRA2GRAY = 10,
    RGBA2GRAY = 11,
    BGR2BGR565 = 12,
    RGB2BGR565 = 13,
    BGR5652BGR = 14,
    BGR5652RGB = 15,
    BGRA2BGR565 = 16,
    RGBA2BGR565 = 17,
    BGR5652BGRA = 18,
    BGR5652RGBA = 19,
    GRAY2BGR565 = 20,
    BGR5652GRAY = 21,
    BGR2BGR555 = 22,
    RGB2BGR555 = 23,
    BGR5552BGR = 24,
    BGR5552RGB = 25,
    BGRA2BGR555 = 26,
    RGBA2BGR555 = 27,
    BGR5552BGRA = 28,
    BGR5552RGBA = 29,
    GRAY2BGR555 = 30,
    BGR5552GRAY = 31,
    BGR2XYZ = 32,
    RGB2XYZ = 33,
    XYZ2BGR = 34,
    XYZ2RGB = 35,
    BGR2YCrCb = 36,
    RGB2YCrCb = 37,
    YCrCb2BGR = 38,
    YCrCb2RGB = 39,
    BGR2HSV = 40,
    RGB2HSV = 41,
    BGR2Lab = 44,
    RGB2Lab = 45,
    BGR2Luv = 50,
    RGB2Luv = 51,
    BGR2HLS = 52,
    RGB2HLS = 53,
    HSV2BGR = 54,
    HSV2RGB = 55,
    Lab2BGR = 56,
    Lab2RGB = 57,
    Luv2BGR = 58,
    Luv2RGB = 59,
    HLS2BGR = 60,
    HLS2RGB = 61,
    BGR2HSV_FULL = 66,
    RGB2HSV_FULL = 67,
    BGR2HLS_FULL = 68,
    RGB2HLS_FULL = 69,
    HSV2BGR_FULL = 70,
    HSV2RGB_FULL = 71,
    HLS2BGR_FULL = 72,
    HLS2RGB_FULL = 73,
    LBGR2Lab = 74,
    LRGB2Lab = 75,
    LBGR2Luv = 76,
    LRGB2Luv = 77,
    Lab2LBGR = 78,
    Lab2LRGB = 79,
    Luv2LBGR = 80,
    Luv2LRGB = 81,
    BGR2YUV = 82,
    RGB2YUV = 83,
    YUV2BGR = 84,
    YUV2RGB = 85,
    YUV2RGB_NV12 = 90,
    YUV2BGR_NV12 = 91,
    YUV2RGB_NV21 = 92,
    YUV2BGR_NV21 = 93,
    YUV2RGBA_NV12 = 94,
    YUV2BGRA_NV12 = 95,
    YUV2RGBA_NV21 = 96,
    YUV2BGRA_NV21 = 97,
    YUV2RGB_YV12 = 98,
    YUV2BGR_YV12 = 99,
    YUV2RGB_IYUV = 100,
    YUV2BGR_IYUV = 101,
    YUV2RGBA_YV12 = 102,
    YUV2BGRA_YV12 = 103,
    YUV2RGBA_IYUV = 104,
    YUV2BGRA_IYUV = 105,
    YUV2GRAY_420 = 106,
    YUV2RGB_UYVY = 107,
    YUV2BGR_UYVY = 108,
    YUV2RGBA_UYVY = 111,
    YUV2BGRA_UYVY = 112,
    YUV2RGB_YUY2 = 115,
    YUV2BGR_YUY2 = 116,
    YUV2RGB_YVYU = 117,
    YUV2BGR_YVYU = 118,
    YUV2RGBA_YUY2 = 119,
    YUV2BGRA_YUY2 = 120,
    YUV2RGBA_YVYU = 121,
    YUV2BGRA_YVYU = 122,
    YUV2GRAY_UYVY = 123,
    YUV2GRAY_YUY2 = 124,
    RGBA2mRGBA = 125,
    mRGBA2RGBA = 126,
    RGB2YUV_I420 = 127,
    BGR2YUV_I420 = 128,
    RGBA2YUV_I420 = 129,
    BGRA2YUV_I420 = 130,
    RGB2YUV_YV12 = 131,
    BGR2YUV_YV12 = 132,
    RGBA2YUV_YV12 = 133,
    BGRA2YUV_YV12 = 134,
    BayerBG2BGR = 46,
    BayerGB2BGR = 47,
    BayerRG2BGR = 48,
    BayerGR2BGR = 49,
    BayerBG2GRAY = 86,
    BayerGB2GRAY = 87,
    BayerRG2GRAY = 88,
    BayerGR2GRAY = 89,
    BayerBG2BGR_VNG = 62,
    BayerGB2BGR_VNG = 63,
    BayerRG2BGR_VNG = 64,
    BayerGR2BGR_VNG = 65,
    BayerBG2BGR_EA = 135,
    BayerGB2BGR_EA = 136,
    BayerRG2BGR_EA = 137,
    BayerGR2BGR_EA = 138,
    COLORCVT_MAX = 139,
}

/// Interpolation algorithm
#[repr(C)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum InterpolationFlag {
    /// nearest neighbor interpolation
    InterNearst = 0,
    /// bilinear interpolation
    InterLinear = 1,
    /// bicubic interpolation
    InterCubic = 2,
    /// resampling using pixel area relation. It may be a preferred method for
    /// image decimation, as it gives moire'-free results. But when the image is
    /// zoomed, it is similar to the INTER_NEAREST method.
    InterArea = 3,
    /// Lanczos interpolation over 8x8 neighborhood
    InterLanczos4 = 4,
    /// Bit exact bilinear interpolation
    InterLinearExact = 5,
    /// mask for interpolation codes
    InterMax = 7,
    /// flag, fills all of the destination image pixels. If some of them
    /// correspond to outliers in the source image, they are set to zero
    WarpFillOutliers = 8,
    /// flag, inverse transformation
    WarpInverseMap = 16,
}

impl Mat {
    /// Draws a simple line.
    pub fn line(&self, pt1: Point2i, pt2: Point2i) {
        let color = Scalar::new(255, 255, 0, 255);
        self.line_custom(pt1, pt2, color, 1, LineType::Line8, 0);
    }

    /// Draws a line with custom color, thickness and linetype.
    pub fn line_custom(
        &self,
        pt1: Point2i,
        pt2: Point2i,
        color: Scalar,
        thickness: c_int,
        linetype: LineType,
        shift: c_int,
    ) {
        unsafe {
            cv_line(self.inner, pt1, pt2, color, thickness, linetype, shift);
        }
    }

    /// Draws a simple, thick, or filled up-right rectangle.
    pub fn rectangle(&self, rect: Rect) {
        self.rectangle_custom(rect, Scalar::new(255, 255, 0, 255), 1, LineType::Line8);
    }

    /// Draws a rectangle with custom color, thickness and linetype.
    pub fn rectangle_custom(&self, rect: Rect, color: Scalar, thickness: c_int, linetype: LineType) {
        unsafe { cv_rectangle(self.inner, rect, color, thickness, linetype) }
    }

    /// Draw a simple, thick, or filled up-right rectangle.
    pub fn rectangle2f(&self, rect: Rect2f) {
        let abs_rect = rect.normalize_to_mat(self);
        self.rectangle(abs_rect);
    }

    /// Draws a simple, thick ellipse
    pub fn ellipse(&self, center: Point2i, axes: Size2i, angle: f64, start_angle: f64, end_angle: f64) {
        self.ellipse_custom(
            center,
            axes,
            angle,
            start_angle,
            end_angle,
            Scalar::new(255, 255, 0, 255),
            1,
            LineType::Line8,
            0,
        )
    }

    /// Draws a custom ellipse
    pub fn ellipse_custom(
        &self,
        center: Point2i,
        axes: Size2i,
        angle: f64,
        start_angle: f64,
        end_angle: f64,
        color: Scalar,
        thickness: c_int,
        linetype: LineType,
        shift: c_int,
    ) {
        unsafe {
            cv_ellipse(
                self.inner,
                center,
                axes,
                angle,
                start_angle,
                end_angle,
                color,
                thickness,
                linetype,
                shift,
            )
        }
    }

    /// Convert an image from one color space to another.
    pub fn cvt_color(&self, code: ColorConversion) -> Mat {
        let m = CMat::new();
        unsafe { cv_cvt_color(self.inner, m, code) }
        Mat::from_raw(m)
    }

    /// Blurs an image and downsamples it. This function performs the
    /// downsampling step of the Gaussian pyramid construction.
    pub fn pyr_down(&self) -> Mat {
        let m = CMat::new();
        unsafe { cv_pyr_down(self.inner, m) }
        Mat::from_raw(m)
    }

    /// Threshold
    ///
    pub fn threshold(&self, thresh: f64, maxval: f64, threshold_type: ThresholdType) -> Mat {
        let m = CMat::new();
        unsafe { cv_threshold(self.inner, m, thresh, maxval, threshold_type) }
        Mat::from_raw(m)
    }

    /// Erode
    ///
    pub fn erode(
        &self,
        kernel: &Mat,
        anchor: Point2i,
        iterations: i32,
        border_type: BorderType,
        border_value: Scalar,
    ) -> Mat {
        let m = CMat::new();
        unsafe {
            cv_erode(
                self.inner,
                m,
                kernel.inner,
                anchor,
                iterations,
                border_type as i32,
                border_value,
            )
        }
        Mat::from_raw(m)
    }

    /// Dilate
    ///
    pub fn dilate(
        &self,
        kernel: &Mat,
        anchor: Point2i,
        iterations: i32,
        border_type: BorderType,
        border_value: Scalar,
    ) -> Mat {
        let m = CMat::new();
        unsafe {
            cv_dilate(
                self.inner,
                m,
                kernel.inner,
                anchor,
                iterations,
                border_type as i32,
                border_value,
            )
        }
        Mat::from_raw(m)
    }

    /// Gaussian Blur
    ///
    pub fn gaussian_blur(&self, dsize: Size2i, sigma_x: f64, sigma_y: f64, border_type: BorderType) -> Mat {
        let m = CMat::new();
        unsafe { cv_gaussian_blur(self.inner, m, dsize, sigma_x, sigma_y, border_type as i32) }
        Mat::from_raw(m)
    }

    /// Resizes an image.
    ///
    /// The function resize resizes the image down to or up to the specified
    /// size.
    pub fn resize_to(&self, dsize: Size2i, interpolation: InterpolationFlag) -> Mat {
        let m = CMat::new();
        unsafe { cv_resize(self.inner, m, dsize, 0.0, 0.0, interpolation) }
        Mat::from_raw(m)
    }

    /// Resizes an image.
    ///
    /// The function resize resizes the image down to or up to the specified
    /// size.
    pub fn resize_by(&self, fx: f64, fy: f64, interpolation: InterpolationFlag) -> Mat {
        let m = CMat::new();
        unsafe { cv_resize(self.inner, m, Size2i::default(), fx, fy, interpolation) }
        Mat::from_raw(m)
    }

    /// Calculate a histogram of an image.
    pub fn calc_hist<T: AsRef<[c_int]>, U: AsRef<[c_int]>, MElem: AsRef<[f32]>, M: AsRef<[MElem]>>(
        &self,
        channels: T,
        mask: &Mat,
        hist_size: U,
        ranges: M,
    ) -> Mat {
        let m = CMat::new();
        let channels = channels.as_ref();
        let hist_size = hist_size.as_ref();
        let ranges = Self::matrix_to_vec(ranges);
        unsafe {
            cv_calc_hist(
                self.inner,
                1,
                channels.as_ptr(),
                mask.inner,
                m,
                channels.len() as c_int,
                hist_size.as_ptr(),
                ranges.as_ptr(),
            );
        }
        Mat::from_raw(m)
    }

    /// Calculate the back projection of a histogram. The function calculates
    /// the back project of the histogram.
    pub fn calc_back_project<T: AsRef<[c_int]>, MElem: AsRef<[f32]>, M: AsRef<[MElem]>>(
        &self,
        channels: T,
        hist: &Mat,
        ranges: M,
    ) -> Mat {
        let m = CMat::new();
        let ranges = Self::matrix_to_vec(ranges);
        unsafe {
            cv_calc_back_project(
                self.inner,
                1,
                channels.as_ref().as_ptr(),
                (*hist).inner,
                m,
                ranges.as_ptr(),
            );
        }
        Mat::from_raw(m)
    }

    /// Compares two histograms.
    /// The function compare two histograms using the specified method.
    /// The function returns d(first_image, second_image).
    /// While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be
    /// suitable for high-dimensional sparse histograms.
    /// In such histograms, because of aliasing and sampling problems,
    /// the coordinates of non-zero histogram bins can slightly shift.
    /// To compare such histograms or more general sparse configurations of weighted points,
    /// consider using the cv::EMD function.
    pub fn compare_hist(&self, other: &Mat, method: HistogramComparisionMethod) -> Result<f64, String> {
        let result = CResult::<f64>::from_callback(|r| unsafe { cv_compare_hist(self.inner, other.inner, method, r) });
        result.into()
    }

    /// Calculates the first x- or y- image derivative using Sobel operator.
    pub fn sobel(
        &self,
        ddepth: i32,
        dx: i32,
        dy: i32,
        k_size: i32,
        scale: f64,
        delta: f64,
        border_type: BorderType,
    ) -> Mat {
        let m = CMat::new();
        unsafe {
            cv_sobel(self.inner, m, ddepth, dx, dy, k_size, scale, delta, border_type as i32);
        }
        Mat::from_raw(m)
    }

    /// Calculates the first x- or y- image derivative using Scharr operator.
    pub fn scharr(&self, ddepth: i32, dx: i32, dy: i32, scale: f64, delta: f64, border_type: BorderType) -> Mat {
        let m = CMat::new();
        unsafe {
            cv_scharr(self.inner, m, ddepth, dx, dy, scale, delta, border_type as i32);
        }
        Mat::from_raw(m)
    }

    /// Performs canny edge detection
    pub fn canny(
        &self,
        threshold1: f64,
        threshold2: f64,
        aperture_size: i32,
        l2_gradient: bool,
    ) -> Result<Mat, String> {
        let edges = Mat::new();
        let result = unsafe {
            cv_canny(
                self.inner,
                edges.inner,
                threshold1,
                threshold2,
                aperture_size,
                match l2_gradient {
                    true => 1,
                    false => 0,
                },
            )
        };
        let result: Result<(), String> = result.into();
        result.map(|_| edges)
    }

    fn matrix_to_vec<T, MElem: AsRef<[T]>, M: AsRef<[MElem]>>(value: M) -> Vec<*const T> {
        value.as_ref().iter().map(|x| x.as_ref().as_ptr()).collect::<Vec<_>>()
    }
}