File: Matrix.cc

package info (click to toggle)
node-opencv 6.0.0+git20180416.cfc96ba0-3
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 24,632 kB
  • sloc: xml: 476,707; cpp: 5,950; makefile: 114; sh: 59; ansic: 20
file content (3195 lines) | stat: -rwxr-xr-x 100,249 bytes parent folder | download
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
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
#include "Contours.h"
#include "Matrix.h"
#include "OpenCV.h"
#include <string.h>
#include <nan.h>

Nan::Persistent<FunctionTemplate> Matrix::constructor;

cv::Scalar setColor(Local<Object> objColor);
cv::Point setPoint(Local<Object> objPoint);
cv::Rect* setRect(Local<Object> objRect, cv::Rect &result);

void Matrix::Init(Local<Object> target) {
  Nan::HandleScope scope;

  //Class
  Local<FunctionTemplate> ctor = Nan::New<FunctionTemplate>(Matrix::New);
  constructor.Reset(ctor);
  ctor->InstanceTemplate()->SetInternalFieldCount(1);
  ctor->SetClassName(Nan::New("Matrix").ToLocalChecked());

  // Prototype
  Nan::SetPrototypeMethod(ctor, "row", Row);
  Nan::SetPrototypeMethod(ctor, "col", Col);
  Nan::SetPrototypeMethod(ctor, "pixelRow", PixelRow);
  Nan::SetPrototypeMethod(ctor, "pixelCol", PixelCol);
  Nan::SetPrototypeMethod(ctor, "empty", Empty);
  Nan::SetPrototypeMethod(ctor, "get", Get);
  Nan::SetPrototypeMethod(ctor, "getPixel", GetPixel);
  Nan::SetPrototypeMethod(ctor, "set", Set);
  Nan::SetPrototypeMethod(ctor, "put", Put);
  Nan::SetPrototypeMethod(ctor, "brightness", Brightness);
  Nan::SetPrototypeMethod(ctor, "normalize", Normalize);
  Nan::SetPrototypeMethod(ctor, "norm", Norm);
  Nan::SetPrototypeMethod(ctor, "getData", GetData);
  Nan::SetPrototypeMethod(ctor, "pixel", Pixel);
  Nan::SetPrototypeMethod(ctor, "width", Width);
  Nan::SetPrototypeMethod(ctor, "height", Height);
  Nan::SetPrototypeMethod(ctor, "type", Type);
  Nan::SetPrototypeMethod(ctor, "size", Size);
  Nan::SetPrototypeMethod(ctor, "clone", Clone);
  Nan::SetPrototypeMethod(ctor, "crop", Crop);
  Nan::SetPrototypeMethod(ctor, "toBuffer", ToBuffer);
  Nan::SetPrototypeMethod(ctor, "toBufferAsync", ToBufferAsync);
  Nan::SetPrototypeMethod(ctor, "ellipse", Ellipse);
  Nan::SetPrototypeMethod(ctor, "rectangle", Rectangle);
  Nan::SetPrototypeMethod(ctor, "line", Line);
  Nan::SetPrototypeMethod(ctor, "fillPoly", FillPoly);
  Nan::SetPrototypeMethod(ctor, "save", Save);
  Nan::SetPrototypeMethod(ctor, "saveAsync", SaveAsync);
  Nan::SetPrototypeMethod(ctor, "resize", Resize);
  Nan::SetPrototypeMethod(ctor, "rotate", Rotate);
  Nan::SetPrototypeMethod(ctor, "warpAffine", WarpAffine);
  Nan::SetPrototypeMethod(ctor, "copyTo", CopyTo);
  Nan::SetPrototypeMethod(ctor, "convertTo", ConvertTo);
  Nan::SetPrototypeMethod(ctor, "pyrDown", PyrDown);
  Nan::SetPrototypeMethod(ctor, "pyrUp", PyrUp);
  Nan::SetPrototypeMethod(ctor, "channels", Channels);
  Nan::SetPrototypeMethod(ctor, "convertGrayscale", ConvertGrayscale);
  Nan::SetPrototypeMethod(ctor, "convertHSVscale", ConvertHSVscale);
  Nan::SetPrototypeMethod(ctor, "gaussianBlur", GaussianBlur);
  Nan::SetPrototypeMethod(ctor, "medianBlur", MedianBlur);
  Nan::SetPrototypeMethod(ctor, "bilateralFilter", BilateralFilter);
  Nan::SetPrototypeMethod(ctor, "sobel", Sobel);
  Nan::SetPrototypeMethod(ctor, "copy", Copy);
  Nan::SetPrototypeMethod(ctor, "flip", Flip);
  Nan::SetPrototypeMethod(ctor, "roi", ROI);
  Nan::SetPrototypeMethod(ctor, "ptr", Ptr);
  Nan::SetPrototypeMethod(ctor, "absDiff", AbsDiff);
  Nan::SetPrototypeMethod(ctor, "dct", Dct);
  Nan::SetPrototypeMethod(ctor, "idct", Idct);
  Nan::SetPrototypeMethod(ctor, "addWeighted", AddWeighted);
  Nan::SetPrototypeMethod(ctor, "add", Add);
  Nan::SetPrototypeMethod(ctor, "bitwiseXor", BitwiseXor);
  Nan::SetPrototypeMethod(ctor, "bitwiseNot", BitwiseNot);
  Nan::SetPrototypeMethod(ctor, "bitwiseAnd", BitwiseAnd);
  Nan::SetPrototypeMethod(ctor, "countNonZero", CountNonZero);
  Nan::SetPrototypeMethod(ctor, "moments", Moments);
  Nan::SetPrototypeMethod(ctor, "canny", Canny);
  Nan::SetPrototypeMethod(ctor, "dilate", Dilate);
  Nan::SetPrototypeMethod(ctor, "erode", Erode);
  Nan::SetPrototypeMethod(ctor, "findContours", FindContours);
  Nan::SetPrototypeMethod(ctor, "drawContour", DrawContour);
  Nan::SetPrototypeMethod(ctor, "drawAllContours", DrawAllContours);
  Nan::SetPrototypeMethod(ctor, "goodFeaturesToTrack", GoodFeaturesToTrack);
  #ifdef HAVE_OPENCV_VIDEO
  Nan::SetPrototypeMethod(ctor, "calcOpticalFlowPyrLK", CalcOpticalFlowPyrLK);
  #endif
  Nan::SetPrototypeMethod(ctor, "houghLinesP", HoughLinesP);
  Nan::SetPrototypeMethod(ctor, "houghCircles", HoughCircles);
  Nan::SetPrototypeMethod(ctor, "inRange", inRange);
  Nan::SetPrototypeMethod(ctor, "adjustROI", AdjustROI);
  Nan::SetPrototypeMethod(ctor, "locateROI", LocateROI);
  Nan::SetPrototypeMethod(ctor, "threshold", Threshold);
  Nan::SetPrototypeMethod(ctor, "adaptiveThreshold", AdaptiveThreshold);
  Nan::SetPrototypeMethod(ctor, "meanStdDev", MeanStdDev);
  Nan::SetPrototypeMethod(ctor, "cvtColor", CvtColor);
  Nan::SetPrototypeMethod(ctor, "split", Split);
  Nan::SetPrototypeMethod(ctor, "merge", Merge);
  Nan::SetPrototypeMethod(ctor, "equalizeHist", EqualizeHist);
  Nan::SetPrototypeMethod(ctor, "floodFill", FloodFill);
  Nan::SetPrototypeMethod(ctor, "matchTemplate", MatchTemplate);
  Nan::SetPrototypeMethod(ctor, "matchTemplateByMatrix", MatchTemplateByMatrix);
  Nan::SetPrototypeMethod(ctor, "templateMatches", TemplateMatches);
  Nan::SetPrototypeMethod(ctor, "minMaxLoc", MinMaxLoc);
  Nan::SetPrototypeMethod(ctor, "pushBack", PushBack);
  Nan::SetPrototypeMethod(ctor, "putText", PutText);
  Nan::SetPrototypeMethod(ctor, "getPerspectiveTransform", GetPerspectiveTransform);
  Nan::SetPrototypeMethod(ctor, "warpPerspective", WarpPerspective);
  Nan::SetMethod(ctor, "Zeros", Zeros);
  Nan::SetMethod(ctor, "Ones", Ones);
  Nan::SetMethod(ctor, "Eye", Eye);
  Nan::SetMethod(ctor, "getRotationMatrix2D", GetRotationMatrix2D);
  Nan::SetPrototypeMethod(ctor, "copyWithMask", CopyWithMask);
  Nan::SetPrototypeMethod(ctor, "setWithMask", SetWithMask);
  Nan::SetPrototypeMethod(ctor, "meanWithMask", MeanWithMask);
  Nan::SetPrototypeMethod(ctor, "mean", Mean);
  Nan::SetPrototypeMethod(ctor, "shift", Shift);
  Nan::SetPrototypeMethod(ctor, "reshape", Reshape);
// leave this out - can't see a way it could be useful to us, as release() always completely forgets the data
//  Nan::SetPrototypeMethod(ctor, "addref", Addref);
  Nan::SetPrototypeMethod(ctor, "release", Release);
  Nan::SetPrototypeMethod(ctor, "getrefCount", GetrefCount);
  Nan::SetPrototypeMethod(ctor, "subtract", Subtract);
  Nan::SetPrototypeMethod(ctor, "compare", Compare);
  Nan::SetPrototypeMethod(ctor, "mul", Mul);
  Nan::SetPrototypeMethod(ctor, "div", Div);
  Nan::SetPrototypeMethod(ctor, "pow", Pow);

  target->Set(Nan::New("Matrix").ToLocalChecked(), ctor->GetFunction());
};

NAN_METHOD(Matrix::New) {
  Nan::HandleScope scope;
  if (info.This()->InternalFieldCount() == 0) {
    Nan::ThrowTypeError("Cannot instantiate without new");
  }

  Matrix *mat;

  if (info.Length() == 0) {
    mat = new Matrix;
  } else if (info.Length() == 2 && info[0]->IsInt32() && info[1]->IsInt32()) {
    mat = new Matrix(info[0]->IntegerValue(), info[1]->IntegerValue());
  } else if (info.Length() == 3 && info[0]->IsInt32() && info[1]->IsInt32()
      && info[2]->IsInt32()) {
    mat = new Matrix(info[0]->IntegerValue(), info[1]->IntegerValue(),
        info[2]->IntegerValue());
  } else if (info.Length() == 4 && info[0]->IsInt32() && info[1]->IsInt32() &&
        info[2]->IsInt32() && info[3]->IsArray()) {
    mat = new Matrix(info[0]->IntegerValue(), info[1]->IntegerValue(),
        info[2]->IntegerValue(), info[3]->ToObject());
  } else {  // if (info.Length() == 5) {
    Matrix *other = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
    int x = info[1]->IntegerValue();
    int y = info[2]->IntegerValue();
    int w = info[3]->IntegerValue();
    int h = info[4]->IntegerValue();
    mat = new Matrix(other->mat, cv::Rect(x, y, w, h));
  }

  mat->Wrap(info.Holder());
  info.GetReturnValue().Set(info.Holder());
}

//Convenience factory method for creating a wrapped Matrix from a cv::Mat and tracking external memory correctly.
// Always tracks the referenced matrix as external memory.
Local<Object> Matrix::CreateWrappedFromMat(cv::Mat mat){
  Local < Object > result =
      Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked();
  Matrix *m = Nan::ObjectWrap::Unwrap<Matrix>(result);
  m->setMat(mat);

  return result;
}

//Convenience factory method for creating a wrapped Matrix from a cv::Mat and tracking external memory correctly.
// Only tracks the referenced matrix as external memory if the refcount does not exceed the base refcount.
// Useful for creating a wrapper Matrix around a Mat that is also referenced by another wrapper Matrix
Local<Object> Matrix::CreateWrappedFromMatIfNotReferenced(cv::Mat mat, int baseRefCount){
  Local < Object > result =
      Nan::NewInstance(Nan::GetFunction(Nan::New(Matrix::constructor)).ToLocalChecked()).ToLocalChecked();
  Matrix *m = Nan::ObjectWrap::Unwrap<Matrix>(result);
  m->mat = mat;
  if (m->getWrappedRefCount() <= 2 + baseRefCount){ //one reference in m, one on the stack
    Nan::AdjustExternalMemory(m->mat.dataend - m->mat.datastart);
  }
  return result;
}

Matrix::Matrix() :
    node_opencv::Matrix() {
  mat = cv::Mat();
}

Matrix::Matrix(int rows, int cols) :
    node_opencv::Matrix() {
  mat = cv::Mat(rows, cols, CV_32FC3);
  Nan::AdjustExternalMemory(mat.dataend - mat.datastart);
}

Matrix::Matrix(int rows, int cols, int type) :
    node_opencv::Matrix() {
  mat = cv::Mat(rows, cols, type);
  Nan::AdjustExternalMemory(mat.dataend - mat.datastart);
}

Matrix::Matrix(Matrix *m) :
    node_opencv::Matrix() {
  mat = cv::Mat(m->mat);
}

Matrix::Matrix(cv::Mat m, cv::Rect roi) :
    node_opencv::Matrix() {
  mat = cv::Mat(m, roi);
}

Matrix::Matrix(int rows, int cols, int type, Local<Object> scalarObj) {
  mat = cv::Mat(rows, cols, type);
  Nan::AdjustExternalMemory(mat.dataend - mat.datastart);
  if (mat.channels() == 3) {
    mat.setTo(cv::Scalar(scalarObj->Get(0)->IntegerValue(),
        scalarObj->Get(1)->IntegerValue(),
        scalarObj->Get(2)->IntegerValue()));
  } else if (mat.channels() == 2) {
    mat.setTo(cv::Scalar(scalarObj->Get(0)->IntegerValue(),
        scalarObj->Get(1)->IntegerValue()));
  } else if (mat.channels() == 1) {
    mat.setTo(cv::Scalar(scalarObj->Get(0)->IntegerValue()));
  } else {
    Nan::ThrowError("Only 1-3 channels are supported");
  }
}

Matrix::~Matrix(){
  if(getWrappedRefCount() == 1){ //if this holds the last reference to the Mat
    int size = mat.dataend - mat.datastart;
    Nan::AdjustExternalMemory(-1 * size);
  }
}

