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
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954

extern crate libc;

use self::libc::{c_char, c_double, c_float, c_int, c_uint};
use crate::array::Array;
use crate::defines::{AfError, BorderType, CannyThresholdType, ColorSpace, Connectivity};
use crate::defines::{DiffusionEq, FluxFn, InterpType, MomentType, YCCStd};
use crate::defines::{InverseDeconvAlgo, IterativeDeconvAlgo};
use crate::error::HANDLE_ERROR;
use crate::util::{AfArray, DimT, MutAfArray};
use crate::util::{ConfidenceCCInput, DeconvInput};
use crate::util::{EdgeComputable, GrayRGBConvertible, MomentsComputable, RealFloating};
use crate::util::{FloatingPoint, HasAfEnum, ImageFilterType, ImageNativeType, RealNumber};
use std::ffi::CString;

// unused functions from image.h header
// af_save_image_memory
// af_delete_image_memory

extern "C" {
fn af_cast(out: MutAfArray, arr: AfArray, aftype: c_uint) -> c_int;
fn af_gradient(dx: MutAfArray, dy: MutAfArray, arr: AfArray) -> c_int;
fn af_load_image(out: MutAfArray, filename: *const c_char, iscolor: c_int) -> c_int;
fn af_save_image(filename: *const c_char, input: AfArray) -> c_int;
fn af_load_image_native(out: MutAfArray, filename: *const c_char) -> c_int;
fn af_save_image_native(filename: *const c_char, input: AfArray) -> c_int;

fn af_resize(
out: MutAfArray,
input: AfArray,
odim0: DimT,
odim1: DimT,
method: c_uint,
) -> c_int;

fn af_transform(
out: MutAfArray,
input: AfArray,
trans: AfArray,
odim0: DimT,
odim1: DimT,
method: c_uint,
is_inverse: c_int,
) -> c_int;

fn af_rotate(
out: MutAfArray,
input: AfArray,
theta: c_float,
crop: c_int,
method: c_uint,
) -> c_int;

fn af_translate(
out: MutAfArray,
input: AfArray,
trans0: c_float,
trans1: c_float,
odim0: DimT,
odim1: DimT,
method: c_uint,
) -> c_int;

fn af_scale(
out: MutAfArray,
input: AfArray,
scale0: c_float,
scale1: c_float,
odim0: DimT,
odim1: DimT,
method: c_uint,
) -> c_int;

fn af_skew(
out: MutAfArray,
input: AfArray,
skew0: c_float,
skew1: c_float,
odim0: DimT,
odim1: DimT,
method: c_uint,
is_inverse: c_int,
) -> c_int;

fn af_histogram(
out: MutAfArray,
input: AfArray,
nbins: c_uint,
minval: c_double,
maxval: c_double,
) -> c_int;

fn af_dilate(out: MutAfArray, input: AfArray, mask: AfArray) -> c_int;
fn af_dilate3(out: MutAfArray, input: AfArray, mask: AfArray) -> c_int;
fn af_erode(out: MutAfArray, input: AfArray, mask: AfArray) -> c_int;
fn af_erode3(out: MutAfArray, input: AfArray, mask: AfArray) -> c_int;
fn af_regions(out: MutAfArray, input: AfArray, conn: c_uint, aftype: c_uint) -> c_int;
fn af_sobel_operator(dx: MutAfArray, dy: MutAfArray, i: AfArray, ksize: c_uint) -> c_int;
fn af_rgb2gray(out: MutAfArray, input: AfArray, r: c_float, g: c_float, b: c_float) -> c_int;
fn af_gray2rgb(out: MutAfArray, input: AfArray, r: c_float, g: c_float, b: c_float) -> c_int;
fn af_hist_equal(out: MutAfArray, input: AfArray, hist: AfArray) -> c_int;
fn af_hsv2rgb(out: MutAfArray, input: AfArray) -> c_int;
fn af_rgb2hsv(out: MutAfArray, input: AfArray) -> c_int;

fn af_bilateral(
out: MutAfArray,
input: AfArray,
sp_sig: c_float,
ch_sig: c_float,
iscolor: c_int,
) -> c_int;

fn af_mean_shift(
out: MutAfArray,
input: AfArray,
sp_sig: c_float,
ch_sig: c_float,
iter: c_uint,
iscolor: c_int,
) -> c_int;

fn af_medfilt(out: MutAfArray, input: AfArray, wlen: DimT, wwid: DimT, etype: c_uint) -> c_int;

fn af_medfilt1(out: MutAfArray, input: AfArray, wlen: DimT, etype: c_uint) -> c_int;

fn af_minfilt(out: MutAfArray, input: AfArray, wlen: DimT, wwid: DimT, etype: c_uint) -> c_int;

fn af_maxfilt(out: MutAfArray, input: AfArray, wlen: DimT, wwid: DimT, etype: c_uint) -> c_int;

fn af_gaussian_kernel(
out: MutAfArray,
rows: c_int,
cols: c_int,
sigma_r: c_double,
sigma_c: c_double,
) -> c_int;

fn af_color_space(out: MutAfArray, input: AfArray, tospace: c_uint, fromspace: c_uint)
-> c_int;

fn af_unwrap(
out: MutAfArray,
input: AfArray,
wx: DimT,
wy: DimT,
sx: DimT,
sy: DimT,
px: DimT,
py: DimT,
is_column: c_int,
) -> c_int;

fn af_wrap(
out: MutAfArray,
input: AfArray,
ox: DimT,
oy: DimT,
wx: DimT,
wy: DimT,
sx: DimT,
sy: DimT,
px: DimT,
py: DimT,
is_column: c_int,
) -> c_int;

fn af_sat(out: MutAfArray, input: AfArray) -> c_int;

fn af_ycbcr2rgb(out: MutAfArray, input: AfArray, stnd: c_int) -> c_int;
fn af_rgb2ycbcr(out: MutAfArray, input: AfArray, stnd: c_int) -> c_int;
fn af_is_image_io_available(out: *mut c_int) -> c_int;
fn af_transform_coordinates(out: MutAfArray, tf: AfArray, d0: c_float, d1: c_float) -> c_int;

fn af_moments(out: MutAfArray, input: AfArray, moment: c_int) -> c_int;
fn af_moments_all(out: *mut c_double, input: AfArray, moment: c_int) -> c_int;

fn af_canny(
out: MutAfArray,
input: AfArray,
thres_type: c_int,
low: c_float,
high: c_float,
swindow: c_uint,
is_fast: c_int,
) -> c_int;
fn af_anisotropic_diffusion(
out: MutAfArray,
input: AfArray,
dt: c_float,
K: c_float,
iters: c_uint,
fftype: c_int,
diff_kind: c_int,
) -> c_int;
fn af_confidence_cc(
out: MutAfArray,
input: AfArray,
seedx: AfArray,
seedy: AfArray,
multiplier: c_uint,
iterations: c_int,
seg_val: c_double,
) -> c_int;
fn af_iterative_deconv(
out: MutAfArray,
input: AfArray,
ker: AfArray,
iterations: c_uint,
rfactor: c_float,
algo: c_int,
) -> c_int;
fn af_inverse_deconv(
out: MutAfArray,
input: AfArray,
ker: AfArray,
gamma: c_float,
algo: c_int,
) -> c_int;
}