// Set the wrapped Mat with correct memory tracking
// For this to work correctly, there should be no external references held to our previous
// wrapped Mat, and no other Matrix objects should wrap a Mat pointing at the same
// memory as our new Mat.
void Matrix::setMat(cv::Mat m){
  int oldSize = 0;
  if(getWrappedRefCount() == 1){ //if this holds the last reference to the Mat
    oldSize = mat.dataend - mat.datastart;
  }
  mat = m;
  int newSize = mat.dataend - mat.datastart;
  Nan::AdjustExternalMemory(newSize - oldSize);
}

NAN_METHOD(Matrix::Empty) {
  SETUP_FUNCTION(Matrix)
  info.GetReturnValue().Set(Nan::New<Boolean>(self->mat.empty()));
}

double Matrix::DblGet(cv::Mat mat, int i, int j) {

  double val = 0;
  cv::Vec3b pix;
  unsigned int pint = 0;

  switch (mat.type()) {
    case CV_32FC3:
      pix = mat.at<cv::Vec3f>(i, j);
      pint |= (uchar) pix.val[2];
      pint |= ((uchar) pix.val[1]) << 8;
      pint |= ((uchar) pix.val[0]) << 16;
      val = (double) pint;
      break;
    case CV_64FC1:
      val = mat.at<double>(i, j);
      break;
    case CV_32FC1:
      val = mat.at<float>(i, j);
      break;
    default:
      val = mat.at<double>(i, j);
      break;
  }

  return val;
}

NAN_METHOD(Matrix::Pixel) {
  SETUP_FUNCTION(Matrix)

  int y = info[0]->IntegerValue();
  int x = info[1]->IntegerValue();

  // cv::Scalar scal = self->mat.at<uchar>(y, x);

  if (info.Length() == 3) {
    Local < Object > objColor = info[2]->ToObject();

    if (self->mat.channels() == 3) {
      self->mat.at<cv::Vec3b>(y, x)[0] =
          (uchar) objColor->Get(0)->IntegerValue();
      self->mat.at<cv::Vec3b>(y, x)[1] =
          (uchar) objColor->Get(1)->IntegerValue();
      self->mat.at<cv::Vec3b>(y, x)[2] =
          (uchar) objColor->Get(2)->IntegerValue();
    } else if (self->mat.channels() == 1)
      self->mat.at<uchar>(y, x) = (uchar) objColor->Get(0)->IntegerValue();

    info.GetReturnValue().Set(info[2]->ToObject());
  } else {
    if (self->mat.channels() == 3) {
      cv::Vec3b intensity = self->mat.at<cv::Vec3b>(y, x);

      v8::Local < v8::Array > arr = Nan::New<v8::Array>(3);
      arr->Set(0, Nan::New<Number>(intensity[0]));
      arr->Set(1, Nan::New<Number>(intensity[1]));
      arr->Set(2, Nan::New<Number>(intensity[2]));
      info.GetReturnValue().Set(arr);
    } else if (self->mat.channels() == 1) {
      uchar intensity = self->mat.at<uchar>(y, x);
      info.GetReturnValue().Set(Nan::New<Number>(intensity));
    }
  }

  return;
  // double val = Matrix::DblGet(t, i, j);
  // info.GetReturnValue().Set(Nan::New<Number>(val));
}

NAN_METHOD(Matrix::Get) {
  SETUP_FUNCTION(Matrix)

  int i = info[0]->IntegerValue();
  int j = info[1]->IntegerValue();

  double val = Matrix::DblGet(self->mat, i, j);
  info.GetReturnValue().Set(Nan::New<Number>(val));
}

NAN_METHOD(Matrix::GetPixel) {
  SETUP_FUNCTION(Matrix)

  int y = info[0]->IntegerValue();
  int x = info[1]->IntegerValue();

  if (self->mat.channels() == 4) {
    v8::Local < v8::Array > arr = Nan::New<Array>(4);
    cv::Vec4b pixel = self->mat.at<cv::Vec4b>(y, x);
    arr->Set(0, Nan::New<Number>((double) pixel.val[0]));
    arr->Set(1, Nan::New<Number>((double) pixel.val[1]));
    arr->Set(2, Nan::New<Number>((double) pixel.val[2]));
    arr->Set(3, Nan::New<Number>((double) pixel.val[3]));
    info.GetReturnValue().Set(arr);
  } else if (self->mat.channels() == 3) {
    v8::Local < v8::Array > arr = Nan::New<Array>(3);
    cv::Vec3b pixel = self->mat.at<cv::Vec3b>(y, x);
    arr->Set(0, Nan::New<Number>((double) pixel.val[0]));
    arr->Set(1, Nan::New<Number>((double) pixel.val[1]));
    arr->Set(2, Nan::New<Number>((double) pixel.val[2]));
    info.GetReturnValue().Set(arr);
  } else if(self->mat.channels() == 1) {
    int pixel = (int)self->mat.at<unsigned char>(y, x);
    info.GetReturnValue().Set(pixel);
  } else {
    Nan::ThrowTypeError("Only 4, 3 and 1 channel matrix are supported");
  }
}

NAN_METHOD(Matrix::Set) {
  SETUP_FUNCTION(Matrix)

  int i = info[0]->IntegerValue();
  int j = info[1]->IntegerValue();
  double val = info[2]->NumberValue();
  int vint = 0;

  if (info.Length() == 4) {
    self->mat.at<cv::Vec3b>(i, j)[info[3]->NumberValue()] = val;
  } else if (info.Length() == 3) {
    switch (self->mat.type()) {
      case CV_32FC3:
        vint = static_cast<unsigned int>(val + 0.5);
        self->mat.at<cv::Vec3f>(i, j)[0] = (uchar) (vint >> 16) & 0xff;
        self->mat.at<cv::Vec3f>(i, j)[1] = (uchar) (vint >> 8) & 0xff;
        self->mat.at<cv::Vec3f>(i, j)[2] = (uchar) (vint) & 0xff;
        // printf("!!!i %x, %x, %x", (vint >> 16) & 0xff, (vint >> 8) & 0xff, (vint) & 0xff);
        break;
      case CV_32FC1:
        self->mat.at<float>(i, j) = val;
        break;
      default:
        self->mat.at<double>(i, j) = val;
    }

  } else {
    Nan::ThrowTypeError("Invalid number of arguments");
  }

  return;
}

// @author tualo
// put node buffer directly into the image data
// img.put(new Buffer([0,100,0,100,100...]));
NAN_METHOD(Matrix::Put) {
  SETUP_FUNCTION(Matrix)

  if (!Buffer::HasInstance(info[0])) {
    Nan::ThrowTypeError("Not a buffer");
  }
  const char* buffer_data = Buffer::Data(info[0]);
  size_t buffer_length = Buffer::Length(info[0]);
  memcpy(self->mat.data, buffer_data, buffer_length);
  return;
}

// @author tualo
// getData getting node buffer of image data
NAN_METHOD(Matrix::GetData) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int size = self->mat.rows * self->mat.cols * self->mat.elemSize();
  Local<Object> buf = Nan::NewBuffer(size).ToLocalChecked();
  uchar* data = (uchar*) Buffer::Data(buf);
  // if there is padding after each row, clone first to get rid of it
  if (self->mat.dims == 2 && self->mat.step[0] != size_t(self->mat.size[1])) {
    cv::Mat copy = self->mat.clone();
    memcpy(data, copy.data, size);
  } else {
    memcpy(data, self->mat.data, size);
  }

  v8::Local<v8::Object> globalObj = Nan::GetCurrentContext()->Global();
  v8::Local<v8::Function> bufferConstructor = v8::Local<v8::Function>::Cast(globalObj->Get(Nan::New<String>("Buffer").ToLocalChecked()));
  v8::Local<v8::Value> constructorArgs[3] = {buf, Nan::New<v8::Integer>((unsigned) size), Nan::New<v8::Integer>(0)};
  v8::Local<v8::Object> actualBuffer = Nan::NewInstance(bufferConstructor, 3, constructorArgs).ToLocalChecked();

  info.GetReturnValue().Set(actualBuffer);
}

NAN_METHOD(Matrix::Brightness) {
  Nan::HandleScope scope;
  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  if (info.Length() == 2) {
    cv::Mat image;

    if (self->mat.channels() == 3) {
      image = self->mat;
    } else if (self->mat.channels() == 1) {
      cv::Mat myimg = self->mat;
      cv::cvtColor(myimg, image, CV_GRAY2RGB);
    } else {
      Nan::ThrowError("those channels are not supported");
    }

    cv::Mat new_image = cv::Mat::zeros( image.size(), image.type() );
    double alpha = info[0]->NumberValue();
    int beta = info[1]->IntegerValue();

    // Do the operation new_image(i,j) = alpha*image(i,j) + beta
    for (int y = 0; y < image.rows; y++ ) {
      for (int x = 0; x < image.cols; x++ ) {
        for (int c = 0; c < 3; c++ ) {
          new_image.at<cv::Vec3b>(y,x)[c] =
              cv::saturate_cast<uchar>(alpha*( image.at<cv::Vec3b>(y,x)[c] ) + beta);
        }
      }
    }

    if (self->mat.channels() == 3) {
      new_image.copyTo(self->mat);
    } else if (self->mat.channels() == 1) {
      cv::Mat gray;
      cv::cvtColor(new_image, gray, CV_BGR2GRAY);
      gray.copyTo(self->mat);
    }
  } else {
    if (info.Length() == 1) {
      int diff = info[0]->IntegerValue();
      cv::Mat img = self->mat + diff;
      img.copyTo(self->mat);
    } else {
      info.GetReturnValue().Set(Nan::New("Insufficient or wrong arguments").ToLocalChecked());
    }
  }

  info.GetReturnValue().Set(Nan::Null());
}

int getNormType(int type) {
  if ((type != cv::NORM_MINMAX) && (type != cv::NORM_INF)
      && (type != cv::NORM_L1) && (type != cv::NORM_L2)
      && (type != cv::NORM_L2SQR) && (type != cv::NORM_HAMMING)
      && (type != cv::NORM_HAMMING2) && (type != cv::NORM_RELATIVE)
      && (type != cv::NORM_TYPE_MASK)) {
    Nan::ThrowTypeError("type value must be NORM_INF=1, NORM_L1=2, NORM_L2=4,"
        " NORM_L2SQR=5, NORM_HAMMING=6, NORM_HAMMING2=7, NORM_TYPE_MASK=7, "
        "NORM_RELATIVE=8, NORM_MINMAX=32 ");
  }
  return type;
}

// @author tualo
// normalize wrapper
NAN_METHOD(Matrix::Normalize) {
  if (!info[0]->IsNumber()) {
    Nan::ThrowTypeError("min is required (argument 1)");
  }

  if (!info[1]->IsNumber()) {
    Nan::ThrowTypeError("max is required (argument 2)");
  }

  int type = cv::NORM_MINMAX;
  if (info[2]->IsNumber()) {
    type = getNormType(info[2]->Uint32Value());
  }
  int dtype = -1;
  if (info[3]->IsNumber()) {
    dtype = info[3]->IntegerValue();
  }

  double min = info[0]->NumberValue();
  double max = info[1]->NumberValue();

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  cv::Mat norm;

  cv::Mat mask;
  if (info[4]->IsObject()) {
    Matrix *mmask = Nan::ObjectWrap::Unwrap<Matrix>(info[4]->ToObject());
    mask = mmask->mat;
  }

  cv::normalize(self->mat, norm, min, max, type, dtype, mask);

  norm.copyTo(self->mat);

  info.GetReturnValue().Set(Nan::Null());
}

/**
 * Calculates an absolute array norm, an absolute difference norm, or a relative
 * difference norm.
 *
 * Reference: http://docs.opencv.org/2.4/modules/core/doc/
 *            operations_on_arrays.html?highlight=normalize#norm
 */
NAN_METHOD(Matrix::Norm) {
  Matrix *src2 = NULL;
  int normType = cv::NORM_L2;
  cv::Mat mask;
  int infoCount = 0;

  Matrix *src1 = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  // If src2 is specified calculate absolute or relative difference norm
  if (!info[infoCount]->IsUndefined() && info[infoCount]->IsObject()) {
    src2 = Nan::ObjectWrap::Unwrap<Matrix>(info[infoCount]->ToObject());
    infoCount++;
  }

  // NORM_TYPE
  if (!info[infoCount]->IsUndefined() && info[infoCount]->IsInt32()) {
    normType = getNormType(info[infoCount]->Uint32Value());
    infoCount++;
  }

  // Mask
  if (!info[infoCount]->IsUndefined() && info[infoCount]->IsObject()) {
    Matrix *mmask = Nan::ObjectWrap::Unwrap<Matrix>(info[infoCount]->ToObject());
    mask = mmask->mat;
    infoCount++;
  }

  double res = 0;
  if (src2) {
    res = cv::norm(src1->mat, src2->mat, normType, mask);
  } else {
    res = cv::norm(src1->mat, normType, mask);
  }

  info.GetReturnValue().Set(Nan::New<Number>(res));
}

NAN_METHOD(Matrix::Size) {
  SETUP_FUNCTION(Matrix)

  v8::Local < v8::Array > arr = Nan::New<Array>(2);
  arr->Set(0, Nan::New<Number>(self->mat.size().height));
  arr->Set(1, Nan::New<Number>(self->mat.size().width));

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::Type) {
  SETUP_FUNCTION(Matrix)

  info.GetReturnValue().Set(Nan::New<Int32>(self->mat.type()));
}

NAN_METHOD(Matrix::Clone) {
  SETUP_FUNCTION(Matrix)

  Local<Object> im_h = Matrix::CreateWrappedFromMat(self->mat.clone());

  info.GetReturnValue().Set(im_h);
}

NAN_METHOD(Matrix::Crop) {
  SETUP_FUNCTION(Matrix)

  if ((info.Length() == 4) && (info[0]->IsNumber()) && (info[1]->IsNumber())
      && (info[2]->IsNumber()) && (info[3]->IsNumber())) {

    int x = info[0]->IntegerValue();
    int y = info[1]->IntegerValue();
    int width = info[2]->IntegerValue();
    int height = info[3]->IntegerValue();

    cv::Mat mat(self->mat, cv::Rect(x,y,width,height));

    Local < Object > im_h = Matrix::CreateWrappedFromMatIfNotReferenced(mat, 1);

    info.GetReturnValue().Set(im_h);
  } else {
    info.GetReturnValue().Set(Nan::New("Insufficient or wrong arguments").ToLocalChecked());
  }
}

NAN_METHOD(Matrix::Row) {
  SETUP_FUNCTION(Matrix)

  int width = self->mat.size().width;
  int y = info[0]->IntegerValue();
  v8::Local < v8::Array > arr = Nan::New<Array>(width);

  for (int x = 0; x < width; x++) {
    double v = Matrix::DblGet(self->mat, y, x);
    arr->Set(x, Nan::New<Number>(v));
  }

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::PixelRow) {
  SETUP_FUNCTION(Matrix)

  int width = self->mat.size().width;
  int y = info[0]->IntegerValue();
  v8::Local < v8::Array > arr;

  if (self->mat.channels() == 4) {
    arr = Nan::New<Array>(width * 4);
    for (int x = 0; x < width; x++) {
      cv::Vec4b pixel = self->mat.at<cv::Vec4b>(y, x);
      int offset = x * 4;
      arr->Set(offset, Nan::New<Number>((double) pixel.val[0]));
      arr->Set(offset + 1, Nan::New<Number>((double) pixel.val[1]));
      arr->Set(offset + 2, Nan::New<Number>((double) pixel.val[2]));
      arr->Set(offset + 3, Nan::New<Number>((double) pixel.val[3]));
    }
  } else if(self->mat.channels() == 3){
    arr = Nan::New<Array>(width * 3);
    for (int x = 0; x < width; x++) {
      cv::Vec3b pixel = self->mat.at<cv::Vec3b>(y, x);
      int offset = x * 3;
      arr->Set(offset, Nan::New<Number>((double) pixel.val[0]));
      arr->Set(offset + 1, Nan::New<Number>((double) pixel.val[1]));
      arr->Set(offset + 2, Nan::New<Number>((double) pixel.val[2]));
    }
  } else if(self->mat.channels() == 1){
    arr = Nan::New<Array>(width);
    for (int x = 0; x < width; x++) {
      int pixel = (int)self->mat.at<unsigned char>(y, x);
      arr->Set(x, Nan::New<Number>(pixel));
    }
  } else {
      Nan::ThrowTypeError("Only 4, 3 and 1 channel matrix are supported");
  }

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::Col) {
  SETUP_FUNCTION(Matrix)

  int height = self->mat.size().height;
  int x = info[0]->IntegerValue();
  v8::Local < v8::Array > arr = Nan::New<Array>(height);

  for (int y = 0; y < height; y++) {
    double v = Matrix::DblGet(self->mat, y, x);
    arr->Set(y, Nan::New<Number>(v));
  }
  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::PixelCol) {
  SETUP_FUNCTION(Matrix)

  int height = self->mat.size().height;
  int x = info[0]->IntegerValue();
  v8::Local < v8::Array > arr;

  if (self->mat.channels() == 4) {
    arr = Nan::New<Array>(height * 4);
    for (int y = 0; y < height; y++) {
      cv::Vec4b pixel = self->mat.at<cv::Vec4b>(y, x);
      int offset = y * 4;
      arr->Set(offset, Nan::New<Number>((double) pixel.val[0]));
      arr->Set(offset + 1, Nan::New<Number>((double) pixel.val[1]));
      arr->Set(offset + 2, Nan::New<Number>((double) pixel.val[2]));
      arr->Set(offset + 3, Nan::New<Number>((double) pixel.val[3]));
    }
  } else if (self->mat.channels() == 3) {
    arr = Nan::New<Array>(height * 3);
    for (int y = 0; y < height; y++) {
      cv::Vec3b pixel = self->mat.at<cv::Vec3b>(y, x);
      int offset = y * 3;
      arr->Set(offset, Nan::New<Number>((double) pixel.val[0]));
      arr->Set(offset + 1, Nan::New<Number>((double) pixel.val[1]));
      arr->Set(offset + 2, Nan::New<Number>((double) pixel.val[2]));
    }
  } else if(self->mat.channels() == 1) {
    arr = Nan::New<Array>(height);
    for (int y = 0; y < height; y++) {
      int pixel = (int)self->mat.at<unsigned char>(y, x);
      arr->Set(y, Nan::New<Number>(pixel));
    }
  } else {
    Nan::ThrowTypeError("Only 4, 3 and 1 channel matrix are supported");
  }

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::Width) {
  SETUP_FUNCTION(Matrix)

  info.GetReturnValue().Set(Nan::New<Number>(self->mat.size().width));
}

NAN_METHOD(Matrix::Height) {
  SETUP_FUNCTION(Matrix)

  info.GetReturnValue().Set(Nan::New<Number>(self->mat.size().height));
}

NAN_METHOD(Matrix::Channels) {
  SETUP_FUNCTION(Matrix)

  info.GetReturnValue().Set(Nan::New<Number>(self->mat.channels()));
}

NAN_METHOD(Matrix::ToBuffer) {
  SETUP_FUNCTION(Matrix)

  if ((info.Length() > 0) && (info[0]->IsFunction())) {
    return Matrix::ToBufferAsync(info);
  }

  // SergeMv changes
  // img.toBuffer({ext: ".png", pngCompression: 9}); // default png compression is 3
  // img.toBuffer({ext: ".jpg", jpegQuality: 80});
  // img.toBuffer(); // creates Jpeg with quality of 95 (Opencv default quality)
  // via the ext you can do other image formats too (like tiff), see
  // http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imencode
  //---------------------------
  // Provide default value
  const char *ext = ".jpg";
  std::string optExt;
  std::vector<int> params;

  // See if the options argument is passed
  if ((info.Length() > 0) && (info[0]->IsObject())) {
    // Get this options argument
    v8::Handle < v8::Object > options = v8::Local<v8::Object>::Cast(info[0]);
    // If the extension (image format) is provided
    if (options->Has(Nan::New<String>("ext").ToLocalChecked())) {
      v8::String::Utf8Value str(
          options->Get(Nan::New<String>("ext").ToLocalChecked())->ToString());
      optExt = *str;
      ext = (const char *) optExt.c_str();
    }
    if (options->Has(Nan::New<String>("jpegQuality").ToLocalChecked())) {
      int compression =
          options->Get(Nan::New<String>("jpegQuality").ToLocalChecked())->IntegerValue();
      params.push_back(CV_IMWRITE_JPEG_QUALITY);
      params.push_back(compression);
    }
    if (options->Has(Nan::New<String>("pngCompression").ToLocalChecked())) {
      int compression =
          options->Get(Nan::New<String>("pngCompression").ToLocalChecked())->IntegerValue();
      params.push_back(CV_IMWRITE_PNG_COMPRESSION);
      params.push_back(compression);
    }
  }

  //---------------------------
  std::vector<uchar> vec(0);

  cv::imencode(ext, self->mat, vec, params);

  Local < Object > buf = Nan::NewBuffer(vec.size()).ToLocalChecked();
  uchar* data = (uchar*) Buffer::Data(buf);
  memcpy(data, &vec[0], vec.size());

  v8::Local < v8::Object > globalObj = Nan::GetCurrentContext()->Global();
  v8::Local < v8::Function > bufferConstructor = v8::Local < v8::Function
      > ::Cast(globalObj->Get(Nan::New<String>("Buffer").ToLocalChecked()));
  v8::Local<v8::Value> constructorArgs[3] =
      {buf, Nan::New<v8::Integer>((unsigned)vec.size()), Nan::New<v8::Integer>(0)};
  v8::Local < v8::Object > actualBuffer = Nan::NewInstance(bufferConstructor, 3, constructorArgs).ToLocalChecked();

  info.GetReturnValue().Set(actualBuffer);
}

class AsyncToBufferWorker: public Nan::AsyncWorker {
public:
  AsyncToBufferWorker(Nan::Callback *callback, Matrix *matrix, std::string ext,
    std::vector<int> params) :
      Nan::AsyncWorker(callback),
      matrix(new Matrix(matrix)), // dulipcate matrix, adding ref, but not copying data
      ext(ext),
      params(params) {
  }

  ~AsyncToBufferWorker() {
      // mat is released, decrementing refcount
  }

  void Execute() {
    std::vector<uchar> vec(0);
    // std::vector<int> params(0);//CV_IMWRITE_JPEG_QUALITY 90
    cv::imencode(ext, matrix->mat, vec, this->params);
    res = vec;
  }

  void HandleOKCallback() {
    Nan::HandleScope scope;

    delete matrix;
    matrix = NULL;

    Local<Object> buf = Nan::NewBuffer(res.size()).ToLocalChecked();
    uchar* data = (uchar*) Buffer::Data(buf);
    memcpy(data, &res[0], res.size());

    v8::Local<v8::Object> globalObj = Nan::GetCurrentContext()->Global();
    v8::Local<v8::Function> bufferConstructor = v8::Local<v8::Function>::Cast(globalObj->Get(Nan::New<String>("Buffer").ToLocalChecked()));
    v8::Local<v8::Value> constructorArgs[3] = {buf, Nan::New<v8::Integer>((unsigned)res.size()), Nan::New<v8::Integer>(0)};
    v8::Local<v8::Object> actualBuffer = Nan::NewInstance(bufferConstructor, 3, constructorArgs).ToLocalChecked();;

    Local<Value> argv[] = {
      Nan::Null(),
      actualBuffer
    };

    Nan::TryCatch try_catch;
    callback->Call(2, argv);
    if (try_catch.HasCaught()) {
      Nan::FatalException(try_catch);
    }

  }

private:
  Matrix *matrix;
  std::string ext;
  std::vector<int> params;
  std::vector<uchar> res;
};

NAN_METHOD(Matrix::ToBufferAsync) {
  SETUP_FUNCTION(Matrix)

  REQ_FUN_ARG(0, cb);

  std::string ext = std::string(".jpg");
  std::vector<int> params;

  // See if the options argument is passed
  if ((info.Length() > 1) && (info[1]->IsObject())) {
    // Get this options argument
    v8::Handle < v8::Object > options = v8::Local<v8::Object>::Cast(info[1]);
    // If the extension (image format) is provided
    if (options->Has(Nan::New<String>("ext").ToLocalChecked())) {
      v8::String::Utf8Value str(
          options->Get(Nan::New<String>("ext").ToLocalChecked())->ToString());
      std::string str2 = std::string(*str);
      ext = str2;
    }
    if (options->Has(Nan::New<String>("jpegQuality").ToLocalChecked())) {
      int compression =
          options->Get(Nan::New<String>("jpegQuality").ToLocalChecked())->IntegerValue();
      params.push_back(CV_IMWRITE_JPEG_QUALITY);
      params.push_back(compression);
    }
    if (options->Has(Nan::New<String>("pngCompression").ToLocalChecked())) {
      int compression =
          options->Get(Nan::New<String>("pngCompression").ToLocalChecked())->IntegerValue();
      params.push_back(CV_IMWRITE_PNG_COMPRESSION);
      params.push_back(compression);
    }
  }

  Nan::Callback *callback = new Nan::Callback(cb.As<Function>());
  Nan::AsyncQueueWorker(new AsyncToBufferWorker(callback, self, ext, params));

  return;
}