///
/// The gradients along the first and second dimensions are calculated simultaneously.
///
/// # Parameters
///
/// - input is the input Array
///
/// # Return Values
///
/// A tuple of Arrays.
///
/// The first Array is dx which is the gradient along the 1st dimension.
///
/// The second Array is dy which is the gradient along the 2nd dimension.
#[allow(unused_mut)]
pub fn gradient<T>(input: &Array<T>) -> (Array<T>, Array<T>)
where
T: HasAfEnum + FloatingPoint,
{
let mut dx: i64 = 0;
let mut dy: i64 = 0;
unsafe {
&mut dx as MutAfArray,
&mut dy as MutAfArray,
input.get() as AfArray,
);
HANDLE_ERROR(AfError::from(err_val));
}
(dx.into(), dy.into())
}

///
/// Only, Images with 8/16/32 bits per channel can be loaded using this function.
///
/// # Parameters
///
/// - filename is aboslute path of the image to be loaded.
/// - is_color indicates if the image file at given path is color or gray scale.
///
/// # Return Arrays
///
/// An Array with pixel values loaded from the image
#[allow(unused_mut)]
#[allow(clippy::match_wild_err_arm)]
pub fn load_image<T>(filename: String, is_color: bool) -> Array<T>
where
T: HasAfEnum + RealNumber,
{
let cstr_param = match CString::new(filename) {
Ok(cstr) => cstr,
Err(_) => panic!("CString creation from input filename failed"),
};
let trgt_type = T::get_af_dtype();
let mut img: i64 = 0;
unsafe {
let mut temp: i64 = 0;
&mut temp as MutAfArray,
cstr_param.as_ptr(),
is_color as c_int,
);
HANDLE_ERROR(AfError::from(err1));
let err2 = af_cast(&mut img as MutAfArray, temp as AfArray, trgt_type as c_uint);
HANDLE_ERROR(AfError::from(err2));
}
img.into()
}

/// Load Image into Array in it's native type
///
/// This load image function allows you to load images as U8, U16 or F32
/// depending on the type of input image as shown by the table below.
///
///  Bits per Color (Gray/RGB/RGBA Bits Per Pixel) | Array Type  | Range
/// -----------------------------------------------|-------------|---------------
///   8 ( 8/24/32  BPP)                            | u8          | 0 - 255
///  16 (16/48/64  BPP)                            | u16         | 0 - 65535
///  32 (32/96/128 BPP)                            | f32         | 0 - 1
///
/// # Parameters
///
/// - filename is name of file to be loaded
///
/// # Return Arrays
///
/// An Array with pixel values loaded from the image
#[allow(unused_mut)]
#[allow(clippy::match_wild_err_arm)]
pub fn load_image_native<T>(filename: String) -> Array<T>
where
T: HasAfEnum + ImageNativeType,
{
let cstr_param = match CString::new(filename) {
Ok(cstr) => cstr,
Err(_) => panic!("CString creation from input filename failed"),
};
let trgt_type = T::get_af_dtype();
let mut img: i64 = 0;
unsafe {
let mut temp: i64 = 0;
let err1 = af_load_image_native(&mut temp as MutAfArray, cstr_param.as_ptr());
HANDLE_ERROR(AfError::from(err1));
let err2 = af_cast(&mut img as MutAfArray, temp as AfArray, trgt_type as c_uint);
HANDLE_ERROR(AfError::from(err2));
}
img.into()
}

/// Save an Array to an image file
///
/// # Parameters
///
/// - filename is the abolute path(includes filename) at which input Array is going to be saved
/// - input is the Array to be stored into the image file
#[allow(unused_mut)]
#[allow(clippy::match_wild_err_arm)]
pub fn save_image<T>(filename: String, input: &Array<T>)
where
T: HasAfEnum + RealNumber,
{
let cstr_param = match CString::new(filename) {
Ok(cstr) => cstr,
Err(_) => panic!("CString creation from input filename failed"),
};
unsafe {
let err_val = af_save_image(cstr_param.as_ptr(), input.get() as AfArray);
HANDLE_ERROR(AfError::from(err_val));
}
}

/// Save an Array without modifications to an image file
///
/// This function only accepts U8, U16, F32 arrays. These arrays are saved to images without any modifications. You must also note that note all image type support 16 or 32 bit images. The best options for 16 bit images are PNG, PPM and TIFF. The best option for 32 bit images is TIFF. These allow lossless storage.
///
/// The images stored have the following properties:
///
///  Array Type  | Bits per Color (Gray/RGB/RGBA Bits Per Pixel) | Range
/// -------------|-----------------------------------------------|---------------
///  U8          |  8 ( 8/24/32  BPP)                            | 0 - 255
///  U16         | 16 (16/48/64  BPP)                            | 0 - 65535
///  F32         | 32 (32/96/128 BPP)                            | 0 - 1
///
/// # Parameters
///
/// - filename is name of file to be saved
/// - input is the Array to be saved. Should be U8 for saving 8-bit image, U16 for 16-bit image, and F32 for 32-bit image.
#[allow(unused_mut)]
#[allow(clippy::match_wild_err_arm)]
pub fn save_image_native<T>(filename: String, input: &Array<T>)
where
T: HasAfEnum + ImageNativeType,
{
let cstr_param = match CString::new(filename) {
Ok(cstr) => cstr,
Err(_) => panic!("CString creation from input filename failed"),
};
unsafe {
let err_val = af_save_image_native(cstr_param.as_ptr(), input.get() as AfArray);
HANDLE_ERROR(AfError::from(err_val));
}
}