NAN_METHOD(Matrix::Ellipse) {
  SETUP_FUNCTION(Matrix)

  int x = 0;
  int y = 0;
  int width = 0;
  int height = 0;
  cv::Scalar color(0, 0, 255);
  int thickness = 1;
  double angle = 0;
  double startAngle = 0;
  double endAngle = 360;
  int lineType = 8;
  int shift = 0;

  if (info[0]->IsObject()) {
    v8::Handle < v8::Object > options = v8::Local<v8::Object>::Cast(info[0]);
    if (options->Has(Nan::New<String>("center").ToLocalChecked())) {
      Local < Object > center =
          options->Get(Nan::New<String>("center").ToLocalChecked())->ToObject();
      x = center->Get(Nan::New<String>("x").ToLocalChecked())->Uint32Value();
      y = center->Get(Nan::New<String>("y").ToLocalChecked())->Uint32Value();
    }
    if (options->Has(Nan::New<String>("axes").ToLocalChecked())) {
      Local < Object > axes = options->Get(Nan::New<String>("axes").ToLocalChecked())->ToObject();
      width = axes->Get(Nan::New<String>("width").ToLocalChecked())->Uint32Value();
      height = axes->Get(Nan::New<String>("height").ToLocalChecked())->Uint32Value();
    }
    if (options->Has(Nan::New<String>("thickness").ToLocalChecked())) {
      thickness = options->Get(Nan::New<String>("thickness").ToLocalChecked())->Uint32Value();
    }
    if (options->Has(Nan::New<String>("angle").ToLocalChecked())) {
      angle = options->Get(Nan::New<String>("angle").ToLocalChecked())->NumberValue();
    }
    if (options->Has(Nan::New<String>("startAngle").ToLocalChecked())) {
      startAngle = options->Get(Nan::New<String>("startAngle").ToLocalChecked())->NumberValue();
    }
    if (options->Has(Nan::New<String>("endAngle").ToLocalChecked())) {
      endAngle = options->Get(Nan::New<String>("endAngle").ToLocalChecked())->NumberValue();
    }
    if (options->Has(Nan::New<String>("lineType").ToLocalChecked())) {
      lineType = options->Get(Nan::New<String>("lineType").ToLocalChecked())->Uint32Value();
    }
    if (options->Has(Nan::New<String>("shift").ToLocalChecked())) {
      shift = options->Get(Nan::New<String>("shift").ToLocalChecked())->Uint32Value();
    }
    if (options->Has(Nan::New<String>("color").ToLocalChecked())) {
      Local < Object > objColor =
          options->Get(Nan::New<String>("color").ToLocalChecked())->ToObject();
      color = setColor(objColor);
    }
  } else {
    x = info[0]->Uint32Value();
    y = info[1]->Uint32Value();
    width = info[2]->Uint32Value();
    height = info[3]->Uint32Value();

    if (info[4]->IsArray()) {
      Local < Object > objColor = info[4]->ToObject();
      color = setColor(objColor);
    }

    if (info[5]->IntegerValue())
      thickness = info[5]->IntegerValue();
  }

  cv::ellipse(self->mat, cv::Point(x, y), cv::Size(width, height), angle,
      startAngle, endAngle, color, thickness, lineType, shift);
  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Rectangle) {
  SETUP_FUNCTION(Matrix)

  if (info[0]->IsArray() && info[1]->IsArray()) {
    Local < Object > xy = info[0]->ToObject();
    Local < Object > width_height = info[1]->ToObject();

    cv::Scalar color(0, 0, 255);

    if (info[2]->IsArray()) {
      Local < Object > objColor = info[2]->ToObject();
      color = setColor(objColor);
    }

    int x = xy->Get(0)->IntegerValue();
    int y = xy->Get(1)->IntegerValue();

    int width = width_height->Get(0)->IntegerValue();
    int height = width_height->Get(1)->IntegerValue();

    int thickness = 1;

    if (info[3]->IntegerValue())
      thickness = info[3]->IntegerValue();

    cv::rectangle(self->mat, cv::Point(x, y), cv::Point(x + width, y + height),
        color, thickness);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Line) {
  SETUP_FUNCTION(Matrix)

  if (info[0]->IsArray() && info[1]->IsArray()) {
    Local < Object > xy1 = info[0]->ToObject();
    Local < Object > xy2 = info[1]->ToObject();

    cv::Scalar color(0, 0, 255);

    if (info[2]->IsArray()) {
      Local < Object > objColor = info[2]->ToObject();
      color = setColor(objColor);
    }

    int x1 = xy1->Get(0)->IntegerValue();
    int y1 = xy1->Get(1)->IntegerValue();

    int x2 = xy2->Get(0)->IntegerValue();
    int y2 = xy2->Get(1)->IntegerValue();

    int thickness = 1;

    if (info[3]->IntegerValue())
      thickness = info[3]->IntegerValue();

    cv::line(self->mat, cv::Point(x1, y1), cv::Point(x2, y2), color, thickness);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::FillPoly) {
  SETUP_FUNCTION(Matrix)

  if (info[0]->IsArray()) {
    Local < Array > polyArray = Local < Array > ::Cast(info[0]->ToObject());

    cv::Point **polygons = new cv::Point*[polyArray->Length()];
    int *polySizes = new int[polyArray->Length()];
    for (unsigned int i = 0; i < polyArray->Length(); i++) {
      Local<Array> singlePoly = Local<Array> ::Cast(polyArray->Get(i)->ToObject());
      polygons[i] = new cv::Point[singlePoly->Length()];
      polySizes[i] = singlePoly->Length();

      for (unsigned int j = 0; j < singlePoly->Length(); j++) {
        Local<Array> point = Local<Array> ::Cast(singlePoly->Get(j)->ToObject());
        polygons[i][j].x = point->Get(0)->IntegerValue();
        polygons[i][j].y = point->Get(1)->IntegerValue();
      }
    }

    cv::Scalar color(0, 0, 255);
    if (info[1]->IsArray()) {
      Local<Object> objColor = info[1]->ToObject();
      color = setColor(objColor);
    }

    cv::fillPoly(self->mat, (const cv::Point **) polygons, polySizes,
        polyArray->Length(), color);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Save) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() > 1) {
    return SaveAsync(info);
  }

  if (!info[0]->IsString()) {
    Nan::ThrowTypeError("filename required");
  }

  Nan::Utf8String filename(info[0]);
  int res = cv::imwrite(*filename, self->mat);

  info.GetReturnValue().Set(Nan::New<Number>(res));
}

// All this is for async save, see here for nan example:
// https://github.com/rvagg/nan/blob/c579ae858ae3208d7e702e8400042ba9d48fa64b/examples/async_pi_estimate/async.cc
class AsyncSaveWorker: public Nan::AsyncWorker {
public:
  AsyncSaveWorker(Nan::Callback *callback, Matrix *matrix, char* filename) :
      Nan::AsyncWorker(callback),
      matrix(new Matrix(matrix)),
      filename(filename) {
  }

  ~AsyncSaveWorker() {
  }

  // Executed inside the worker-thread.
  // It is not safe to access V8, or V8 data structures
  // here, so everything we need for input and output
  // should go on `this`.
  void Execute() {
    res = cv::imwrite(this->filename, matrix->mat);
  }

  // Executed when the async work is complete
  // this function will be run inside the main event loop
  // so it is safe to use V8 again
  void HandleOKCallback() {
    Nan::HandleScope scope;

    delete matrix;
    matrix = NULL;

    Local<Value> argv[] = {
      Nan::Null(),
      Nan::New<Number>(res)
    };

    Nan::TryCatch try_catch;
    callback->Call(2, argv);
    if (try_catch.HasCaught()) {
      Nan::FatalException(try_catch);
    }
  }

private:
  Matrix *matrix;
  std::string filename;
  int res;
};

NAN_METHOD(Matrix::SaveAsync) {
  SETUP_FUNCTION(Matrix)

  if (!info[0]->IsString()) {
    Nan::ThrowTypeError("filename required");
  }

  Nan::Utf8String filename(info[0]);

  REQ_FUN_ARG(1, cb);

  Nan::Callback *callback = new Nan::Callback(cb.As<Function>());
  Nan::AsyncQueueWorker(new AsyncSaveWorker(callback, self, *filename));

  return;
}

NAN_METHOD(Matrix::Zeros) {
  Nan::HandleScope scope;

  int w = info[0]->Uint32Value();
  int h = info[1]->Uint32Value();
  int type = (info.Length() > 2) ? info[2]->IntegerValue() : CV_64FC1;

  cv::Mat mat = cv::Mat::zeros(w, h, type);
  Local<Object> im_h = Matrix::CreateWrappedFromMat(mat);
  info.GetReturnValue().Set(im_h);
}

NAN_METHOD(Matrix::Ones) {
  Nan::HandleScope scope;

  int w = info[0]->Uint32Value();
  int h = info[1]->Uint32Value();
  int type = (info.Length() > 2) ? info[2]->IntegerValue() : CV_64FC1;

  cv::Mat mat = cv::Mat::ones(w, h, type);
  Local<Object> im_h = Matrix::CreateWrappedFromMat(mat);

  info.GetReturnValue().Set(im_h);
}

NAN_METHOD(Matrix::Eye) {
  Nan::HandleScope scope;

  int w = info[0]->Uint32Value();
  int h = info[1]->Uint32Value();
  int type = (info.Length() > 2) ? info[2]->IntegerValue() : CV_64FC1;

  cv::Mat mat = cv::Mat::eye(w, h, type);
  Local<Object> im_h = Matrix::CreateWrappedFromMat(mat);

  info.GetReturnValue().Set(im_h);
}

NAN_METHOD(Matrix::ConvertGrayscale) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  if (self->mat.channels() != 3) {
    Nan::ThrowError("Image is no 3-channel");
  }

  int oldSize = self->mat.dataend - self->mat.datastart;
  cv::cvtColor(self->mat, self->mat, CV_BGR2GRAY);
  int newSize = self->mat.dataend - self->mat.datastart;
  Nan::AdjustExternalMemory(newSize - oldSize);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::ConvertHSVscale) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  if (self->mat.channels() != 3) {
    Nan::ThrowError("Image is no 3-channel");
  }

  cv::Mat hsv;

  cv::cvtColor(self->mat, hsv, CV_BGR2HSV);
  hsv.copyTo(self->mat);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::GaussianBlur) {
  Nan::HandleScope scope;
  cv::Size ksize;
  cv::Mat blurred;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  double sigmaX = 0;
  double sigmaY = 0;
  int borderType = cv::BORDER_DEFAULT;

  if (info.Length() < 1) {
    ksize = cv::Size(5, 5);
  }
  else {
    if (!info[0]->IsArray()) {
      Nan::ThrowTypeError("'ksize' argument must be a 2 double array");
    }
    Local<Object> array = info[0]->ToObject();
    // TODO: Length check
    Local<Value> x = array->Get(0);
    Local<Value> y = array->Get(1);
    if (!x->IsNumber() || !y->IsNumber()) {
      Nan::ThrowTypeError("'ksize' argument must be a 2 double array");
    }
    ksize = cv::Size(x->NumberValue(), y->NumberValue());

    sigmaX = info.Length() < 2 ? 0 : info[1]->NumberValue();
    sigmaY = info.Length() < 3 ? 0 : info[2]->NumberValue();

    if (info.Length() == 4) {
      borderType = info[3]->IntegerValue();
    }
  }

  cv::GaussianBlur(self->mat, blurred, ksize, sigmaX, sigmaY, borderType);
  blurred.copyTo(self->mat);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::MedianBlur) {
  Nan::HandleScope scope;
  cv::Mat blurred;
  int ksize = 3;
  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  if (info[0]->IsNumber()) {
    ksize = info[0]->IntegerValue();
    if ((ksize % 2) == 0) {
      Nan::ThrowTypeError("'ksize' argument must be a positive odd integer");
    }
  } else {
    Nan::ThrowTypeError("'ksize' argument must be a positive odd integer");
  }

  cv::medianBlur(self->mat, blurred, ksize);
  blurred.copyTo(self->mat);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::BilateralFilter) {
  Nan::HandleScope scope;
  cv::Mat filtered;
  int d = 15;
  double sigmaColor = 80;
  double sigmaSpace = 80;
  int borderType = cv::BORDER_DEFAULT;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  if (info.Length() != 0) {
    if (info.Length() < 3 || info.Length() > 4) {
      Nan::ThrowTypeError("BilateralFilter takes 0, 3, or 4 arguments");
    } else {
      d = info[0]->IntegerValue();
      sigmaColor = info[1]->NumberValue();
      sigmaSpace = info[2]->NumberValue();
      if (info.Length() == 4) {
        borderType = info[3]->IntegerValue();
      }
    }
  }

  cv::bilateralFilter(self->mat, filtered, d, sigmaColor, sigmaSpace, borderType);
  filtered.copyTo(self->mat);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Sobel) {
  Nan::HandleScope scope;

  if (info.Length() < 3)
    Nan::ThrowError("Need more arguments: sobel(ddepth, xorder, yorder, ksize=3, scale=1.0, delta=0.0, borderType=CV_BORDER_DEFAULT)");

  int ddepth = info[0]->IntegerValue();
  int xorder = info[1]->IntegerValue();
  int yorder = info[2]->IntegerValue();

  int ksize = 3;
  if (info.Length() > 3) ksize = info[3]->IntegerValue();
  double scale = 1;
  if (info.Length() > 4) scale = info[4]->NumberValue();
  double delta = 0;
  if (info.Length() > 5) delta = info[5]->NumberValue();
  int borderType = cv::BORDER_DEFAULT;
  if (info.Length() > 6) borderType = info[6]->IntegerValue();

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  cv::Mat result;
  cv::Sobel(self->mat, result, ddepth, xorder, yorder, ksize, scale, delta, borderType);

  info.GetReturnValue().Set(CreateWrappedFromMat(result));
}

NAN_METHOD(Matrix::Copy) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  cv::Mat result;
  self->mat.copyTo(result);

  info.GetReturnValue().Set(CreateWrappedFromMat(result));
}

NAN_METHOD(Matrix::Flip) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  if ( info.Length() < 1 || !info[0]->IsInt32() ) {
    Nan::ThrowTypeError("Flip requires an integer flipCode argument "
        "(0 = X axis, positive = Y axis, negative = both axis)");
  }

  int flipCode = Nan::To<int>(info[0]).FromJust();

  cv::Mat result;
  cv::flip(self->mat, result, flipCode);

  info.GetReturnValue().Set(CreateWrappedFromMat(result));
}

NAN_METHOD(Matrix::ROI) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  if ( info.Length() != 4 ) {
    Nan::ThrowTypeError("ROI requires x,y,w,h arguments");
  }

  // Although it's an image to return, it is in fact a pointer to ROI of parent matrix

  int x = info[0]->IntegerValue();
  int y = info[1]->IntegerValue();
  int w = info[2]->IntegerValue();
  int h = info[3]->IntegerValue();

  cv::Mat roi(self->mat, cv::Rect(x,y,w,h));
  // Although it's an image to return, it is in fact a pointer to ROI of parent matrix
  Local<Object> img_to_return = Matrix::CreateWrappedFromMatIfNotReferenced(roi, 1);

  info.GetReturnValue().Set(img_to_return);
}

NAN_METHOD(Matrix::Ptr) {
  Nan::HandleScope scope;
  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int line = info[0]->Uint32Value();

  char* data = self->mat.ptr<char>(line);
  // uchar* data = self->mat.data;

  // char *mydata = "Random raw data\0";
  Local<Object> return_buffer = Nan::NewBuffer((char*)data, self->mat.step).ToLocalChecked();
  info.GetReturnValue().Set( return_buffer );
//  return;
}

NAN_METHOD(Matrix::AbsDiff) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *src1 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  Matrix *src2 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());
  cv::absdiff(src1->mat, src2->mat, self->mat);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Dct) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int cols = self->mat.cols;
  int rows = self->mat.rows;

  cv::Mat result(cols, rows, CV_32F);

  cv::dct(self->mat, result);

  info.GetReturnValue().Set(CreateWrappedFromMat(result));
}

NAN_METHOD(Matrix::Idct) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int cols = self->mat.cols;
  int rows = self->mat.rows;

  cv::Mat result(cols, rows, CV_32F);

  cv::idct(self->mat, result);

  info.GetReturnValue().Set(CreateWrappedFromMat(result));
}

NAN_METHOD(Matrix::AddWeighted) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *src1 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  Matrix *src2 = Nan::ObjectWrap::Unwrap<Matrix>(info[2]->ToObject());

  float alpha = info[1]->NumberValue();
  float beta = info[3]->NumberValue();
  int gamma = 0;

  try {
    cv::addWeighted(src1->mat, alpha, src2->mat, beta, gamma, self->mat);
  } catch(cv::Exception& e ) {
    const char* err_msg = e.what();
    Nan::ThrowError(err_msg);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Add) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int cols = self->mat.cols;
  int rows = self->mat.rows;

  Matrix *src1 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  try {
    cv::Mat outputmat = cv::Mat(cols, rows, self->mat.type());
    cv::add(self->mat, src1->mat, outputmat);
    Local<Object> out = CreateWrappedFromMat(outputmat);
    info.GetReturnValue().Set(out);
  } catch(cv::Exception& e ) {
    const char* err_msg = e.what();
    Nan::ThrowError(err_msg);
  }
}

NAN_METHOD(Matrix::BitwiseXor) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *src1 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  Matrix *src2 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());

  if (info.Length() == 3) {
    Matrix *mask = Nan::ObjectWrap::Unwrap<Matrix>(info[2]->ToObject());
    cv::bitwise_xor(src1->mat, src2->mat, self->mat, mask->mat);
  } else {
    cv::bitwise_xor(src1->mat, src2->mat, self->mat);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::BitwiseNot) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *dst = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  if (info.Length() == 2) {
    Matrix *mask = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());
    cv::bitwise_not(self->mat, dst->mat, mask->mat);
  } else {
    cv::bitwise_not(self->mat, dst->mat);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::BitwiseAnd) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *src1 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  Matrix *src2 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());
  if (info.Length() == 3) {
    Matrix *mask = Nan::ObjectWrap::Unwrap<Matrix>(info[2]->ToObject());
    cv::bitwise_and(src1->mat, src2->mat, self->mat, mask->mat);
  } else {
    cv::bitwise_and(src1->mat, src2->mat, self->mat);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::CountNonZero) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  double count = (double)cv::countNonZero(self->mat);

  info.GetReturnValue().Set(Nan::New<Number>(count));
}

/*
NAN_METHOD(Matrix::Split) {
  Nan::HandleScope scope;

  //Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  info.GetReturnValue().Set(Nan::Null());
} */

NAN_METHOD(Matrix::Moments) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  cv::Moments mo = moments( self->mat, false );

  Local<Object> res = Nan::New<Object>();

  res->Set(Nan::New("m00").ToLocalChecked(), Nan::New<Number>(mo.m00));
  res->Set(Nan::New("m10").ToLocalChecked(), Nan::New<Number>(mo.m10));
  res->Set(Nan::New("m01").ToLocalChecked(), Nan::New<Number>(mo.m01));
  res->Set(Nan::New("m20").ToLocalChecked(), Nan::New<Number>(mo.m20));
  res->Set(Nan::New("m11").ToLocalChecked(), Nan::New<Number>(mo.m11));
  res->Set(Nan::New("m02").ToLocalChecked(), Nan::New<Number>(mo.m02));
  res->Set(Nan::New("m30").ToLocalChecked(), Nan::New<Number>(mo.m30));
  res->Set(Nan::New("m21").ToLocalChecked(), Nan::New<Number>(mo.m21));
  res->Set(Nan::New("m12").ToLocalChecked(), Nan::New<Number>(mo.m12));
  res->Set(Nan::New("m03").ToLocalChecked(), Nan::New<Number>(mo.m03));

  res->Set(Nan::New("mu20").ToLocalChecked(), Nan::New<Number>(mo.mu20));
  res->Set(Nan::New("mu11").ToLocalChecked(), Nan::New<Number>(mo.mu11));
  res->Set(Nan::New("mu02").ToLocalChecked(), Nan::New<Number>(mo.mu02));
  res->Set(Nan::New("mu30").ToLocalChecked(), Nan::New<Number>(mo.mu30));
  res->Set(Nan::New("mu21").ToLocalChecked(), Nan::New<Number>(mo.mu21));
  res->Set(Nan::New("mu12").ToLocalChecked(), Nan::New<Number>(mo.mu12));
  res->Set(Nan::New("mu03").ToLocalChecked(), Nan::New<Number>(mo.mu03));

  res->Set(Nan::New("nu20").ToLocalChecked(), Nan::New<Number>(mo.nu20));
  res->Set(Nan::New("nu11").ToLocalChecked(), Nan::New<Number>(mo.nu11));
  res->Set(Nan::New("nu02").ToLocalChecked(), Nan::New<Number>(mo.nu02));
  res->Set(Nan::New("nu30").ToLocalChecked(), Nan::New<Number>(mo.nu30));
  res->Set(Nan::New("nu21").ToLocalChecked(), Nan::New<Number>(mo.nu21));
  res->Set(Nan::New("nu12").ToLocalChecked(), Nan::New<Number>(mo.nu12));
  res->Set(Nan::New("nu03").ToLocalChecked(), Nan::New<Number>(mo.nu03));

  info.GetReturnValue().Set(res);
}

NAN_METHOD(Matrix::Canny) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int lowThresh = info[0]->NumberValue();
  int highThresh = info[1]->NumberValue();

  cv::Canny(self->mat, self->mat, lowThresh, highThresh);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Dilate) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int niters = info[0]->NumberValue();

  cv::Mat kernel = cv::Mat();
  if (info.Length() == 2) {
    Matrix *kernelMatrix = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());
    kernel = kernelMatrix->mat;
  }

  cv::dilate(self->mat, self->mat, kernel, cv::Point(-1, -1), niters);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::Erode) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int niters = info[0]->NumberValue();

  cv::Mat kernel = cv::Mat();
  if (info.Length() == 2) {
    Matrix *kernelMatrix = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());
    kernel = kernelMatrix->mat;
  }
  cv::erode(self->mat, self->mat, kernel, cv::Point(-1, -1), niters);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::FindContours) {
  Nan::HandleScope scope;

  int mode = CV_RETR_LIST;
  int chain = CV_CHAIN_APPROX_SIMPLE;

  if (info.Length() > 0) {
    if (info[0]->IsNumber()) mode = info[0]->IntegerValue();
  }

  if (info.Length() > 1) {
    if (info[1]->IsNumber()) chain = info[1]->IntegerValue();
  }

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Local<Object> conts_to_return = Nan::NewInstance(Nan::GetFunction(Nan::New(Contour::constructor)).ToLocalChecked()).ToLocalChecked();
  Contour *contours = Nan::ObjectWrap::Unwrap<Contour>(conts_to_return);

  cv::findContours(self->mat, contours->contours, contours->hierarchy, mode, chain);

  info.GetReturnValue().Set(conts_to_return);

}

NAN_METHOD(Matrix::DrawContour) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Contour *cont = Nan::ObjectWrap::Unwrap<Contour>(info[0]->ToObject());
  int pos = info[1]->NumberValue();
  cv::Scalar color(0, 0, 255);

  if (info[2]->IsArray()) {
    Local<Object> objColor = info[2]->ToObject();
    color = setColor(objColor);
  }

  int thickness = info.Length() < 4 ? 1 : info[3]->NumberValue();
  int lineType = info.Length() < 5 ? 8 : info[4]->NumberValue();
  int maxLevel = info.Length() < 6 ? 0 : info[5]->NumberValue();

  cv::Point offset;
  if (info.Length() == 6) {
    Local<Array> _offset = Local<Array>::Cast(info[5]);
    offset = cv::Point(
            Nan::To<int>(Nan::Get(_offset, 0).ToLocalChecked()).FromJust(),
            Nan::To<int>(Nan::Get(_offset, 1).ToLocalChecked()).FromJust()
    );
  }

  cv::drawContours(self->mat, cont->contours, pos, color, thickness, lineType, cont->hierarchy, maxLevel, offset);

  return;
}

NAN_METHOD(Matrix::DrawAllContours) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Contour *cont = Nan::ObjectWrap::Unwrap<Contour>(info[0]->ToObject());
  cv::Scalar color(0, 0, 255);

  if (info[1]->IsArray()) {
    Local<Object> objColor = info[1]->ToObject();
    color = setColor(objColor);
  }

  int thickness = info.Length() < 3 ? 1 : info[2]->NumberValue();
  cv::drawContours(self->mat, cont->contours, -1, color, thickness);

  return;
}

NAN_METHOD(Matrix::GoodFeaturesToTrack) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int maxCorners = info.Length() >= 1 ? info[0]->IntegerValue() : 500;
  double qualityLevel = info.Length() >= 2 ? (double) info[1]->NumberValue() : 0.01;
  double minDistance = info.Length() >= 3 ? (double) info[2]->NumberValue() : 10;
  int blockSize = info.Length() >= 4 ? info[3]->IntegerValue() : 3;
  bool useHarrisDetector = info.Length() >= 5 ? info[4]->BooleanValue() : false;
  double k = info.Length() >= 6 ? (double) info[5]->NumberValue() : 0.04;

  std::vector<cv::Point2f> corners;
  cv::Mat gray;

   if (self->mat.channels() == 1) {
     gray = self->mat;
   } else {
     cvtColor(self->mat, gray, CV_BGR2GRAY);
     equalizeHist(gray, gray);
   }

  cv::goodFeaturesToTrack(gray, corners, maxCorners, qualityLevel, minDistance, cv::noArray(), blockSize, useHarrisDetector, k);
  v8::Local<v8::Array> arr = Nan::New<Array>(corners.size());

  for (unsigned int i=0; i<corners.size(); i++) {
    v8::Local<v8::Array> pt = Nan::New<Array>(2);
    pt->Set(0, Nan::New<Number>((double) corners[i].x));
    pt->Set(1, Nan::New<Number>((double) corners[i].y));
    arr->Set(i, pt);
  }

  info.GetReturnValue().Set(arr);
}

#ifdef HAVE_OPENCV_VIDEO
NAN_METHOD(Matrix::CalcOpticalFlowPyrLK) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *newMatrix = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  Local<Array> points = Local<Array>::Cast(info[1]->ToObject());
  std::vector<cv::Point2f> old_points;

  for (unsigned int i=0; i<points->Length(); i++) {
    Local<Object> pt = points->Get(i)->ToObject();
    old_points.push_back(cv::Point2f(pt->Get(0)->NumberValue(), pt->Get(1)->NumberValue()));
  }

  cv::Size winSize;
  if (info.Length() >= 3 && info[2]->IsArray()) {
    Local<Object> winSizeObj = info[2]->ToObject();
    winSize = cv::Size(winSizeObj->Get(0)->IntegerValue(), winSizeObj->Get(1)->IntegerValue());
  } else {
    winSize = cv::Size(21, 21);
  }

  int maxLevel = info.Length() >= 4 ? info[3]->IntegerValue() : 3;

  cv::TermCriteria criteria;
  if (info.Length() >= 5 && info[4]->IsArray()) {
    Local<Object> criteriaObj = info[4]->ToObject();
    criteria = cv::TermCriteria(criteriaObj->Get(0)->IntegerValue(), criteriaObj->Get(1)->IntegerValue(), (double) criteriaObj->Get(2)->NumberValue());
  } else {
    criteria = cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 30, 0.01);
  }

  int flags = info.Length() >= 6 ? info[5]->IntegerValue() : 0;
  double minEigThreshold = info.Length() >= 7 ? info[6]->NumberValue() : 1e-4;

  cv::Mat old_gray;
  cv::cvtColor(self->mat, old_gray, CV_BGR2GRAY);

  cv::Mat new_gray;
  cv::cvtColor(newMatrix->mat, new_gray, CV_BGR2GRAY);

  std::vector<cv::Point2f> new_points;
  std::vector<uchar> status;
  std::vector<float> err;

  cv::calcOpticalFlowPyrLK(old_gray, new_gray, old_points, new_points, status, err, winSize, maxLevel, criteria, flags, minEigThreshold);

  v8::Local<v8::Array> old_arr = Nan::New<Array>(old_points.size());
  v8::Local<v8::Array> new_arr = Nan::New<Array>(new_points.size());
  v8::Local<v8::Array> found = Nan::New<Array>(status.size());

  for (unsigned int i=0; i<old_points.size(); i++) {
    v8::Local<v8::Array> pt = Nan::New<Array>(2);
    pt->Set(0, Nan::New<Number>((double) old_points[i].x));
    pt->Set(1, Nan::New<Number>((double) old_points[i].y));
    old_arr->Set(i, pt);
  }

  for (unsigned int i=0; i<new_points.size(); i++) {
    v8::Local<v8::Array> pt = Nan::New<Array>(2);
    pt->Set(0, Nan::New<Number>((double) new_points[i].x));
    pt->Set(1, Nan::New<Number>((double) new_points[i].y));
    new_arr->Set(i, pt);
  }

  for (unsigned int i=0; i<status.size(); i++) {
    v8::Local<v8::Integer> pt = Nan::New<Integer>((int)status[i]);
    found->Set(i, pt);
  }

  Local<Object> data = Nan::New<Object>();
  data->Set(Nan::New<String>("old_points").ToLocalChecked(), old_arr);
  data->Set(Nan::New<String>("new_points").ToLocalChecked(), new_arr);
  data->Set(Nan::New<String>("found").ToLocalChecked(), found);

  info.GetReturnValue().Set(data);
}
#endif

NAN_METHOD(Matrix::HoughLinesP) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  double rho = info.Length() < 1 ? 1 : info[0]->NumberValue();
  double theta = info.Length() < 2 ? CV_PI/180 : info[1]->NumberValue();
  int threshold = info.Length() < 3 ? 80 : info[2]->Uint32Value();
  double minLineLength = info.Length() < 4 ? 30 : info[3]->NumberValue();
  double maxLineGap = info.Length() < 5 ? 10 : info[4]->NumberValue();
  std::vector<cv::Vec4i> lines;

  cv::Mat gray;

  equalizeHist(self->mat, gray);
  // cv::Canny(gray, gray, 50, 200, 3);
  cv::HoughLinesP(gray, lines, rho, theta, threshold, minLineLength, maxLineGap);

  v8::Local<v8::Array> arr = Nan::New<Array>(lines.size());

  for (unsigned int i=0; i<lines.size(); i++) {
    v8::Local<v8::Array> pt = Nan::New<Array>(4);
    pt->Set(0, Nan::New<Number>((double) lines[i][0]));
    pt->Set(1, Nan::New<Number>((double) lines[i][1]));
    pt->Set(2, Nan::New<Number>((double) lines[i][2]));
    pt->Set(3, Nan::New<Number>((double) lines[i][3]));
    arr->Set(i, pt);
  }

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::HoughCircles) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  double dp = info.Length() < 1 ? 1 : info[0]->NumberValue();
  double minDist = info.Length() < 2 ? 1 : info[1]->NumberValue();
  double higherThreshold = info.Length() < 3 ? 100 : info[2]->NumberValue();
  double accumulatorThreshold = info.Length() < 4 ? 100 : info[3]->NumberValue();
  int minRadius = info.Length() < 5 ? 0 : info[4]->Uint32Value();
  int maxRadius = info.Length() < 6 ? 0 : info[5]->Uint32Value();
  std::vector<cv::Vec3f> circles;

  cv::Mat gray;

  equalizeHist(self->mat, gray);

  cv::HoughCircles(gray, circles, CV_HOUGH_GRADIENT, dp, minDist,
      higherThreshold, accumulatorThreshold, minRadius, maxRadius);

  v8::Local<v8::Array> arr = Nan::New<Array>(circles.size());

  for (unsigned int i=0; i < circles.size(); i++) {
    v8::Local<v8::Array> pt = Nan::New<Array>(3);
    pt->Set(0, Nan::New<Number>((double) circles[i][0]));  // center x
    pt->Set(1, Nan::New<Number>((double) circles[i][1]));// center y
    pt->Set(2, Nan::New<Number>((double) circles[i][2]));// radius
    arr->Set(i, pt);
  }

  info.GetReturnValue().Set(arr);
}