/// Resize an Image
///
/// Resizing an input image can be done using either NEAREST or BILINEAR interpolations.
/// Nearest interpolation will pick the nearest value to the location, whereas bilinear
/// interpolation will do a weighted interpolation for calculate the new size.
///
/// This function does not differentiate between images and data. As long as the array is defined
/// and the output dimensions are not 0, it will resize any type or size of array.
///
/// # Parameters
///
/// - input is the image to be resized
/// - odim0 is the output height
/// - odim1 is the output width
/// - method indicates which interpolation method to use for resizing. It uses enum
/// [InterpType](./enum.InterpType.html) to identify the interpolation method.
///
/// # Return Values
///
/// Resized Array
#[allow(unused_mut)]
pub fn resize<T: HasAfEnum>(
input: &Array<T>,
odim0: i64,
odim1: i64,
method: InterpType,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_resize(
&mut temp as MutAfArray,
input.get() as AfArray,
odim0 as DimT,
odim1 as DimT,
method as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Transform(Affine) an Image
///
/// The transform function uses an affine transform matrix to tranform an input image into a new
/// one. The transform matrix tf is a 3x2 matrix of type float. The matrix operation is applied to each
/// location (x, y) that is then transformed to (x', y') of the new array. Hence the transformation
/// is an element-wise operation.
///
/// The operation is as below: tf = [r00 r10 r01 r11 t0 t1]
///
/// x' = x * r00 + y * r01 + t0; y' = x * r10 + y * r11 + t1;
///
/// Interpolation types of NEAREST, LINEAR, BILINEAR and CUBIC are allowed. Affine transforms can be used for various purposes. [translate](./fn.translate.html), [scale](./fn.scale.html) and [skew](./fn.skew.html) are
/// specializations of the transform function.
///
/// This function can also handle batch operations.
///
/// # Parameters
///
/// - input is the image to be resized
/// - trans is the transformation matrix to be used for image transformation
/// - odim0 is the output height
/// - odim1 is the output width
/// - method indicates which interpolation method to use for resizing. It uses enum
/// [InterpType](./enum.InterpType.html) to identify the interpolation method.
/// - is_inverse indicates if to apply inverse/forward transform
///
/// # Return Values
///
/// Transformed Array
#[allow(unused_mut)]
pub fn transform<T: HasAfEnum>(
input: &Array<T>,
trans: &Array<f32>,
odim0: i64,
odim1: i64,
method: InterpType,
is_inverse: bool,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_transform(
&mut temp as MutAfArray,
input.get() as AfArray,
trans.get() as AfArray,
odim0 as DimT,
odim1 as DimT,
method as c_uint,
is_inverse as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Rotate an Image
///
/// Rotating an input image can be done using either NEAREST or BILINEAR interpolations.
/// Nearest interpolation will pick the nearest value to the location, whereas bilinear
/// interpolation will do a weighted interpolation for calculate the new size.
///
/// This function does not differentiate between images and data. As long as the array is defined,
/// it will rotate any type or size of array.
///
/// The crop option allows you to choose whether to resize the image. If crop is set to false, ie.
/// the entire rotated image will be a part of the array and the new array size will be greater
/// than or equal to the input array size. If crop is set to true, then the new array size is same
/// as the input array size and the data that falls outside the boundaries of the array is
///
/// Any location of the rotated array that does not map to a location of the input array is set to
/// 0.
///
/// # Parameters
///
/// - input is the input image
/// - theta is the amount of angle (in radians) image should be rotated
/// - crop indicates if the rotated image has to be cropped to original size
/// - method indicates which interpolation method to use for rotating the image. It uses enum
/// [InterpType](./enum.InterpType.html) to identify the interpolation method.
///
/// # Return Values
///
/// Rotated Array
#[allow(unused_mut)]
pub fn rotate<T: HasAfEnum>(
input: &Array<T>,
theta: f64,
crop: bool,
method: InterpType,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_rotate(
&mut temp as MutAfArray,
input.get() as AfArray,
theta as c_float,
crop as c_int,
method as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Translate an Image
///
/// Translating an image is moving it along 1st and 2nd dimensions by trans0 and trans1. Positive
/// values of these will move the data towards negative x and negative y whereas negative values of
/// these will move the positive right and positive down. See the example below for more.
///
/// To specify an output dimension, use the odim0 and odim1 for dim0 and dim1 respectively. The
/// size of 2rd and 3rd dimension is same as input. If odim0 and odim1 and not defined, then the
/// output dimensions are same as the input dimensions and the data out of bounds will be
///
/// All new values that do not map to a location of the input array are set to 0.
///
/// Translate is a special case of the [transform](./fn.transform.html) function.
///
/// # Parameters
///
/// - input is input image
/// - trans0 is amount by which the first dimension is translated
/// - trans1 is amount by which the second dimension is translated
/// - odim0 is the first output dimension
/// - odim1 is the second output dimension
/// - method is the interpolation type (Nearest by default)
///
/// # Return Values
///
/// Translated Image(Array).
#[allow(unused_mut)]
pub fn translate<T: HasAfEnum>(
input: &Array<T>,
trans0: f32,
trans1: f32,
odim0: i64,
odim1: i64,
method: InterpType,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_translate(
&mut temp as MutAfArray,
input.get() as AfArray,
trans0 as c_float,
trans1 as c_float,
odim0 as DimT,
odim1 as DimT,
method as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Scale an Image
///
/// Scale is the same functionality as [resize](./fn.resize.html) except that the scale function uses the transform kernels. The other difference is that scale does not set boundary values to be the boundary of the input array. Instead these are set to 0.
///
/// Scale is a special case of the [transform](./fn.transform.html) function.
///
/// # Parameters
///
/// - input is input image
/// - trans0 is amount by which the first dimension is translated
/// - trans1 is amount by which the second dimension is translated
/// - odim0 is the first output dimension
/// - odim1 is the second output dimension
/// - method is the interpolation type (Nearest by default)
///
/// # Return Values
///
/// Translated Image(Array).
#[allow(unused_mut)]
pub fn scale<T: HasAfEnum>(
input: &Array<T>,
scale0: f32,
scale1: f32,
odim0: i64,
odim1: i64,
method: InterpType,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_scale(
&mut temp as MutAfArray,
input.get() as AfArray,
scale0 as c_float,
scale1 as c_float,
odim0 as DimT,
odim1 as DimT,
method as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Skew an image
///
/// Skew function skews the input array along dim0 by skew0 and along dim1 by skew1. The skew
/// areguments are in radians. Skewing the data means the data remains parallel along 1 dimensions
/// but the other dimensions gets moved along based on the angle. If both skew0 and skew1 are
/// specified, then the data will be skewed along both directions. Explicit output dimensions
/// can be specified using odim0 and odim1. All new values that do not map to a location of the input array are set to 0.
///
/// Skew is a special case of the [transform](./fn.transform.html) function.
///
/// # Parameters
///
/// - input is the image to be skewed
/// - skew0 is the factor by which data is skewed along first dimension
/// - skew1 is the factor by which data is skewed along second dimension
/// - odim0 is the output length along first dimension
/// - odim1 is the output length along second dimension
/// - method indicates which interpolation method to use for rotating the image. It uses enum
/// [InterpType](./enum.InterpType.html) to identify the interpolation method.
/// - is_inverse indicates if to apply inverse/forward transform
///
/// # Return Values
///
/// Skewed Image
#[allow(unused_mut)]
pub fn skew<T: HasAfEnum>(
input: &Array<T>,
skew0: f32,
skew1: f32,
odim0: i64,
odim1: i64,
method: InterpType,
is_inverse: bool,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_skew(
&mut temp as MutAfArray,
input.get() as AfArray,
skew0 as c_float,
skew1 as c_float,
odim0 as DimT,
odim1 as DimT,
method as c_uint,
is_inverse as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Compute Histogram of an Array
///
/// A histogram is a representation of the distribution of given data. This representation is
/// essentially a graph consisting of the data range or domain on one axis and frequency of
/// occurence on the other axis. All the data in the domain is counted in the appropriate bin. The
/// total number of elements belonging to each bin is known as the bin's frequency.
///
/// The regular histogram function creates bins of equal size between the minimum and maximum of
/// the input data (min and max are calculated internally). The histogram min-max function takes
/// input parameters minimum and maximum, and divides the bins into equal sizes within the range
/// specified by min and max parameters. All values less than min in the data range are placed in
/// the first (min) bin and all values greater than max will be placed in the last (max) bin.
///
/// # Parameters
///
/// - input is the Array whose histogram has to be computed
/// - nbins is the number bins the input data has to be categorized into.
/// - minval is the minimum value of bin ordering
/// - maxval is the maximum value of bin ordering
///
/// # Return Values
///
/// Histogram of input Array
#[allow(unused_mut)]
pub fn histogram<T>(input: &Array<T>, nbins: u32, minval: f64, maxval: f64) -> Array<u32>
where
T: HasAfEnum + RealNumber,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_histogram(
&mut temp as MutAfArray,
input.get() as AfArray,
nbins as c_uint,
minval as c_double,
maxval as c_double,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Dilate an Image
///
/// The dilation function takes two pieces of data as inputs. The first is the input image to be
/// morphed, and the second is the mask indicating the neighborhood around each pixel to match.
///
/// In dilation, for each pixel, the mask is centered at the pixel. If the center pixel of the mask
/// matches the corresponding pixel on the image, then the mask is accepted. If the center pixels
/// do not matches, then the mask is ignored and no changes are made.
///
/// For further reference, see [here](https://en.wikipedia.org/wiki/Dilation_(morphology)).
///
/// # Parameters
///
/// - input is the input image
/// - mask is the morphological operation mask
///
/// # Return Values
///
/// Dilated Image(Array)
#[allow(unused_mut)]
pub fn dilate<T>(input: &Array<T>, mask: &Array<T>) -> Array<T>
where
T: HasAfEnum + ImageFilterType,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_dilate(
&mut temp as MutAfArray,
input.get() as AfArray,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Erode an Image
///
/// The erosion function is a morphological transformation on an image that requires two inputs.
/// The first is the image to be morphed, and the second is the mask indicating neighborhood that
/// must be white in order to preserve each pixel.
///
/// In erode, for each pixel, the mask is centered at the pixel. If each pixel of the mask matches
/// the corresponding pixel on the image, then no change is made. If there is at least one
/// mismatch, then pixels are changed to the background color (black).
///
/// For further reference, see [here](https://en.wikipedia.org/wiki/Erosion_(morphology)).
///
/// # Parameters
///
/// - input is the input image
/// - mask is the morphological operation mask
///
/// # Return Values
///
/// Eroded Image(Array)
#[allow(unused_mut)]
pub fn erode<T>(input: &Array<T>, mask: &Array<T>) -> Array<T>
where
T: HasAfEnum + ImageFilterType,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_erode(
&mut temp as MutAfArray,
input.get() as AfArray,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Dilate a Volume
///
/// Dilation for a volume is similar to the way dilation works on an image. Only difference is that
/// the masking operation is performed on a volume instead of a rectangular region.
///
/// # Parameters
///
/// - input is the input volume
/// - mask is the morphological operation mask
///
/// # Return Values
///
/// Dilated Volume(Array)
#[allow(unused_mut)]
pub fn dilate3<T>(input: &Array<T>, mask: &Array<T>) -> Array<T>
where
T: HasAfEnum + ImageFilterType,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_dilate3(
&mut temp as MutAfArray,
input.get() as AfArray,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Erode a Volume
///
/// Erosion for a volume is similar to the way erosion works on an image. Only difference is that
/// the masking operation is performed on a volume instead of a rectangular region.
///
/// # Parameters
///
/// - input is the input volume
/// - mask is the morphological operation mask
///
/// # Return Values
///
/// Eroded Volume(Array)
#[allow(unused_mut)]
pub fn erode3<T>(input: &Array<T>, mask: &Array<T>) -> Array<T>
where
T: HasAfEnum + ImageFilterType,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_erode3(
&mut temp as MutAfArray,
input.get() as AfArray,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Bilateral Filter.
///
/// A bilateral filter is a edge-preserving filter that reduces noise in an image. The intensity of
/// each pixel is replaced by a weighted average of the intensities of nearby pixels. The weights
/// follow a Gaussian distribution and depend on the distance as well as the color distance.
///
/// The bilateral filter requires the size of the filter (in pixels) and the upper bound on color
/// values, N, where pixel values range from 0–N inclusively.
///
/// # Parameters
///
/// - input array is the input image
/// - spatial_sigma is the spatial variance parameter that decides the filter window
/// - chromatic_sigma is the chromatic variance parameter
/// - iscolor indicates if the input is color image or grayscale
///
/// # Return Values
///
/// Filtered Image - Array
#[allow(unused_mut)]
pub fn bilateral<T>(
input: &Array<T>,
spatial_sigma: f32,
chromatic_sigma: f32,
iscolor: bool,
) -> Array<T::AbsOutType>
where
T: HasAfEnum + ImageFilterType,
T::AbsOutType: HasAfEnum,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_bilateral(
&mut temp as MutAfArray,
input.get() as AfArray,
spatial_sigma as c_float,
chromatic_sigma as c_float,
iscolor as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Meanshift Filter.
///
/// A meanshift filter is an edge-preserving smoothing filter commonly used in object tracking and
/// image segmentation.
///
/// This filter replaces each pixel in the image with the mean of the values within a given given
/// color and spatial radius. The meanshift filter is an iterative algorithm that continues until a
/// maxium number of iterations is met or until the value of the means no longer changes.
///
/// # Parameters
///
/// - input array is the input image
/// - spatial_sigma is the spatial variance parameter that decides the filter window
/// - chromatic_sigma is the chromatic variance parameter
/// - iter is the number of iterations filter operation is performed
/// - iscolor indicates if the input is color image or grayscale
///
/// # Return Values
///
/// Filtered Image - Array
#[allow(unused_mut)]
pub fn mean_shift<T>(
input: &Array<T>,
spatial_sigma: f32,
chromatic_sigma: f32,
iter: u32,
iscolor: bool,
) -> Array<T>
where
T: HasAfEnum + RealNumber,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_mean_shift(
&mut temp as MutAfArray,
input.get() as AfArray,
spatial_sigma as c_float,
chromatic_sigma as c_float,
iter as c_uint,
iscolor as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

macro_rules! filt_func_def {
($doc_str: expr,$fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str]
///
///# Parameters
///
/// - input is the input image(Array)
/// - wlen is the horizontal length of the filter
/// - hlen is the vertical length of the filter
/// - etype is enum of type [BorderType](./enum.BorderType.html)
///
///# Return Values
///
/// An Array with filtered image data.
#[allow(unused_mut)]
pub fn $fn_name<T>(input: &Array<T>, wlen: u64, wwid: u64, etype: BorderType) -> Array<T> where T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { let err_val =$ffi_name(
&mut temp as MutAfArray,
input.get() as AfArray,
wlen as DimT,
wwid as DimT,
etype as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}
};
}

filt_func_def!("Median filter", medfilt, af_medfilt);
filt_func_def!(
"Box filter with minimum as box operation",
minfilt,
af_minfilt
);
filt_func_def!(
"Box filter with maximum as box operation",
maxfilt,
af_maxfilt
);

/// Creates a Gaussian Kernel.
///
/// This function creates a kernel of a specified size that contains a Gaussian distribution. This
/// distribution is normalized to one. This is most commonly used when performing a Gaussian blur
/// on an image. The function takes two sets of arguments, the size of the kernel (width and height
/// in pixels) and the sigma parameters (for row and column) which effect the distribution of the
/// weights in the y and x directions, respectively.
///
/// Changing sigma causes the weights in each direction to vary. Sigma is calculated internally as
/// (0.25 * rows + 0.75) for rows and similarly for columns.
///
/// # Parameters
///
/// - rows is number of rows of kernel
/// - cols is number of cols of kernel
/// - sigma_r is standard deviation of rows
/// - sigma_c is standard deviation of cols
///
/// # Return Values
///
/// An Array with gaussian kernel values
#[allow(unused_mut)]
pub fn gaussian_kernel(rows: i32, cols: i32, sigma_r: f64, sigma_c: f64) -> Array<f32> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_gaussian_kernel(
&mut temp as MutAfArray,
rows as c_int,
cols as c_int,
sigma_r as c_double,
sigma_c as c_double,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Color space conversion
///
/// Following are the supported conversions
///
/// - RGB => GRAY
/// - GRAY => RGB
/// - RGB => HSV
/// - HSV => RGB
/// - YCbCr => RGB
/// - RGB => YCbCr
///
/// RGB (Red, Green, Blue) is the most common format used in computer imaging. RGB stores
/// individual values for red, green and blue, and hence the 3 values per pixel. A combination of
/// these three values produces the gamut of unique colors.
///
/// HSV (Hue, Saturation, Value), also known as HSB (hue, saturation, brightness), is often used by
/// artists because it is more natural to think about a color in terms of hue and saturation than
/// in terms of additive or subtractive color components (as in RGB). HSV is a transformation of
/// RGB colorspace; its components and colorimetry are relative to the RGB colorspace from which it
/// was derived. Like RGB, HSV also uses 3 values per pixel.
///
/// GRAY is a single channel color space where pixel value ranges from 0 to 1. Zero represents
/// black, one represent white and any value between zero & one is a gray value
///
/// # Parameters
///
/// - input is the input image
/// - tospace is the target color space. Takes values of [ColorSpace](./enum.ColorSpace.html)
/// - fromspace is the source image color space. Takes values of
/// [ColorSpace](./enum.ColorSpace.html)
///
/// # Return Values
///
/// An Array with input image values in target color space
#[allow(unused_mut)]
pub fn color_space<T>(input: &Array<T>, tospace: ColorSpace, fromspace: ColorSpace) -> Array<T>
where
T: HasAfEnum + RealNumber,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_color_space(
&mut temp as MutAfArray,
input.get() as AfArray,
tospace as c_uint,
fromspace as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Find blobs in given image.
///
/// Given a binary image (with zero representing background pixels), regions computes a floating
/// point image where each connected component is labeled from 1 to N, the total number of
/// components in the image.
///
/// A component is defined as one or more nonzero pixels that are connected by the specified
/// connectivity (either [Connectivity::FOUR](./enum.Connectivity.html) or [Connectivity::EIGHT](./enum.Connectivity.html)) in two dimensions.
///
/// # Parameters
///
/// - input is the input image
/// - conn can take one of the values of [Connectivity](./enum.Connectivity.html)
///
/// # Return Values
///
/// Array with labels indicating different regions
#[allow(unused_mut)]
pub fn regions<OutType>(input: &Array<bool>, conn: Connectivity) -> Array<OutType>
where
OutType: HasAfEnum + RealNumber,
{
let otype = OutType::get_af_dtype();
let mut temp: i64 = 0;
unsafe {
let err_val = af_regions(
&mut temp as MutAfArray,
input.get() as AfArray,
conn as c_uint,
otype as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Sobel Operator
///
/// Sobel operators perform a 2-D spatial gradient measurement on an image to emphasize the regions
/// of high spatial frequency, namely edges. A more in depth discussion on it can be found [here](https://en.wikipedia.org/wiki/Sobel_operator).
///
/// # Parameters
///
/// - input is the input image
/// - ker_size is the kernel size of sobel operator
///
/// # Return Values
///
/// A tuple of Arrays.
///
/// The first Array has derivatives along horizontal direction
///
/// The second Array has derivatives along vertical direction
#[allow(unused_mut)]
pub fn sobel<T>(input: &Array<T>, ker_size: u32) -> (Array<T::SobelOutType>, Array<T::SobelOutType>)
where
T: HasAfEnum + ImageFilterType,
T::SobelOutType: HasAfEnum,
{
let mut dx: i64 = 0;
let mut dy: i64 = 0;
unsafe {
let err_val = af_sobel_operator(
&mut dx as MutAfArray,
&mut dy as MutAfArray,
input.get() as AfArray,
ker_size as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
(dx.into(), dy.into())
}

/// Histogram Equalization
///
/// # Parameters
///
/// - input is the input Array to be equalized
/// - hist is the Array to be used for equalizing input
///
/// # Return Values
/// Equalized Array
#[allow(unused_mut)]
pub fn hist_equal<T>(input: &Array<T>, hist: &Array<u32>) -> Array<T>
where
T: HasAfEnum + RealNumber,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_hist_equal(
&mut temp as MutAfArray,
input.get() as AfArray,
hist.get() as AfArray,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

macro_rules! grayrgb_func_def {
($doc_str: expr,$fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str]
///
///# Parameters
///
/// - r is fraction of red channel to appear in output
/// - g is fraction of green channel to appear in output
/// - b is fraction of blue channel to appear in output
///
///#Return Values
///
///An Array with image data in target color space
#[allow(unused_mut)]
pub fn $fn_name<T>(input: &Array<T>, r: f32, g: f32, b: f32) -> Array<T> where T: HasAfEnum + GrayRGBConvertible, { let mut temp: i64 = 0; unsafe { let err_val =$ffi_name(
&mut temp as MutAfArray,
input.get() as AfArray,
r as c_float,
g as c_float,
b as c_float,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}
};
}

grayrgb_func_def!("Color(RGB) to Grayscale conversion", rgb2gray, af_rgb2gray);
grayrgb_func_def!("Grayscale to Color(RGB) conversion", gray2rgb, af_gray2rgb);

macro_rules! hsvrgb_func_def {
($doc_str: expr,$fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str]
#[allow(unused_mut)]
pub fn $fn_name<T>(input: &Array<T>) -> Array<T> where T: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { let err_val =$ffi_name(&mut temp as MutAfArray, input.get() as AfArray);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}
};
}

hsvrgb_func_def!("HSV to RGB color space conversion", hsv2rgb, af_hsv2rgb);
hsvrgb_func_def!("RGB to HSV color space conversion", rgb2hsv, af_rgb2hsv);

/// Generate an array with image windows as columns
///
/// unwrap takes in an input image along with the window sizes wx and wy, strides sx and sy, and
/// padding px and py. This function then generates a matrix where each windows is an independent
/// column.
///
/// The number of columns (rows if is_column is true) in the output array are govenered by the
/// number of windows that can be fit along x and y directions. Padding is applied along all 4
/// sides of the matrix with px defining the height of the padding along dim 0 and py defining the
/// width of the padding along dim 1.
///
/// The first column window is always at the top left corner of the input including padding. If a
/// window cannot fit before the end of the matrix + padding, it is skipped from the generated
/// matrix.
///
/// Padding can take a maximum value of window - 1 repectively for x and y.
///
/// For multiple channels (3rd and 4th dimension), the generated matrix contains the same number of
/// channels as the input matrix. Each channel of the output matrix corresponds to the same channel
/// of the input.
///
/// # Parameters
///
/// - input is the input image
/// - wx is the block window size along 0th-dimension between [1, input.dims[0] + px]
/// - wy is the block window size along 1st-dimension between [1, input.dims[1] + py]
/// - sx is the stride along 0th-dimension
/// - sy is the stride along 1st-dimension
/// - px is the padding along 0th-dimension between [0, wx). Padding is applied both before and after.
/// - py is the padding along 1st-dimension between [0, wy). Padding is applied both before and after.
/// - is_column specifies the layout for the unwrapped patch. If is_column is false, the unrapped patch is laid out as a row.
///
/// # Return Values
///
/// An Array with image windows as columns
///
/// # Examples
///
/// text
/// A [5 5 1 1]
/// 10 15 20 25 30
/// 11 16 21 26 31
/// 12 17 22 27 32
/// 13 18 23 28 33
/// 14 19 24 29 34
///
/// // Window 3x3, strides 1x1, padding 0x0
/// unwrap(A, 3, 3, 1, 1, 0, 0, False) [9 9 1 1]
/// 10 11 12 15 16 17 20 21 22
/// 11 12 13 16 17 18 21 22 23
/// 12 13 14 17 18 19 22 23 24
/// 15 16 17 20 21 22 25 26 27
/// 16 17 18 21 22 23 26 27 28
/// 17 18 19 22 23 24 27 28 29
/// 20 21 22 25 26 27 30 31 32
/// 21 22 23 26 27 28 31 32 33
/// 22 23 24 27 28 29 32 33 34
///
/// // Window 3x3, strides 1x1, padding 1x1
/// unwrap(A, 3, 3, 1, 1, 1, 1, False) [9 25 1 1]
///  0  0  0  0  0  0 10 11 12 13  0 15 16 17 18  0 20 21 22 23  0 25 26 27 28
///  0  0  0  0  0 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
///  0  0  0  0  0 11 12 13 14  0 16 17 18 19  0 21 22 23 24  0 26 27 28 29  0
///  0 10 11 12 13  0 15 16 17 18  0 20 21 22 23  0 25 26 27 28  0 30 31 32 33
/// 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
/// 11 12 13 14  0 16 17 18 19  0 21 22 23 24  0 26 27 28 29  0 31 32 33 34  0
///  0 15 16 17 18  0 20 21 22 23  0 25 26 27 28  0 30 31 32 33  0  0  0  0  0
/// 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  0  0  0  0  0
/// 16 17 18 19  0 21 22 23 24  0 26 27 28 29  0 31 32 33 34  0  0  0  0  0  0
/// 
#[allow(clippy::too_many_arguments)]
pub fn unwrap<T: HasAfEnum>(
input: &Array<T>,
wx: i64,
wy: i64,
sx: i64,
sy: i64,
px: i64,
py: i64,
is_column: bool,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_unwrap(
&mut temp as MutAfArray,
input.get() as AfArray,
wx,
wy,
sx,
sy,
px,
py,
is_column as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Converts unwrapped image to an image
///
/// Wrap takes an unwrapped image (see unwrap()) and converts it back to an image.
///
/// The inputs to this function should be the same as the inputs used to generate the unwrapped
/// image.
///
/// # Parameters
///
/// - input is the output of unwrap function call
/// - ox is the 0th-dimension of output image
/// - oy is the 1st-dimension of output image
/// - wx is the block window size along 0th-dimension between
/// - wy is the block window size along 1st-dimension between
/// - sx is the stride along 0th-dimension
/// - sy is the stride along 1st-dimension
/// - px is the padding used along 0th-dimension between [0, wx).
/// - py is the padding used along 1st-dimension between [0, wy).
/// - is_column specifies the layout for the unwrapped patch. If is_column is false, the rows are treated as the patches
///
/// # Return Values
///
/// Image(Array) created from unwrapped Image(Array)
#[allow(clippy::too_many_arguments)]
pub fn wrap<T: HasAfEnum>(
input: &Array<T>,
ox: i64,
oy: i64,
wx: i64,
wy: i64,
sx: i64,
sy: i64,
px: i64,
py: i64,
is_column: bool,
) -> Array<T> {
let mut temp: i64 = 0;
unsafe {
let err_val = af_wrap(
&mut temp as MutAfArray,
input.get() as AfArray,
ox,
oy,
wx,
wy,
sx,
sy,
px,
py,
is_column as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Summed area table of an Image
///
/// # Parameters
///
/// - input is the input image
///
/// # Return Values
///
/// Summed area table (a.k.a Integral Image) of the input image.
pub fn sat<T>(input: &Array<T>) -> Array<T::AggregateOutType>
where
T: HasAfEnum + RealNumber,
T::AggregateOutType: HasAfEnum,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_sat(&mut temp as MutAfArray, input.get() as AfArray);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// RGB to YCbCr colorspace converter.
///
/// RGB (Red, Green, Blue) is the most common format used in computer imaging. RGB stores
/// individual values for red, green and blue, and hence the 3 values per pixel. A combination of
/// these three values produces the gamut of unique colors.
///
/// YCbCr is a family of color spaces used as a part of the color image pipeline in video and
/// digital photography systems where Y is luma component and Cb & Cr are the blue-difference and
/// red-difference chroma components.
///
/// Input array to this function should be of real data in the range [0,1].
///
/// # Parameters
///
/// - input is the input image in RGB color space
/// - standard is the target color space - [YCbCr standard](./enum.YCCStd.html)
///
/// # Return Values
///
/// Image(Array) in YCbCr color space
pub fn rgb2ycbcr<T>(input: &Array<T>, standard: YCCStd) -> Array<T>
where
T: HasAfEnum + RealFloating,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_rgb2ycbcr(
&mut temp as MutAfArray,
input.get() as AfArray,
standard as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// YCbCr to RGB colorspace converter.
///
/// YCbCr is a family of color spaces used as a part of the color image pipeline in video and
/// digital photography systems where Y is luma component and Cb & Cr are the blue-difference and
/// red-difference chroma components.
///
/// RGB (Red, Green, Blue) is the most common format used in computer imaging. RGB stores
/// individual values for red, green and blue, and hence the 3 values per pixel. A combination of
/// these three values produces the gamut of unique colors.
///
/// Input array to this function should be of real data with the following range in their
/// respective channels.
///
/// - Y  −> [16,219]
/// - Cb −> [16,240]
/// - Cr −> [16,240]
///
/// # Parameters
///
/// - input is the input image in YCbCr color space
/// - standard is the [YCbCr standard](./enum.YCCStd.html) in which input image color space is
/// present.
///
/// # Return Values
///
/// Image(Array) in RGB color space
pub fn ycbcr2rgb<T>(input: &Array<T>, standard: YCCStd) -> Array<T>
where
T: HasAfEnum + RealFloating,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_ycbcr2rgb(
&mut temp as MutAfArray,
input.get() as AfArray,
standard as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Function to check if Image I/O is available
///
/// # Parameters
///
/// None
///
/// # Return Values
///
/// Return a boolean indicating if ArrayFire was compiled with Image I/O support
pub fn is_imageio_available() -> bool {
let mut temp: i32 = 0;
unsafe {
af_is_image_io_available(&mut temp as *mut c_int);
}
temp > 0 // Return boolean flag
}

/// Transform input coordinates
///
/// The transform function uses a perspective transform matrix to transform input coordinates
/// (given as two dimensions) into a coordinates matrix.
///
/// The output is a 4x2 matrix, indicating the coordinates of the 4 bidimensional transformed
/// points.
///
/// # Parameters
///
/// - tf is the transformation matrix
/// - d0 is the first input dimension
/// - d1 is the second input dimension
///
/// # Return Values
///
/// Transformed coordinates
pub fn transform_coords<T>(tf: &Array<T>, d0: f32, d1: f32) -> Array<T>
where
T: HasAfEnum + RealFloating,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_transform_coordinates(
&mut temp as MutAfArray,
tf.get() as AfArray,
d0 as c_float,
d1 as c_float,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Find Image moments
///
/// # Parameters
///
/// - input is the input image
/// - moment is the type of moment to be computed, takes a value of
/// [enum](./enum.MomentType.html)
///
/// # Return Values
///
/// Moments Array
pub fn moments<T>(input: &Array<T>, moment: MomentType) -> Array<f32>
where
T: HasAfEnum + MomentsComputable,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_moments(
&mut temp as MutAfArray,
input.get() as AfArray,
moment as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Find Image moment for whole image
///
/// # Parameters
///
/// - input is the input image
/// - moment is the type of moment to be computed, takes a value of
/// [enum](./enum.MomentType.html)
///
/// # Return Values
///
/// Moment value of the whole image
pub fn moments_all<T>(input: &Array<T>, moment: MomentType) -> f64
where
T: HasAfEnum + MomentsComputable,
{
let mut temp: f64 = 0.0;
unsafe {
let err_val = af_moments_all(
&mut temp as *mut c_double,
input.get() as AfArray,
moment as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp
}

/// One dimensional median filter on image
///
/// # Parameters
///
///  - input is the input image(Array)
///  - wlen is the horizontal length of the filter
///  - etype is enum of type [BorderType](./enum.BorderType.html)
///
/// # Return Values
///
/// An Array with filtered image data.
pub fn medfilt1<T>(input: &Array<T>, wlen: u64, etype: BorderType) -> Array<T>
where
T: HasAfEnum + ImageFilterType,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_medfilt1(
&mut temp as MutAfArray,
input.get() as AfArray,
wlen as DimT,
etype as c_uint,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Canny edge detection operator
///
/// The Canny edge detector is an edge detection operator that uses a multi-stage algorithm to detect a wide range of edges in images. A more in depth discussion on it can be found [here](https://en.wikipedia.org/wiki/Canny_edge_detector).
///
/// # Parameters
///
/// - input is the input image
/// - threshold_type helps determine if user set high threshold is to be used or not. It can take values defined by the enum [CannyThresholdType](./enum.CannyThresholdType.html)
/// - low is the lower threshold % of the maximum or auto-derived high
/// - hight is the higher threshold % of maximum value in gradient image used in hysteresis procedure. This value is ignored if [CannyThresholdType::OTSU](./enum.CannyThresholdType.html) is chosen.
/// - sobel_window is the window size of sobel kernel for computing gradient direction and magnitude.
/// - is_fast indicates if L<SUB>1</SUB> norm(faster but less accurate) is used to compute image gradient magnitude instead of L<SUB>2</SUB> norm.
///
/// # Return Values
///
/// An Array of binary type [DType::B8](./enum.DType.html) indicating edges(All pixels with
/// non-zero values are edges).
pub fn canny<T>(
input: &Array<T>,
threshold_type: CannyThresholdType,
low: f32,
hight: f32,
sobel_window: u32,
is_fast: bool,
) -> Array<bool>
where
T: HasAfEnum + EdgeComputable,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_canny(
&mut temp as MutAfArray,
input.get() as AfArray,
threshold_type as c_int,
low as c_float,
hight as c_float,
sobel_window as c_uint,
is_fast as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Anisotropic smoothing filter
///
/// Anisotropic diffusion algorithm aims at removing noise in the images
/// while preserving important features such as edges. The algorithm
/// essentially creates a scale space representation of the original
/// image, where image from previous step is used to create a new version
/// of blurred image using the diffusion process. Standard isotropic diffusion
/// methods such as gaussian blur, doesn't take into account the local
/// content(smaller neighborhood of current processing pixel) while removing
/// noise. Anisotropic diffusion uses the flux equations given below to
/// achieve that. Flux equation is the formula used by the diffusion process
/// to determine how much a pixel in neighborhood should contribute to
/// the blurring operation being done at the current pixel at a given iteration.
///
/// The flux function can be either exponential or quadratic.
///
/// <table>
/// <caption id="multi row">Available Flux Functions</caption>
/// <tr>
///     <td align="center" style="vertical-align:middle;">
///     </td>
///     <td align="center">
///
///         \frac{1}{1 + (\frac{\| \nabla I\|}{K})^2}
///
///     </td>
/// </tr>
/// <tr>
///     <td align="center" style="vertical-align:middle;">
///       AF_FLUX_EXPONENTIAL
///     </td>
///     <td align="center">
///
///         \exp{-(\frac{\| \nabla I\|}{K})^2}
///
///     </td>
/// </tr>
/// </table>
///
/// Please be cautious using the time step parameter to the function.
/// Appropriate time steps for solving this type of p.d.e. depend on
/// the dimensionality of the image and the order of the equation.
/// Stable values for most 2D and 3D functions are 0.125 and 0.0625,
/// respectively. The time step values are automatically constrained
/// to the stable value.
///
/// Another input parameter to be cautious about is the conductance
/// parameter, lower values strongly preserve image features and
/// vice-versa. For human vision, this value ranges from 0.5 to 2.0.
///
/// # Parameters
///
/// - img is the noisy input image
/// - dt is the timestep for diffusion equation
/// - k is the conductance parameter for diffusion
/// - iters is the number of iterations diffusion is performed
/// - fftype dictates the type of flux flow and it is an
///    [enum](./enum.DiffusionEq.html)
/// - diff_kind dictates the type of diffusion and it is an
///   [enum](./enum.FluxFn.html)
///
/// # Return Values
///
/// Returns an anisotropically smoothed and noise-free image
///
/// ### References
///
///  - Pietro Perona and Jitendra Malik, Scale-space and edge detection
///    using anisotropic diffusion, IEEE Transactions on Pattern Analysis
///    Machine Intelligence, vol. 12, pp. 629-639, 1990.
///  - R. Whitaker and X. Xue. Variable-Conductance, Level-Set Curvature
///    for Image Denoising, International Conference on Image Processing,
///    2001 pp. 142-145, Vol.3.
pub fn anisotropic_diffusion<T>(
img: &Array<T>,
dt: f32,
k: f32,
iters: u32,
fftype: FluxFn,
diff_kind: DiffusionEq,
) -> Array<T::AbsOutType>
where
T: HasAfEnum + EdgeComputable,
T::AbsOutType: HasAfEnum,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_anisotropic_diffusion(
&mut temp as MutAfArray,
img.get() as AfArray,
dt as c_float,
k as c_float,
iters as c_uint,
fftype as c_int,
diff_kind as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Segment image based on similar pixel characteristics
///
/// This filter is similar to [regions](./fn.regions.html) with additional criteria for
/// segmentation. In regions, all connected pixels are considered to be a single component.
/// In this variation of connected components, pixels having similar pixel statistics of the
/// neighborhoods around a given set of seed points are grouped together.
///
/// The parameter radius determines the size of neighborhood around a seed point.
///
/// Mean and Variance are the pixel statistics that are computed across all neighborhoods around
/// the given set of seed points. The pixels which are connected to seed points and lie in the
/// confidence interval are grouped together. Given below is the confidence interval.
///
///
///     [\mu - \alpha * \sigma, \mu + \alpha * \sigma]
///
/// where
///
/// - $\mu$ is the mean of the pixels in the seed neighborhood
/// - $\sigma^2$ is the variance of the pixels in the seed neighborhood
/// - $\alpha$ is the multiplier used to control the width of the confidence interval.
///
/// This filter follows an iterative approach for fine tuning the segmentation. An initial
/// segmenetation followed by a finite number iterations of segmentations are performed.
/// The user provided parameter iterations is only a request and the algorithm can prempt
/// the execution if variance approaches zero. The initial segmentation uses the mean and
/// variance calculated from the neighborhoods of all the seed points. For subsequent
/// segmentations, all pixels in the previous segmentation are used to re-calculate the mean
/// and variance (as opposed to using the pixels in the neighborhood of the seed point).
///
/// # Parameters
///
/// - input is the input image
/// - seedx contains the x coordinates of seeds in image coordinates
/// - seedy contains the y coordinates of seeds in image coordinates
/// - radius is the neighborhood region to be considered around each seed point
/// - multiplier controls the threshold range computed from the mean and variance of seed point neighborhoods
/// - iterations is the number of times the segmentation in performed
/// - segmented_value is the value to which output array valid pixels are set to
///
/// # Return Values
///
/// Segmented(based on pixel characteristics) image(Array) with regions surrounding the seed points
pub fn confidence_cc<InOutType>(
input: &Array<InOutType>,
seedx: &Array<u32>,
seedy: &Array<u32>,
multiplier: u32,
iterations: u32,
segmented_val: f64,
) -> Array<InOutType>
where
InOutType: ConfidenceCCInput,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_confidence_cc(
&mut temp as MutAfArray,
input.get() as AfArray,
seedx.get() as AfArray,
seedy.get() as AfArray,
multiplier,
iterations as i32,
segmented_val,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Iterative Deconvolution
///
/// The following table shows the iteration update equations of the respective
/// deconvolution algorithms.
///
/// <table>
/// <tr><th>Algorithm</th><th>Update Equation</th></tr>
/// <tr>
///     <td>LandWeber</td>
///     <td>
///         $\hat{I}_{n} = \hat{I}_{n-1} + \alpha * P^T \otimes (I - P \otimes \hat{I}_{n-1})$
///     </td>
/// </tr>
/// <tr>
///   <td>Richardson-Lucy</td>
///   <td>
///     $\hat{I}_{n} = \hat{I}_{n-1} . ( \frac{I}{\hat{I}_{n-1} \otimes P} \otimes P^T )$
///   </td>
/// </tr>
/// </table>
///
/// where
///
/// - $I$ is the observed(input/blurred) image
/// - $P$ is the point spread function
/// - $P^T$ is the transpose of point spread function
/// - $\hat{I}_{n}$ is the current iteration's updated image estimate
/// - $\hat{I}_{n-1}$ is the previous iteration's image estimate
/// - $\alpha$ is the relaxation factor
/// - $\otimes$ indicates the convolution operator
///
/// The type of output Array from deconvolution will be of type f64 if
/// the input array type is f64. For other types, output type will be f32 type.
/// Should the caller want to save the image to disk or require the values of output
/// to be in a fixed range, that should be done by the caller explicitly.
pub fn iterative_deconv<T>(
input: &Array<T>,
kernel: &Array<f32>,
iterations: u32,
relaxation_factor: f32,
algo: IterativeDeconvAlgo,
) -> Array<T::AbsOutType>
where
T: DeconvInput,
T::AbsOutType: HasAfEnum,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_iterative_deconv(
&mut temp as MutAfArray,
input.get() as AfArray,
kernel.get() as AfArray,
iterations,
relaxation_factor,
algo as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}

/// Inverse deconvolution
///
/// This is a linear algorithm i.e. they are non-iterative in
/// nature and usually faster than iterative deconvolution algorithms.
///
/// Depending on the values passed on to algo of type enum [InverseDeconvAlgo](./enum.inverse_deconv_algo.html),
/// different equations are used to compute the final result.
///
/// #### Tikhonov's Deconvolution Method:
///
/// The update equation for this algorithm is as follows:
///
/// <div>
///
/// \hat{I}_{\omega} = \frac{ I_{\omega} * P^{*}_{\omega} } { |P_{\omega}|^2 + \gamma }
///
/// </div>
///
/// where
///
/// - $I_{\omega}$ is the observed(input/blurred) image in frequency domain
/// - $P_{\omega}$ is the point spread function in frequency domain
/// - $\gamma$ is a user defined regularization constant
///
/// The type of output Array from deconvolution will be double if the input array type is double.
/// Otherwise, it will be float in rest of the cases. Should the caller want to save the image to
/// disk or require the values of output to be in a fixed range, that should be done by the caller
/// explicitly.
pub fn inverse_deconv<T>(
input: &Array<T>,
kernel: &Array<f32>,
gamma: f32,
algo: InverseDeconvAlgo,
) -> Array<T::AbsOutType>
where
T: DeconvInput,
T::AbsOutType: HasAfEnum,
{
let mut temp: i64 = 0;
unsafe {
let err_val = af_inverse_deconv(
&mut temp as MutAfArray,
input.get() as AfArray,
kernel.get() as AfArray,
gamma,
algo as c_int,
);
HANDLE_ERROR(AfError::from(err_val));
}
temp.into()
}