cv::Scalar setColor(Local<Object> objColor) {
  int64_t channels[4] = { 0, 0, 0, 0 };

  // We'll accomodate a channel count up to 4 and fall back to the old
  // "assume it's always 3" in the default case
  if (!objColor->HasRealIndexedProperty(1)) {
    channels[0] = objColor->Get(0)->IntegerValue();
  } else if (!objColor->HasRealIndexedProperty(2)) {
    channels[0] = objColor->Get(0)->IntegerValue();
    channels[1] = objColor->Get(1)->IntegerValue();
  } else if (!objColor->HasRealIndexedProperty(4)) {
    channels[0] = objColor->Get(0)->IntegerValue();
    channels[1] = objColor->Get(1)->IntegerValue();
    channels[2] = objColor->Get(2)->IntegerValue();
    channels[3] = objColor->Get(3)->IntegerValue();
  } else {
    channels[0] = objColor->Get(0)->IntegerValue();
    channels[1] = objColor->Get(1)->IntegerValue();
    channels[2] = objColor->Get(2)->IntegerValue();
  }

  return cv::Scalar(channels[0], channels[1], channels[2], channels[3]);
}

cv::Point setPoint(Local<Object> objPoint) {
  return cv::Point(objPoint->Get(0)->IntegerValue(),
      objPoint->Get(1)->IntegerValue());
}

cv::Rect* setRect(Local<Object> objRect, cv::Rect &result) {
  if (!objRect->IsArray() || !objRect->Get(0)->IsArray()
      || !objRect->Get(0)->IsArray()) {
    printf("error");
    return 0;
  };

  Local < Object > point = objRect->Get(0)->ToObject();
  Local < Object > size = objRect->Get(1)->ToObject();

  result.x = point->Get(0)->IntegerValue();
  result.y = point->Get(1)->IntegerValue();
  result.width = size->Get(0)->IntegerValue();
  result.height = size->Get(1)->IntegerValue();

  return &result;
}


class ResizeASyncWorker: public Nan::AsyncWorker {
public:
  ResizeASyncWorker(Nan::Callback *callback, Matrix *image, cv::Size size, double fx, double fy, int interpolation) :
      Nan::AsyncWorker(callback),
      image(new Matrix(image)),
      dest(cv::Mat()),
      size(size),
      fx(fx),
      fy(fy),
      interpolation(interpolation),
      success(0) {
  }
    
  ~ResizeASyncWorker() {
    // Any cleanup we needed to do could be done here.
    // Clean up of the input image Matrix and the destination cv::Mat
    // should be handled automatically by destructors.
  }

  void Execute() {
    try {
        cv::resize(image->mat, dest, size, fx, fy, interpolation);
        success = 1;
    } catch(...){
        success = 0;
    }
  }

  void HandleOKCallback() {
    Nan::HandleScope scope;

    delete image;
    image = NULL;
    
    if (success){
        try{
            Local<Object> im_to_return = Matrix::CreateWrappedFromMat(dest);
            dest.release(); //release our refcount before handing it back to the callback

            Local<Value> argv[] = {
              Nan::Null(), // err
              im_to_return //result
            };

            Nan::TryCatch try_catch;
            callback->Call(2, argv);
            if (try_catch.HasCaught()) {
              Nan::FatalException(try_catch);
            }
        } catch (...){
            Local<Value> argv[] = {
              Nan::New("C++ exception wrapping response").ToLocalChecked(), // err
              Nan::Null() // result
            };

            Nan::TryCatch try_catch;
            callback->Call(2, argv);
            if (try_catch.HasCaught()) {
              Nan::FatalException(try_catch);
            }
        }
    } else {
        Local<Value> argv[] = {
          Nan::New("C++ exception").ToLocalChecked(), // err
          Nan::Null() //result
        };

        Nan::TryCatch try_catch;
        callback->Call(2, argv);
        if (try_catch.HasCaught()) {
          Nan::FatalException(try_catch);
        }
    }
  }

private:
  Matrix *image;
  cv::Mat dest;
  cv::Size size;
  double fx;
  double fy;
  int interpolation;
  int success;

};


NAN_METHOD(Matrix::Resize) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 2) {
    return Nan::ThrowError("Matrix.resize requires at least 2 argument2");
  }

  //im.resize( width, height );
  //im.resize( width, height, fx, fy );
  //im.resize( width, height, interpolation );
  //im.resize( width, height, fx, fy, interpolation );
  // if fn is added on the end, makes it Async
  
  int numargs = info.Length();
  int isAsync = 0;
  
  if (info[numargs-1]->IsFunction()){
      isAsync = 1;
  }

  if (info.Length() < 2+isAsync) {
    return Nan::ThrowError("Matrix.resize requires at least x and y size argument2");
  }

  int x = info[0]->Uint32Value();
  int y = info[1]->Uint32Value();

  cv::Size size(x, y);
  
  if (size.area() == 0) {
    return Nan::ThrowError("Area of size must be > 0");
  }

  double fx = 0;
  double fy = 0;
  int interpolation = cv::INTER_LINEAR;

  // if 4 or more args, then expect fx, fy next
  if (numargs >= 4+isAsync) {
    DOUBLE_FROM_ARGS(fx, 2)
    DOUBLE_FROM_ARGS(fy, 3)
    if (numargs == 5+isAsync) {
      INT_FROM_ARGS(interpolation, 5)
    }
  } else {
    // if 3 args after possible function, expect interpolation
    if (numargs == 3+isAsync) {
      INT_FROM_ARGS(interpolation, 3)
    }
  }
  
  // if async
  if (isAsync){
    REQ_FUN_ARG(numargs-1, cb);
    Nan::Callback *callback = new Nan::Callback(cb.As<Function>());
    Nan::AsyncQueueWorker(new ResizeASyncWorker(callback, self, size, fx, fy, interpolation));
    info.GetReturnValue().Set(Nan::Null());
  } else {
    try{
        Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
        cv::Mat res = cv::Mat(x, y, CV_32FC3);
        cv::resize(self->mat, res, cv::Size(x, y), 0, 0, interpolation);
        self->setMat(res);
    } catch (...){
        return Nan::ThrowError("c++ Exception processing resize");
    }
  }
}

NAN_METHOD(Matrix::Rotate) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  cv::Mat rotMatrix(2, 3, CV_32FC1);
  cv::Mat res;

  float angle = Nan::To<double>(info[0]).FromJust();

  // Modification by SergeMv
  //-------------
  // If you provide only the angle argument and the angle is multiple of 90, then
  // we do a fast thing
  bool rightOrStraight = (ceil(angle) == angle) && (!((int)angle % 90))
      && (info.Length() == 1);
  if (rightOrStraight) {
    int angle2 = ((int)angle) % 360;
    if (!angle2) {return;}
    if (angle2 < 0) {angle2 += 360;}
    // See if we do right angle rotation, we transpose the matrix:
    if (angle2 % 180) {
      cv::transpose(self->mat, res);
      self->setMat(res);
    }
    // Now flip the image
    int mode = -1;// flip around both axes
    // If counterclockwise, flip around the x-axis
    if (angle2 == 90) {mode = 0;}
    // If clockwise, flip around the y-axis
    if (angle2 == 270) {mode = 1;}
    cv::flip(self->mat, self->mat, mode);
    return;
  }

  //-------------
  int x = info[1]->IsUndefined() ? round(self->mat.size().width / 2) :
      info[1]->Uint32Value();
  int y = info[1]->IsUndefined() ? round(self->mat.size().height / 2) :
      info[2]->Uint32Value();

  cv::Point center = cv::Point(x,y);
  rotMatrix = getRotationMatrix2D(center, angle, 1.0);

  cv::warpAffine(self->mat, res, rotMatrix, self->mat.size());
  self->setMat(res);

  return;
}

NAN_METHOD(Matrix::GetRotationMatrix2D) {
  Nan::HandleScope scope;
  if (info.Length() < 3) {
    JSTHROW("Invalid number of arguments");
  }

  float angle = Nan::To<double>(info[0]).FromJust();
  int x = Nan::To<uint32_t>(info[1]).FromJust();
  int y = Nan::To<uint32_t>(info[2]).FromJust();
  double scale = Nan::To<double>(info[3]).FromMaybe(1.0);

  cv::Point center = cv::Point(x,y);
  Local<Object> img_to_return = Matrix::CreateWrappedFromMat(getRotationMatrix2D(center, angle, scale));

  info.GetReturnValue().Set(img_to_return);
}

NAN_METHOD(Matrix::WarpAffine) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  cv::Mat res;

  Matrix *rotMatrix = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  // Resize the image if size is specified
  int dstRows = info[1]->IsUndefined() ? self->mat.rows : info[1]->Uint32Value();
  int dstCols = info[2]->IsUndefined() ? self->mat.cols : info[2]->Uint32Value();
  cv::Size resSize = cv::Size(dstRows, dstCols);

  cv::warpAffine(self->mat, res, rotMatrix->mat, resSize);
  self->setMat(res);

  return;
}

NAN_METHOD(Matrix::PyrDown) {
  SETUP_FUNCTION(Matrix)

  int oldSize = self->mat.dataend - self->mat.datastart;
  cv::pyrDown(self->mat, self->mat);
  int newSize = self->mat.dataend - self->mat.datastart;
  Nan::AdjustExternalMemory(newSize - oldSize);
  return;
}

NAN_METHOD(Matrix::PyrUp) {
  SETUP_FUNCTION(Matrix)

  int oldSize = self->mat.dataend - self->mat.datastart;
  cv::pyrUp(self->mat, self->mat);
  int newSize = self->mat.dataend - self->mat.datastart;
  Nan::AdjustExternalMemory(newSize - oldSize);
  return;
}

NAN_METHOD(Matrix::inRange) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  /*if (self->mat.channels() != 3)
   Nan::ThrowError(String::New("Image is no 3-channel"));*/

  if (info[0]->IsArray() && info[1]->IsArray()) {
    Local<Object> args_lowerb = info[0]->ToObject();
    Local<Object> args_upperb = info[1]->ToObject();

    cv::Scalar lowerb(0, 0, 0);
    cv::Scalar upperb(0, 0, 0);

    lowerb = setColor(args_lowerb);
    upperb = setColor(args_upperb);

    cv::Mat mask;
    cv::inRange(self->mat, lowerb, upperb, mask);
    mask.copyTo(self->mat);
  }

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::AdjustROI) {
  SETUP_FUNCTION(Matrix)
  int dtop = info[0]->Uint32Value();
  int dbottom = info[1]->Uint32Value();
  int dleft = info[2]->Uint32Value();
  int dright = info[3]->Uint32Value();

  self->mat.adjustROI(dtop, dbottom, dleft, dright);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::LocateROI) {
  SETUP_FUNCTION(Matrix)

  cv::Size wholeSize;
  cv::Point ofs;

  self->mat.locateROI(wholeSize, ofs);

  v8::Local < v8::Array > arr = Nan::New<Array>(4);
  arr->Set(0, Nan::New<Number>(wholeSize.width));
  arr->Set(1, Nan::New<Number>(wholeSize.height));
  arr->Set(2, Nan::New<Number>(ofs.x));
  arr->Set(3, Nan::New<Number>(ofs.y));

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::Threshold) {
  SETUP_FUNCTION(Matrix)

  double threshold = info[0]->NumberValue();
  double maxVal = info[1]->NumberValue();
  int typ = cv::THRESH_BINARY;

  if (info.Length() >= 3) {
    Nan::Utf8String typstr(info[2]);

    if (strcmp(*typstr, "Binary") == 0) {
      // Uses default value
    }
    else if (strcmp(*typstr, "Binary Inverted") == 0) {
      typ = cv::THRESH_BINARY_INV;
    }
    else if (strcmp(*typstr, "Threshold Truncated") == 0) {
      typ = cv::THRESH_TRUNC;
    }
    else if (strcmp(*typstr, "Threshold to Zero") == 0) {
      typ = cv::THRESH_TOZERO;
    }
    else if (strcmp(*typstr, "Threshold to Zero Inverted") == 0) {
      typ = cv::THRESH_TOZERO_INV;
    }
    else {
      char *typeString = *typstr;
      char text[] = "\" is no supported binarization technique. "
        "Use \"Binary\" (default), \"Binary Inverted\", "
        "\"Threshold Truncated\", \"Threshold to Zero\" "
        "or \"Threshold to Zero Inverted\"";
      char *errorMessage;
      errorMessage = new char[strlen(typeString) + strlen(text) + 2];
      strcpy(errorMessage, "\"");
      strcat(errorMessage, typeString);
      strcat(errorMessage, text);

      Nan::ThrowError(errorMessage);
      return;
    }
  }

  if (info.Length() >= 4) {
    Nan::Utf8String algorithm(info[3]);

    if (strcmp(*algorithm, "Simple") == 0) {
        // Uses default
    }
    else if (strcmp(*algorithm, "Otsu") == 0) {
      typ += 8;
    }
    else {
      char *algo = *algorithm;
      char text[] = "\" is no supported threshold algorithm. "
        "Use \"Simple\" (default) or \"Otsu\".";
      char *errorMessage;
      errorMessage = new char[strlen(algo) + strlen(text) + 2];
      strcpy(errorMessage, "\"");
      strcat(errorMessage, algo);
      strcat(errorMessage, text);

      Nan::ThrowError(errorMessage);
      return;
    }
  }

  cv::Mat outputmat = cv::Mat();
  self->mat.copyTo(outputmat);

  cv::threshold(self->mat, outputmat, threshold, maxVal, typ);

  Local < Object > img_to_return = CreateWrappedFromMat(outputmat);

  info.GetReturnValue().Set(img_to_return);
}

NAN_METHOD(Matrix::AdaptiveThreshold) {
  SETUP_FUNCTION(Matrix)

  double maxVal = info[0]->NumberValue();
  double adaptiveMethod = info[1]->NumberValue();
  double thresholdType = info[2]->NumberValue();
  double blockSize = info[3]->NumberValue();
  double C = info[4]->NumberValue();

  cv::Mat outputmat = cv::Mat();
  self->mat.copyTo(outputmat);

  cv::adaptiveThreshold(self->mat, outputmat, maxVal, adaptiveMethod,
      thresholdType, blockSize, C);
  
  Local < Object > img_to_return = CreateWrappedFromMat(outputmat);

  info.GetReturnValue().Set(img_to_return);
}

NAN_METHOD(Matrix::MeanStdDev) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  cv::Mat meanMat = cv::Mat();
  cv::Mat stddevMat = cv::Mat();

  cv::meanStdDev(self->mat, meanMat, stddevMat);

  Local<Object> data = Nan::New<Object>();
  data->Set(Nan::New<String>("mean").ToLocalChecked(), CreateWrappedFromMat(meanMat));
  data->Set(Nan::New<String>("stddev").ToLocalChecked(), CreateWrappedFromMat(stddevMat));

  info.GetReturnValue().Set(data);
}

// @author SergeMv
// Copies our (small) image into a ROI of another (big) image
// @param Object another image (destination)
// @param Number Destination x (where our image is to be copied)
// @param Number Destination y (where our image is to be copied)
// Example: smallImg.copyTo(bigImg, 50, 50);
// Note, x,y and width and height of our image must be so that
// our.width + x <= destination.width (and the same for y and height)
// both x and y must be >= 0
NAN_METHOD(Matrix::CopyTo) {
  Nan::HandleScope scope;

  Matrix * self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  int width = self->mat.size().width;
  int height = self->mat.size().height;

  // param 0 - destination image:
  Matrix *dest = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  // param 1 - x coord of the destination
  int x = info[1]->IntegerValue();
  // param 2 - y coord of the destination
  int y = info[2]->IntegerValue();

  cv::Mat dstROI = cv::Mat(dest->mat, cv::Rect(x, y, width, height));
  self->mat.copyTo(dstROI);

  return;
}

/**
 * Converts an array to another data type with optional scaling
 * Reference: http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-convertto
 */
NAN_METHOD(Matrix::ConvertTo) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 2) {
    JSTHROW("Invalid number of arguments");
  }

  // param 0 - destination image
  Matrix *dest = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  // param 1 - desired matrix type
  int rtype = -1;
  INT_FROM_ARGS(rtype, 1);

  // param 2 - alpha
  double alpha = 1;
  if (info.Length() >= 3) {
    DOUBLE_FROM_ARGS(alpha, 2);
  }

  // param 3 - beta
  double beta = 0;
  if (info.Length() >= 4) {
    DOUBLE_FROM_ARGS(beta, 3);
  }

  self->mat.convertTo(dest->mat, rtype, alpha, beta);

  return;
}

// @author SergeMv
// Does in-place color transformation
// img.cvtColor('CV_BGR2YCrCb');
NAN_METHOD(Matrix::CvtColor) {
  Nan::HandleScope scope;

  Matrix * self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  if (info.Length() < 1) {
    Nan::ThrowTypeError("Invalid number of arguments");
  }

  // Get transform string
  v8::String::Utf8Value str (info[0]->ToString());
  std::string str2 = std::string(*str);
  const char * sTransform = (const char *) str2.c_str();
  int iTransform;

  if (!strcmp(sTransform, "CV_BGR2GRAY")) {
    iTransform = CV_BGR2GRAY;
  } else if (!strcmp(sTransform, "CV_GRAY2BGR")) {
    iTransform = CV_GRAY2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2XYZ")) {
    iTransform = CV_BGR2XYZ;
  } else if (!strcmp(sTransform, "CV_XYZ2BGR")) {
    iTransform = CV_XYZ2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2YCrCb")) {
    iTransform = CV_BGR2YCrCb;
  } else if (!strcmp(sTransform, "CV_YCrCb2BGR")) {
    iTransform = CV_YCrCb2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2HSV")) {
    iTransform = CV_BGR2HSV;
  } else if (!strcmp(sTransform, "CV_HSV2BGR")) {
    iTransform = CV_HSV2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2HLS")) {
    iTransform = CV_BGR2HLS;
  } else if (!strcmp(sTransform, "CV_HLS2BGR")) {
    iTransform = CV_HLS2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2Lab")) {
    iTransform = CV_BGR2Lab;
  } else if (!strcmp(sTransform, "CV_Lab2BGR")) {
    iTransform = CV_Lab2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2Luv")) {
    iTransform = CV_BGR2Luv;
  } else if (!strcmp(sTransform, "CV_Luv2BGR")) {
    iTransform = CV_Luv2BGR;
  } else if (!strcmp(sTransform, "CV_BayerBG2BGR")) {
    iTransform = CV_BayerBG2BGR;
  } else if (!strcmp(sTransform, "CV_BayerGB2BGR")) {
    iTransform = CV_BayerGB2BGR;
  } else if (!strcmp(sTransform, "CV_BayerRG2BGR")) {
    iTransform = CV_BayerRG2BGR;
  } else if (!strcmp(sTransform, "CV_BayerGR2BGR")) {
    iTransform = CV_BayerGR2BGR;
  } else if (!strcmp(sTransform, "CV_BGR2RGB")) {
    iTransform = CV_BGR2RGB;
  } else if (!strcmp(sTransform, "CV_BGRA2BGR")) {
    iTransform = CV_BGRA2BGR;
  } else {
    iTransform = 0;  // to avoid compiler warning
    Nan::ThrowTypeError("Conversion code is unsupported");
  }

  int oldSize = self->mat.dataend - self->mat.datastart;
  cv::cvtColor(self->mat, self->mat, iTransform);
  int newSize = self->mat.dataend - self->mat.datastart;
  if(oldSize != newSize){
    Nan::AdjustExternalMemory(newSize - oldSize);
  }

  return;
}

// @author SergeMv
// arrChannels = img.split();
NAN_METHOD(Matrix::Split) {
  Nan::HandleScope scope;

  Matrix * self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  unsigned int size = self->mat.channels();
  std::vector<cv::Mat> channels;

  // Split doesn't seem to work on empty vectors
  for (unsigned int i = 0; i < size; i++) {
    channels.push_back(cv::Mat());
  }

  cv::split(self->mat, channels);
  size = channels.size();
  v8::Local<v8::Array> arrChannels = Nan::New<Array>(size);
  for (unsigned int i = 0; i < size; i++) {
    Local<Object> matObject = Matrix::CreateWrappedFromMatIfNotReferenced(channels[i], 1);
    arrChannels->Set(i, matObject);
  }

  info.GetReturnValue().Set(arrChannels);
}

// @author SergeMv
// img.merge(arrChannels);
NAN_METHOD(Matrix::Merge) {
  Nan::HandleScope scope;

  Matrix * self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  if (!info[0]->IsArray()) {
    Nan::ThrowTypeError("The argument must be an array");
  }
  int oldSize = self->mat.dataend - self->mat.datastart;
  v8::Local<v8::Array> jsChannels = v8::Local<v8::Array>::Cast(info[0]);

  unsigned int L = jsChannels->Length();
  std::vector<cv::Mat> vChannels(L);
  for (unsigned int i = 0; i < L; i++) {
    Matrix * matObject = Nan::ObjectWrap::Unwrap<Matrix>(jsChannels->Get(i)->ToObject());
    vChannels[i] = matObject->mat;
  }
  cv::merge(vChannels, self->mat);
  int newSize = self->mat.dataend - self->mat.datastart;
  Nan::AdjustExternalMemory(newSize - oldSize);

  return;
}

// @author SergeMv
// Equalizes histogram
// img.equalizeHist()
NAN_METHOD(Matrix::EqualizeHist) {
  Nan::HandleScope scope;
  Matrix * self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  cv::equalizeHist(self->mat, self->mat);

  return;
}

NAN_METHOD(Matrix::FloodFill) {
  SETUP_FUNCTION(Matrix)
  // obj->Get(Nan::New<String>("x").ToLocalChecked())
  // int cv::floodFill(cv::InputOutputArray, cv::Point, cv::Scalar, cv::Rect*, cv::Scalar, cv::Scalar, int)

  /*  mat.floodFill( {seedPoint: [1,1] ,
        newColor: [255,0,0] ,
        rect:[[0,2],[30,40]] ,
        loDiff : [8,90,60],
        upDiff:[10,100,70]
      }); */

  if (info.Length() < 1 || !info[0]->IsObject()) {
    // error
  }

  Local < Object > obj = info[0]->ToObject();
  cv::Rect rect;

  int ret = cv::floodFill(self->mat,
      setPoint(obj->Get(Nan::New<String>("seedPoint").ToLocalChecked())->ToObject()),
      setColor(obj->Get(Nan::New<String>("newColor").ToLocalChecked())->ToObject()),
      obj->Get(Nan::New<String>("rect").ToLocalChecked())->IsUndefined() ?
          0 : setRect(obj->Get(Nan::New<String>("rect").ToLocalChecked())->ToObject(), rect),
      setColor(obj->Get(Nan::New<String>("loDiff").ToLocalChecked())->ToObject()),
      setColor(obj->Get(Nan::New<String>("upDiff").ToLocalChecked())->ToObject()), 4);

  info.GetReturnValue().Set(Nan::New<Number>(ret));
}

// @author olfox
// Returns an array of the most probable positions
// Usage: output = input.templateMatches(min_probability, max_probability, limit, ascending, min_x_distance, min_y_distance);
NAN_METHOD(Matrix::TemplateMatches) {
  SETUP_FUNCTION(Matrix)

  bool filter_min_probability =
      (info.Length() >= 1) ? info[0]->IsNumber() : false;
  bool filter_max_probability =
      (info.Length() >= 2) ? info[1]->IsNumber() : false;
  double min_probability = filter_min_probability ? info[0]->NumberValue() : 0;
  double max_probability = filter_max_probability ? info[1]->NumberValue() : 0;
  int limit = (info.Length() >= 3) ? info[2]->IntegerValue() : 0;
  bool ascending = (info.Length() >= 4) ? info[3]->BooleanValue() : false;
  int min_x_distance = (info.Length() >= 5) ? info[4]->IntegerValue() : 0;
  int min_y_distance = (info.Length() >= 6) ? info[5]->IntegerValue() : 0;

  cv::Mat_<int> indices;

  if (ascending) {
    cv::sortIdx(self->mat.reshape(0, 1), indices,
    CV_SORT_ASCENDING + CV_SORT_EVERY_ROW);
  } else {
    cv::sortIdx(self->mat.reshape(0, 1), indices,
    CV_SORT_DESCENDING + CV_SORT_EVERY_ROW);
  }

  cv::Mat hit_mask = cv::Mat::zeros(self->mat.size(), CV_64F);
  v8::Local < v8::Array > probabilites_array = Nan::New<v8::Array>(limit);

  cv::Mat_<float>::const_iterator begin = self->mat.begin<float>();
  cv::Mat_<int>::const_iterator it = indices.begin();
  cv::Mat_<int>::const_iterator end = indices.end();
  int index = 0;

  for (; (limit == 0 || index < limit) && it != end; ++it) {
    cv::Point pt = (begin + *it).pos();

    float probability = self->mat.at<float>(pt.y, pt.x);

    if (filter_min_probability && probability < min_probability) {
      if (ascending) {
        continue;
      }
      else {
        break;
      }
    }

    if (filter_max_probability && probability > max_probability) {
      if (ascending)
        break;
      else
        continue;
    }

    if (min_x_distance != 0 || min_y_distance != 0) {
      // Check hit mask color for for every corner

      cv::Size maxSize = hit_mask.size();
      int max_x = maxSize.width - 1;
      int max_y = maxSize.height - 1;
      cv::Point top_left = cv::Point(std::max(0, pt.x - min_x_distance),
        std::max(0, pt.y - min_y_distance));
      cv::Point top_right = cv::Point(std::min(max_x, pt.x + min_x_distance),
        std::max(0, pt.y - min_y_distance));
      cv::Point bottom_left = cv::Point(std::max(0, pt.x - min_x_distance),
        std::min(max_y, pt.y + min_y_distance));
      cv::Point bottom_right = cv::Point(std::min(max_x, pt.x + min_x_distance),
        std::min(max_y, pt.y + min_y_distance));
      if (hit_mask.at<double>(top_left.y, top_left.x) > 0)
        continue;
      if (hit_mask.at<double>(top_right.y, top_right.x) > 0)
        continue;
      if (hit_mask.at<double>(bottom_left.y, bottom_left.x) > 0)
        continue;
      if (hit_mask.at<double>(bottom_right.y, bottom_right.x) > 0)
        continue;
      cv::Scalar color(255.0);
      cv::rectangle(hit_mask, top_left, bottom_right, color, CV_FILLED);
    }

    Local<Value> x_value = Nan::New<Number>(pt.x);
    Local<Value> y_value = Nan::New<Number>(pt.y);
    Local<Value> probability_value = Nan::New<Number>(probability);

    Local < Object > probability_object = Nan::New<Object>();
    probability_object->Set(Nan::New<String>("x").ToLocalChecked(), x_value);
    probability_object->Set(Nan::New<String>("y").ToLocalChecked(), y_value);
    probability_object->Set(Nan::New<String>("probability").ToLocalChecked(), probability_value);

    probabilites_array->Set(index, probability_object);
    index++;
  }

  info.GetReturnValue().Set(probabilites_array);
}

// @author Evilcat325
// MatchTemplate accept a Matrix
// Usage: output = input.matchTemplateByMatrix(matrix. method);
NAN_METHOD(Matrix::MatchTemplateByMatrix) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *templ = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  int cols = self->mat.cols - templ->mat.cols + 1;
  int rows = self->mat.rows - templ->mat.rows + 1;
  cv::Mat result(cols, rows, CV_32FC1);

  /*
   TM_SQDIFF        =0
   TM_SQDIFF_NORMED =1
   TM_CCORR         =2
   TM_CCORR_NORMED  =3
   TM_CCOEFF        =4
   TM_CCOEFF_NORMED =5
   */

  int method = (info.Length() < 2) ? (int)cv::TM_CCORR_NORMED : info[1]->Uint32Value();
  if (!(method >= 0 && method <= 5)) method = (int)cv::TM_CCORR_NORMED;
  cv::matchTemplate(self->mat, templ->mat, result, method);
  info.GetReturnValue().Set(CreateWrappedFromMat(result));
}

// @author ytham
// Match Template filter
// Usage: output = input.matchTemplate("templateFileString", method);
NAN_METHOD(Matrix::MatchTemplate) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  v8::String::Utf8Value args0(info[0]->ToString());
  std::string filename = std::string(*args0);
  cv::Mat templ;
  templ = cv::imread(filename, -1);

  int cols = self->mat.cols - templ.cols + 1;
  int rows = self->mat.rows - templ.rows + 1;
  cv::Mat result(cols, rows, CV_32FC1);

  /*
   TM_SQDIFF        =0
   TM_SQDIFF_NORMED =1
   TM_CCORR         =2
   TM_CCORR_NORMED  =3
   TM_CCOEFF        =4
   TM_CCOEFF_NORMED =5
   */

  int method = (info.Length() < 2) ? (int)cv::TM_CCORR_NORMED : info[1]->Uint32Value();
  cv::matchTemplate(self->mat, templ, result, method);
  cv::normalize(result, result, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());
  double minVal;
  double maxVal;
  cv::Point minLoc;
  cv::Point maxLoc;
  cv::Point matchLoc;

  minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());

  if(method  == CV_TM_SQDIFF || method == CV_TM_SQDIFF_NORMED) {
    matchLoc = minLoc;
  }
  else {
    matchLoc = maxLoc;
  }

  //detected ROI
  unsigned int roi_x = matchLoc.x;
  unsigned int roi_y = matchLoc.y;
  unsigned int roi_width = templ.cols;
  unsigned int roi_height = templ.rows;

  //draw rectangle
  if(info.Length() >= 3) {
    cv::Rect roi(roi_x,roi_y,roi_width,roi_height);
    cv::rectangle(self->mat, roi, cv::Scalar(0,0,255));
  }

  result.convertTo(result, CV_8UC1, 255, 0);

  v8::Local <v8::Array> arr = Nan::New<v8::Array>(5);
  arr->Set(0, CreateWrappedFromMat(result));
  arr->Set(1, Nan::New<Number>(roi_x));
  arr->Set(2, Nan::New<Number>(roi_y));
  arr->Set(3, Nan::New<Number>(roi_width));
  arr->Set(4, Nan::New<Number>(roi_height));

  info.GetReturnValue().Set(arr);
}

// @author ytham
// Min/Max location
NAN_METHOD(Matrix::MinMaxLoc) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
  cv::minMaxLoc(self->mat, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat() );

  Local<Value> v_minVal = Nan::New<Number>(minVal);
  Local<Value> v_maxVal = Nan::New<Number>(maxVal);
  Local<Value> v_minLoc_x = Nan::New<Number>(minLoc.x);
  Local<Value> v_minLoc_y = Nan::New<Number>(minLoc.y);
  Local<Value> v_maxLoc_x = Nan::New<Number>(maxLoc.x);
  Local<Value> v_maxLoc_y = Nan::New<Number>(maxLoc.y);

  Local<Object> o_minLoc = Nan::New<Object>();
  o_minLoc->Set(Nan::New<String>("x").ToLocalChecked(), v_minLoc_x);
  o_minLoc->Set(Nan::New<String>("y").ToLocalChecked(), v_minLoc_y);

  Local<Object> o_maxLoc = Nan::New<Object>();
  o_maxLoc->Set(Nan::New<String>("x").ToLocalChecked(), v_maxLoc_x);
  o_maxLoc->Set(Nan::New<String>("y").ToLocalChecked(), v_maxLoc_y);

  // Output result object
  Local<Object> result = Nan::New<Object>();
  result->Set(Nan::New<String>("minVal").ToLocalChecked(), v_minVal);
  result->Set(Nan::New<String>("maxVal").ToLocalChecked(), v_maxVal);
  result->Set(Nan::New<String>("minLoc").ToLocalChecked(), o_minLoc);
  result->Set(Nan::New<String>("maxLoc").ToLocalChecked(), o_maxLoc);

  info.GetReturnValue().Set(result);
}

// @author ytham
// Pushes some matrix (argument) the back of a matrix (self)
NAN_METHOD(Matrix::PushBack) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Matrix *m_input = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  self->mat.push_back(m_input->mat);

  info.GetReturnValue().Set(info.This());
}

NAN_METHOD(Matrix::PutText) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  Nan::Utf8String textString(info[0]);  //FIXME: might cause issues, see here https://github.com/rvagg/nan/pull/152
  char *text = *textString;//(char *) malloc(textString.length() + 1);
  //strcpy(text, *textString);

  int x = info[1]->IntegerValue();
  int y = info[2]->IntegerValue();

  Nan::Utf8String fontString(info[3]);
  char *font = *fontString;//(char *) malloc(fontString.length() + 1);
  //strcpy(font, *fontString);
  int constFont = cv::FONT_HERSHEY_SIMPLEX;

  if (!strcmp(font, "HERSEY_SIMPLEX")) {constFont = cv::FONT_HERSHEY_SIMPLEX;}
  else if (!strcmp(font, "HERSEY_PLAIN")) {constFont = cv::FONT_HERSHEY_PLAIN;}
  else if (!strcmp(font, "HERSEY_DUPLEX")) {constFont = cv::FONT_HERSHEY_DUPLEX;}
  else if (!strcmp(font, "HERSEY_COMPLEX")) {constFont = cv::FONT_HERSHEY_COMPLEX;}
  else if (!strcmp(font, "HERSEY_TRIPLEX")) {constFont = cv::FONT_HERSHEY_TRIPLEX;}
  else if (!strcmp(font, "HERSEY_COMPLEX_SMALL")) {constFont = cv::FONT_HERSHEY_COMPLEX_SMALL;}
  else if (!strcmp(font, "HERSEY_SCRIPT_SIMPLEX")) {constFont = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;}
  else if (!strcmp(font, "HERSEY_SCRIPT_COMPLEX")) {constFont = cv::FONT_HERSHEY_SCRIPT_COMPLEX;}
  else if (!strcmp(font, "HERSEY_SCRIPT_SIMPLEX")) {constFont = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;}

  cv::Scalar color(0, 0, 255);

  if (info[4]->IsArray()) {
    Local<Object> objColor = info[4]->ToObject();
    color = setColor(objColor);
  }

  double scale = info.Length() < 6 ? 1 : info[5]->NumberValue();
  double thickness = info.Length() < 7 ? 1 : info[6]->NumberValue();

  cv::putText(self->mat, text, cv::Point(x, y), constFont, scale, color, thickness);

  return;
}

NAN_METHOD(Matrix::GetPerspectiveTransform) {
  Nan::HandleScope scope;

  // extract quad info
  Local<Object> srcArray = info[0]->ToObject();
  Local<Object> tgtArray = info[1]->ToObject();

  std::vector<cv::Point2f> src_corners(4);
  std::vector<cv::Point2f> tgt_corners(4);
  for (unsigned int i = 0; i < 4; i++) {
    src_corners[i] = cvPoint(srcArray->Get(i*2)->IntegerValue(),srcArray->Get(i*2+1)->IntegerValue());
    tgt_corners[i] = cvPoint(tgtArray->Get(i*2)->IntegerValue(),tgtArray->Get(i*2+1)->IntegerValue());
  }

  Local<Object> xfrm = Matrix::CreateWrappedFromMat(cv::getPerspectiveTransform(src_corners, tgt_corners));

  info.GetReturnValue().Set(xfrm);
}

NAN_METHOD(Matrix::WarpPerspective) {
  SETUP_FUNCTION(Matrix)

  Matrix *xfrm = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  int width = info[1]->IntegerValue();
  int height = info[2]->IntegerValue();

  int flags = cv::INTER_LINEAR;
  int borderMode = cv::BORDER_REPLICATE;

  cv::Scalar borderColor(0, 0, 255);

  if (info[3]->IsArray()) {
    Local < Object > objColor = info[3]->ToObject();
    borderColor = setColor(objColor);
  }

  cv::Mat res = cv::Mat(width, height, CV_32FC3);

  cv::warpPerspective(self->mat, res, xfrm->mat, cv::Size(width, height), flags,
      borderMode, borderColor);

  self->setMat(res);

  info.GetReturnValue().Set(Nan::Null());
}

NAN_METHOD(Matrix::CopyWithMask) {
  SETUP_FUNCTION(Matrix)

  // param 0 - destination image:
  Matrix *dest = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());
  // param 1 - mask. same size as src and dest
  Matrix *mask = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());

  self->mat.copyTo(dest->mat, mask->mat);

  return;
}

NAN_METHOD(Matrix::SetWithMask) {
  SETUP_FUNCTION(Matrix)

  // param 0 - target value:
  Local < Object > valArray = info[0]->ToObject();
  cv::Scalar newvals;
  newvals.val[0] = valArray->Get(0)->NumberValue();
  newvals.val[1] = valArray->Get(1)->NumberValue();
  newvals.val[2] = valArray->Get(2)->NumberValue();

  // param 1 - mask. same size as src and dest
  Matrix *mask = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject());

  self->mat.setTo(newvals, mask->mat);

  return;
}

NAN_METHOD(Matrix::MeanWithMask) {
  SETUP_FUNCTION(Matrix)

  // param 0 - mask. same size as src and dest
  Matrix *mask = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  cv::Scalar means = cv::mean(self->mat, mask->mat);
  v8::Local < v8::Array > arr = Nan::New<Array>(4);
  arr->Set(0, Nan::New<Number>(means[0]));
  arr->Set(1, Nan::New<Number>(means[1]));
  arr->Set(2, Nan::New<Number>(means[2]));
  arr->Set(3, Nan::New<Number>(means[3]));

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::Mean) {
  SETUP_FUNCTION(Matrix)

  cv::Scalar means = cv::mean(self->mat);
  v8::Local<v8::Array> arr = Nan::New<Array>(4);
  arr->Set(0, Nan::New<Number>(means[0]));
  arr->Set(1, Nan::New<Number>(means[1]));
  arr->Set(2, Nan::New<Number>(means[2]));
  arr->Set(3, Nan::New<Number>(means[3]));

  info.GetReturnValue().Set(arr);
}

NAN_METHOD(Matrix::Shift) {
  SETUP_FUNCTION(Matrix)

  cv::Mat res;

  double tx = info[0]->NumberValue();
  double ty = info[1]->NumberValue();

  // get the integer values of info
  cv::Point2i deltai(ceil(tx), ceil(ty));

  int fill = cv::BORDER_REPLICATE;
  cv::Scalar value = cv::Scalar(0, 0, 0, 0);

  // INTEGER SHIFT
  // first create a border around the parts of the Mat that will be exposed
  int t = 0, b = 0, l = 0, r = 0;
  if (deltai.x > 0) {
    l = deltai.x;
  }
  if (deltai.x < 0) {
    r = -deltai.x;
  }
  if (deltai.y > 0) {
    t = deltai.y;
  }
  if (deltai.y < 0) {
    b = -deltai.y;
  }
  cv::Mat padded;
  cv::copyMakeBorder(self->mat, padded, t, b, l, r, fill, value);

  // construct the region of interest around the new matrix
  cv::Rect roi = cv::Rect(std::max(-deltai.x, 0), std::max(-deltai.y, 0), 0, 0)
      + self->mat.size();
  res = padded(roi);

  self->setMat(res);

  return;
}

/**
 * Changes the shape and/or the number of channels of a 2D matrix without
 * copying the data.
 * Reference:http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-reshape
 */
NAN_METHOD(Matrix::Reshape) {
  SETUP_FUNCTION(Matrix)

  int cn = 0;
  int rows = 0;
  if (info.Length() == 2) {
    INT_FROM_ARGS(cn, 0);
    INT_FROM_ARGS(rows, 1);
  } else if (info.Length() == 1) {
    INT_FROM_ARGS(cn, 0);
  } else {
    JSTHROW("Invalid number of arguments");
  }

  Local<Object> img_to_return = Matrix::CreateWrappedFromMatIfNotReferenced(self->mat.reshape(cn, rows),0);

  info.GetReturnValue().Set(img_to_return);
}

NAN_METHOD(Matrix::Release) {
  Nan::HandleScope scope;

  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());

  if(self->getWrappedRefCount() == 1){
    int size = self->mat.dataend - self->mat.datastart;
    Nan::AdjustExternalMemory(-1 * size);
  }

  self->mat.release();

  return;
}

// leave this out - can't see a way it could be useful to us, as release() always completely forgets the data
//NAN_METHOD(Matrix::Addref) {
//  Nan::HandleScope scope;
//
//  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
//  self->mat.addref();
//
//  return;
//}


int Matrix::getWrappedRefCount(){
    int refcount = -1;
#if CV_MAJOR_VERSION >= 3
    if (mat.u){
        refcount = mat.u->refcount;
    } else {
        refcount = -1; // indicates no reference ptr
    }
#else
    if (mat.refcount){
        refcount = *(mat.refcount);
    } else {
        refcount = -1; // indicates no reference ptr
    }
#endif 
    return refcount;
}

NAN_METHOD(Matrix::GetrefCount) {
  Nan::HandleScope scope;
  Matrix *self = Nan::ObjectWrap::Unwrap<Matrix>(info.This());
  
  int refcount = self->getWrappedRefCount();

  info.GetReturnValue().Set(Nan::New<Number>(refcount));
  return;
}


NAN_METHOD(Matrix::Subtract) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 1) {
    Nan::ThrowTypeError("Invalid number of arguments");
  }

  Matrix *other = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  self->mat -= other->mat;

  return;
}

NAN_METHOD(Matrix::Compare) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 2) {
    Nan::ThrowTypeError("Invalid number of arguments");
  }
  Matrix *other = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  int cmpop = info[1]->IntegerValue();

  int width = self->mat.size().width;
  int height = self->mat.size().height;

  cv::Mat res = cv::Mat(width, height, CV_8UC1);

  cv::compare(self->mat, other->mat, res, cmpop);
  Local<Object> out = Matrix::CreateWrappedFromMat(res);

  info.GetReturnValue().Set(out);
  return;
}
NAN_METHOD(Matrix::Mul) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 1) {
    Nan::ThrowTypeError("Invalid number of arguments");
  }

  Matrix *other = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  double scale = 1;
  if (info.Length() > 1) scale = info[1]->NumberValue();

  cv::Mat res = self->mat.mul(other->mat, scale);

  Local<Object> out = Matrix::CreateWrappedFromMat(res);

  info.GetReturnValue().Set(out);
  return;
}

NAN_METHOD(Matrix::Div) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 1) {
    Nan::ThrowTypeError("Invalid number of arguments");
  }

  Matrix *other = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject());

  cv::divide(self->mat, other->mat, self->mat);

  return;
}

NAN_METHOD(Matrix::Pow) {
  SETUP_FUNCTION(Matrix)

  if (info.Length() < 1) {
    Nan::ThrowTypeError("Invalid number of arguments");
  }

  double power = info[0]->NumberValue();

  cv::pow(self->mat, power, self->mat);

  return;
}