ts_func.cpp 95.8 KB
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 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
#include "precomp.hpp"
#include <float.h>
#include <limits.h>
#include "opencv2/imgproc/types_c.h"

using namespace cv;

namespace cvtest
{

const char* getTypeName( int type )
{
    static const char* type_names[] = { "8u", "8s", "16u", "16s", "32s", "32f", "64f", "ptr" };
    return type_names[CV_MAT_DEPTH(type)];
}

int typeByName( const char* name )
{
    int i;
    for( i = 0; i < CV_DEPTH_MAX; i++ )
        if( strcmp(name, getTypeName(i)) == 0 )
            return i;
    return -1;
}

string vec2str( const string& sep, const int* v, size_t nelems )
{
    char buf[32];
    string result = "";
    for( size_t i = 0; i < nelems; i++ )
    {
        sprintf(buf, "%d", v[i]);
        result += string(buf);
        if( i < nelems - 1 )
            result += sep;
    }
    return result;
}


Size randomSize(RNG& rng, double maxSizeLog)
{
    double width_log = rng.uniform(0., maxSizeLog);
    double height_log = rng.uniform(0., maxSizeLog - width_log);
    if( (unsigned)rng % 2 != 0 )
        std::swap(width_log, height_log);
    Size sz;
    sz.width = cvRound(exp(width_log));
    sz.height = cvRound(exp(height_log));
    return sz;
}

void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz)
{
    int i, dims = rng.uniform(minDims, maxDims+1);
    sz.resize(dims);
    for( i = 0; i < dims; i++ )
    {
        double v = rng.uniform(0., maxSizeLog);
        maxSizeLog -= v;
        sz[i] = cvRound(exp(v));
    }
    for( i = 0; i < dims; i++ )
    {
        int j = rng.uniform(0, dims);
        int k = rng.uniform(0, dims);
        std::swap(sz[j], sz[k]);
    }
}

int randomType(RNG& rng, _OutputArray::DepthMask typeMask, int minChannels, int maxChannels)
{
    int channels = rng.uniform(minChannels, maxChannels+1);
    int depth = 0;
    CV_Assert((typeMask & _OutputArray::DEPTH_MASK_ALL_16F) != 0);
    for(;;)
    {
        depth = rng.uniform(CV_8U, CV_16F+1);
        if( ((1 << depth) & typeMask) != 0 )
            break;
    }
    return CV_MAKETYPE(depth, channels);
}

double getMinVal(int depth)
{
    depth = CV_MAT_DEPTH(depth);
    double val = depth == CV_8U ? 0 : depth == CV_8S ? SCHAR_MIN : depth == CV_16U ? 0 :
    depth == CV_16S ? SHRT_MIN : depth == CV_32S ? INT_MIN :
    depth == CV_32F ? -FLT_MAX : depth == CV_64F ? -DBL_MAX :
            depth == CV_16F ? -65504
            : -1;
    CV_Assert(val != -1);
    return val;
}

double getMaxVal(int depth)
{
    depth = CV_MAT_DEPTH(depth);
    double val = depth == CV_8U ? UCHAR_MAX : depth == CV_8S ? SCHAR_MAX : depth == CV_16U ? USHRT_MAX :
    depth == CV_16S ? SHRT_MAX : depth == CV_32S ? INT_MAX :
    depth == CV_32F ? FLT_MAX : depth == CV_64F ? DBL_MAX :
            depth == CV_16F ? 65504
            : -1;
    CV_Assert(val != -1);
    return val;
}

Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi)
{
    Size size0 = size;
    if( useRoi )
    {
        size0.width += std::max(rng.uniform(0, 10) - 5, 0);
        size0.height += std::max(rng.uniform(0, 10) - 5, 0);
    }

    Mat m(size0, type);

    rng.fill(m, RNG::UNIFORM, minVal, maxVal);
    if( size0 == size )
        return m;
    return m(Rect((size0.width-size.width)/2, (size0.height-size.height)/2, size.width, size.height));
}

Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi)
{
    int i, dims = (int)size.size();
    vector<int> size0(dims);
    vector<Range> r(dims);
    bool eqsize = true;
    for( i = 0; i < dims; i++ )
    {
        size0[i] = size[i];
        r[i] = Range::all();
        if( useRoi )
        {
            size0[i] += std::max(rng.uniform(0, 5) - 2, 0);
            r[i] = Range((size0[i] - size[i])/2, (size0[i] - size[i])/2 + size[i]);
        }
        eqsize = eqsize && size[i] == size0[i];
    }

    Mat m(dims, &size0[0], type);

    rng.fill(m, RNG::UNIFORM, minVal, maxVal);
    if( eqsize )
        return m;
    return m(&r[0]);
}

void add(const Mat& _a, double alpha, const Mat& _b, double beta,
        Scalar gamma, Mat& c, int ctype, bool calcAbs)
{
    Mat a = _a, b = _b;
    if( a.empty() || alpha == 0 )
    {
        // both alpha and beta can be 0, but at least one of a and b must be non-empty array,
        // otherwise we do not know the size of the output (and may be type of the output, when ctype<0)
        CV_Assert( !a.empty() || !b.empty() );
        if( !b.empty() )
        {
            a = b;
            alpha = beta;
            b = Mat();
            beta = 0;
        }
    }
    if( b.empty() || beta == 0 )
    {
        b = Mat();
        beta = 0;
    }
    else
        CV_Assert(a.size == b.size);

    if( ctype < 0 )
        ctype = a.depth();
    ctype = CV_MAKETYPE(CV_MAT_DEPTH(ctype), a.channels());
    c.create(a.dims, &a.size[0], ctype);
    const Mat *arrays[] = {&a, &b, &c, 0};
    Mat planes[3], buf[3];

    NAryMatIterator it(arrays, planes);
    size_t i, nplanes = it.nplanes;
    int cn=a.channels();
    int total = (int)planes[0].total(), maxsize = std::min(12*12*std::max(12/cn, 1), total);

    CV_Assert(planes[0].rows == 1);
    buf[0].create(1, maxsize, CV_64FC(cn));
    if(!b.empty())
        buf[1].create(1, maxsize, CV_64FC(cn));
    buf[2].create(1, maxsize, CV_64FC(cn));
    scalarToRawData(gamma, buf[2].ptr(), CV_64FC(cn), (int)(maxsize*cn));

    for( i = 0; i < nplanes; i++, ++it)
    {
        for( int j = 0; j < total; j += maxsize )
        {
            int j2 = std::min(j + maxsize, total);
            Mat apart0 = planes[0].colRange(j, j2);
            Mat cpart0 = planes[2].colRange(j, j2);
            Mat apart = buf[0].colRange(0, j2 - j);

            apart0.convertTo(apart, apart.type(), alpha);
            size_t k, n = (j2 - j)*cn;
            double* aptr = apart.ptr<double>();
            const double* gptr = buf[2].ptr<double>();

            if( b.empty() )
            {
                for( k = 0; k < n; k++ )
                    aptr[k] += gptr[k];
            }
            else
            {
                Mat bpart0 = planes[1].colRange((int)j, (int)j2);
                Mat bpart = buf[1].colRange(0, (int)(j2 - j));
                bpart0.convertTo(bpart, bpart.type(), beta);
                const double* bptr = bpart.ptr<double>();

                for( k = 0; k < n; k++ )
                    aptr[k] += bptr[k] + gptr[k];
            }
            if( calcAbs )
                for( k = 0; k < n; k++ )
                    aptr[k] = fabs(aptr[k]);
            apart.convertTo(cpart0, cpart0.type(), 1, 0);
        }
    }
}


template<typename _Tp1, typename _Tp2> inline void
convert_(const _Tp1* src, _Tp2* dst, size_t total, double alpha, double beta)
{
    size_t i;
    if( alpha == 1 && beta == 0 )
        for( i = 0; i < total; i++ )
            dst[i] = saturate_cast<_Tp2>(src[i]);
    else if( beta == 0 )
        for( i = 0; i < total; i++ )
            dst[i] = saturate_cast<_Tp2>(src[i]*alpha);
    else
        for( i = 0; i < total; i++ )
            dst[i] = saturate_cast<_Tp2>(src[i]*alpha + beta);
}

template<typename _Tp> inline void
convertTo(const _Tp* src, void* dst, int dtype, size_t total, double alpha, double beta)
{
    switch( CV_MAT_DEPTH(dtype) )
    {
    case CV_8U:
        convert_(src, (uchar*)dst, total, alpha, beta);
        break;
    case CV_8S:
        convert_(src, (schar*)dst, total, alpha, beta);
        break;
    case CV_16U:
        convert_(src, (ushort*)dst, total, alpha, beta);
        break;
    case CV_16S:
        convert_(src, (short*)dst, total, alpha, beta);
        break;
    case CV_32S:
        convert_(src, (int*)dst, total, alpha, beta);
        break;
    case CV_32F:
        convert_(src, (float*)dst, total, alpha, beta);
        break;
    case CV_64F:
        convert_(src, (double*)dst, total, alpha, beta);
        break;
    default:
        CV_Assert(0);
    }
}

void convert(const Mat& src, cv::OutputArray _dst, int dtype, double alpha, double beta)
{
    if (dtype < 0) dtype = _dst.depth();

    dtype = CV_MAKETYPE(CV_MAT_DEPTH(dtype), src.channels());
    _dst.create(src.dims, &src.size[0], dtype);
    Mat dst = _dst.getMat();
    if( alpha == 0 )
    {
        set( dst, Scalar::all(beta) );
        return;
    }
    if( dtype == src.type() && alpha == 1 && beta == 0 )
    {
        copy( src, dst );
        return;
    }

    const Mat *arrays[]={&src, &dst, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].channels();
    size_t i, nplanes = it.nplanes;

    for( i = 0; i < nplanes; i++, ++it)
    {
        const uchar* sptr = planes[0].ptr();
        uchar* dptr = planes[1].ptr();

        switch( src.depth() )
        {
        case CV_8U:
            convertTo((const uchar*)sptr, dptr, dtype, total, alpha, beta);
            break;
        case CV_8S:
            convertTo((const schar*)sptr, dptr, dtype, total, alpha, beta);
            break;
        case CV_16U:
            convertTo((const ushort*)sptr, dptr, dtype, total, alpha, beta);
            break;
        case CV_16S:
            convertTo((const short*)sptr, dptr, dtype, total, alpha, beta);
            break;
        case CV_32S:
            convertTo((const int*)sptr, dptr, dtype, total, alpha, beta);
            break;
        case CV_32F:
            convertTo((const float*)sptr, dptr, dtype, total, alpha, beta);
            break;
        case CV_64F:
            convertTo((const double*)sptr, dptr, dtype, total, alpha, beta);
            break;
        }
    }
}


void copy(const Mat& src, Mat& dst, const Mat& mask, bool invertMask)
{
    dst.create(src.dims, &src.size[0], src.type());

    if(mask.empty())
    {
        const Mat* arrays[] = {&src, &dst, 0};
        Mat planes[2];
        NAryMatIterator it(arrays, planes);
        size_t i, nplanes = it.nplanes;
        size_t planeSize = planes[0].total()*src.elemSize();

        for( i = 0; i < nplanes; i++, ++it )
            memcpy(planes[1].ptr(), planes[0].ptr(), planeSize);

        return;
    }

    int mcn = mask.channels();
    CV_Assert( src.size == mask.size && mask.depth() == CV_8U
               && (mcn == 1 || mcn == src.channels()) );

    const Mat *arrays[]={&src, &dst, &mask, 0};
    Mat planes[3];

    NAryMatIterator it(arrays, planes);
    size_t j, k, elemSize = src.elemSize(), maskElemSize = mask.elemSize(), total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    size_t elemSize1 = src.elemSize1();

    for( i = 0; i < nplanes; i++, ++it)
    {
        const uchar* sptr = planes[0].ptr();
        uchar* dptr = planes[1].ptr();
        const uchar* mptr = planes[2].ptr();
        for( j = 0; j < total; j++, sptr += elemSize, dptr += elemSize, mptr += maskElemSize )
        {
            if( mcn == 1)
            {
                if( (mptr[0] != 0) ^ invertMask )
                    for( k = 0; k < elemSize; k++ )
                        dptr[k] = sptr[k];
            }
            else
            {
                for( int c = 0; c < mcn; c++ )
                    if( (mptr[c] != 0) ^ invertMask )
                        for( k = 0; k < elemSize1; k++ )
                            dptr[k + c * elemSize1] = sptr[k + c * elemSize1];
            }
        }
    }
}


void set(Mat& dst, const Scalar& gamma, const Mat& mask)
{
    double buf[12];
    scalarToRawData(gamma, &buf, dst.type(), dst.channels());
    const uchar* gptr = (const uchar*)&buf[0];

    if(mask.empty())
    {
        const Mat* arrays[] = {&dst, 0};
        Mat plane;
        NAryMatIterator it(arrays, &plane);
        size_t i, nplanes = it.nplanes;
        size_t j, k, elemSize = dst.elemSize(), planeSize = plane.total()*elemSize;

        for( k = 1; k < elemSize; k++ )
            if( gptr[k] != gptr[0] )
                break;
        bool uniform = k >= elemSize;

        for( i = 0; i < nplanes; i++, ++it )
        {
            uchar* dptr = plane.ptr();
            if( uniform )
                memset( dptr, gptr[0], planeSize );
            else if( i == 0 )
            {
                for( j = 0; j < planeSize; j += elemSize, dptr += elemSize )
                    for( k = 0; k < elemSize; k++ )
                        dptr[k] = gptr[k];
            }
            else
                memcpy(dptr, dst.ptr(), planeSize);
        }
        return;
    }

    int cn = dst.channels(), mcn = mask.channels();
    CV_Assert( dst.size == mask.size && (mcn == 1 || mcn == cn) );

    const Mat *arrays[]={&dst, &mask, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t j, k, elemSize = dst.elemSize(), maskElemSize = mask.elemSize(), total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    size_t elemSize1 = dst.elemSize1();

    for( i = 0; i < nplanes; i++, ++it)
    {
        uchar* dptr = planes[0].ptr();
        const uchar* mptr = planes[1].ptr();

        for( j = 0; j < total; j++, dptr += elemSize, mptr += maskElemSize )
        {
            if( mcn == 1)
            {
                if( mptr[0] )
                    for( k = 0; k < elemSize; k++ )
                        dptr[k] = gptr[k];
            }
            else
            {
                for( int c = 0; c < mcn; c++ )
                    if( mptr[c] )
                        for( k = 0; k < elemSize1; k++ )
                            dptr[k + c * elemSize1] = gptr[k + c * elemSize1];
            }
        }
    }
}


void insert(const Mat& src, Mat& dst, int coi)
{
    CV_Assert( dst.size == src.size && src.depth() == dst.depth() &&
              0 <= coi && coi < dst.channels() );

    const Mat* arrays[] = {&src, &dst, 0};
    Mat planes[2];
    NAryMatIterator it(arrays, planes);
    size_t i, nplanes = it.nplanes;
    size_t j, k, size0 = src.elemSize(), size1 = dst.elemSize(), total = planes[0].total();

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr();
        uchar* dptr = planes[1].ptr() + coi*size0;

        for( j = 0; j < total; j++, sptr += size0, dptr += size1 )
        {
            for( k = 0; k < size0; k++ )
                dptr[k] = sptr[k];
        }
    }
}


void extract(const Mat& src, Mat& dst, int coi)
{
    dst.create( src.dims, &src.size[0], src.depth() );
    CV_Assert( 0 <= coi && coi < src.channels() );

    const Mat* arrays[] = {&src, &dst, 0};
    Mat planes[2];
    NAryMatIterator it(arrays, planes);
    size_t i, nplanes = it.nplanes;
    size_t j, k, size0 = src.elemSize(), size1 = dst.elemSize(), total = planes[0].total();

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr() + coi*size1;
        uchar* dptr = planes[1].ptr();

        for( j = 0; j < total; j++, sptr += size0, dptr += size1 )
        {
            for( k = 0; k < size1; k++ )
                dptr[k] = sptr[k];
        }
    }
}


void transpose(const Mat& src, Mat& dst)
{
    CV_Assert(src.data != dst.data && "Inplace is not support in cvtest::transpose");
    CV_Assert(src.dims == 2);
    dst.create(src.cols, src.rows, src.type());
    int i, j, k, esz = (int)src.elemSize();

    for( i = 0; i < dst.rows; i++ )
    {
        const uchar* sptr = src.ptr(0) + i*esz;
        uchar* dptr = dst.ptr(i);

        for( j = 0; j < dst.cols; j++, sptr += src.step[0], dptr += esz )
        {
            for( k = 0; k < esz; k++ )
                dptr[k] = sptr[k];
        }
    }
}


template<typename _Tp> static void
randUniInt_(RNG& rng, _Tp* data, size_t total, int cn, const Scalar& scale, const Scalar& delta)
{
    for( size_t i = 0; i < total; i += cn )
        for( int k = 0; k < cn; k++ )
        {
            int val = cvFloor( randInt(rng)*scale[k] + delta[k] );
            data[i + k] = saturate_cast<_Tp>(val);
        }
}


template<typename _Tp> static void
randUniFlt_(RNG& rng, _Tp* data, size_t total, int cn, const Scalar& scale, const Scalar& delta)
{
    for( size_t i = 0; i < total; i += cn )
        for( int k = 0; k < cn; k++ )
        {
            double val = randReal(rng)*scale[k] + delta[k];
            data[i + k] = saturate_cast<_Tp>(val);
        }
}


void randUni( RNG& rng, Mat& a, const Scalar& param0, const Scalar& param1 )
{
    Scalar scale = param0;
    Scalar delta = param1;
    double C = a.depth() < CV_32F ? 1./(65536.*65536.) : 1.;

    for( int k = 0; k < 4; k++ )
    {
        double s = scale.val[k] - delta.val[k];
        if( s >= 0 )
            scale.val[k] = s;
        else
        {
            delta.val[k] = scale.val[k];
            scale.val[k] = -s;
        }
        scale.val[k] *= C;
    }

    const Mat *arrays[]={&a, 0};
    Mat plane;

    NAryMatIterator it(arrays, &plane);
    size_t i, nplanes = it.nplanes;
    int depth = a.depth(), cn = a.channels();
    size_t total = plane.total()*cn;

    for( i = 0; i < nplanes; i++, ++it )
    {
        switch( depth )
        {
        case CV_8U:
            randUniInt_(rng, plane.ptr<uchar>(), total, cn, scale, delta);
            break;
        case CV_8S:
            randUniInt_(rng, plane.ptr<schar>(), total, cn, scale, delta);
            break;
        case CV_16U:
            randUniInt_(rng, plane.ptr<ushort>(), total, cn, scale, delta);
            break;
        case CV_16S:
            randUniInt_(rng, plane.ptr<short>(), total, cn, scale, delta);
            break;
        case CV_32S:
            randUniInt_(rng, plane.ptr<int>(), total, cn, scale, delta);
            break;
        case CV_32F:
            randUniFlt_(rng, plane.ptr<float>(), total, cn, scale, delta);
            break;
        case CV_64F:
            randUniFlt_(rng, plane.ptr<double>(), total, cn, scale, delta);
            break;
        default:
            CV_Assert(0);
        }
    }
}


template<typename _Tp> static void
erode_(const Mat& src, Mat& dst, const vector<int>& ofsvec)
{
    int width = dst.cols*src.channels(), n = (int)ofsvec.size();
    const int* ofs = &ofsvec[0];

    for( int y = 0; y < dst.rows; y++ )
    {
        const _Tp* sptr = src.ptr<_Tp>(y);
        _Tp* dptr = dst.ptr<_Tp>(y);

        for( int x = 0; x < width; x++ )
        {
            _Tp result = sptr[x + ofs[0]];
            for( int i = 1; i < n; i++ )
                result = std::min(result, sptr[x + ofs[i]]);
            dptr[x] = result;
        }
    }
}


template<typename _Tp> static void
dilate_(const Mat& src, Mat& dst, const vector<int>& ofsvec)
{
    int width = dst.cols*src.channels(), n = (int)ofsvec.size();
    const int* ofs = &ofsvec[0];

    for( int y = 0; y < dst.rows; y++ )
    {
        const _Tp* sptr = src.ptr<_Tp>(y);
        _Tp* dptr = dst.ptr<_Tp>(y);

        for( int x = 0; x < width; x++ )
        {
            _Tp result = sptr[x + ofs[0]];
            for( int i = 1; i < n; i++ )
                result = std::max(result, sptr[x + ofs[i]]);
            dptr[x] = result;
        }
    }
}


void erode(const Mat& _src, Mat& dst, const Mat& _kernel, Point anchor,
           int borderType, const Scalar& _borderValue)
{
    //if( _src.type() == CV_16UC3 && _src.size() == Size(1, 2) )
    //    putchar('*');
    Mat kernel = _kernel, src;
    Scalar borderValue = _borderValue;
    if( kernel.empty() )
        kernel = Mat::ones(3, 3, CV_8U);
    else
    {
        CV_Assert( kernel.type() == CV_8U );
    }
    if( anchor == Point(-1,-1) )
        anchor = Point(kernel.cols/2, kernel.rows/2);
    if( borderType == BORDER_CONSTANT )
        borderValue = getMaxVal(src.depth());
    copyMakeBorder(_src, src, anchor.y, kernel.rows - anchor.y - 1,
                   anchor.x, kernel.cols - anchor.x - 1,
                   borderType, borderValue);
    dst.create( _src.size(), src.type() );

    vector<int> ofs;
    int step = (int)(src.step/src.elemSize1()), cn = src.channels();
    for( int i = 0; i < kernel.rows; i++ )
        for( int j = 0; j < kernel.cols; j++ )
            if( kernel.at<uchar>(i, j) != 0 )
                ofs.push_back(i*step + j*cn);
    if( ofs.empty() )
        ofs.push_back(anchor.y*step + anchor.x*cn);

    switch( src.depth() )
    {
    case CV_8U:
        erode_<uchar>(src, dst, ofs);
        break;
    case CV_8S:
        erode_<schar>(src, dst, ofs);
        break;
    case CV_16U:
        erode_<ushort>(src, dst, ofs);
        break;
    case CV_16S:
        erode_<short>(src, dst, ofs);
        break;
    case CV_32S:
        erode_<int>(src, dst, ofs);
        break;
    case CV_32F:
        erode_<float>(src, dst, ofs);
        break;
    case CV_64F:
        erode_<double>(src, dst, ofs);
        break;
    default:
        CV_Assert(0);
    }
}

void dilate(const Mat& _src, Mat& dst, const Mat& _kernel, Point anchor,
            int borderType, const Scalar& _borderValue)
{
    Mat kernel = _kernel, src;
    Scalar borderValue = _borderValue;
    if( kernel.empty() )
        kernel = Mat::ones(3, 3, CV_8U);
    else
    {
        CV_Assert( kernel.type() == CV_8U );
    }
    if( anchor == Point(-1,-1) )
        anchor = Point(kernel.cols/2, kernel.rows/2);
    if( borderType == BORDER_CONSTANT )
        borderValue = getMinVal(src.depth());
    copyMakeBorder(_src, src, anchor.y, kernel.rows - anchor.y - 1,
                   anchor.x, kernel.cols - anchor.x - 1,
                   borderType, borderValue);
    dst.create( _src.size(), src.type() );

    vector<int> ofs;
    int step = (int)(src.step/src.elemSize1()), cn = src.channels();
    for( int i = 0; i < kernel.rows; i++ )
        for( int j = 0; j < kernel.cols; j++ )
            if( kernel.at<uchar>(i, j) != 0 )
                ofs.push_back(i*step + j*cn);
    if( ofs.empty() )
        ofs.push_back(anchor.y*step + anchor.x*cn);

    switch( src.depth() )
    {
    case CV_8U:
        dilate_<uchar>(src, dst, ofs);
        break;
    case CV_8S:
        dilate_<schar>(src, dst, ofs);
        break;
    case CV_16U:
        dilate_<ushort>(src, dst, ofs);
        break;
    case CV_16S:
        dilate_<short>(src, dst, ofs);
        break;
    case CV_32S:
        dilate_<int>(src, dst, ofs);
        break;
    case CV_32F:
        dilate_<float>(src, dst, ofs);
        break;
    case CV_64F:
        dilate_<double>(src, dst, ofs);
        break;
    default:
        CV_Assert(0);
    }
}


template<typename _Tp> static void
filter2D_(const Mat& src, Mat& dst, const vector<int>& ofsvec, const vector<double>& coeffvec)
{
    const int* ofs = &ofsvec[0];
    const double* coeff = &coeffvec[0];
    int width = dst.cols*dst.channels(), ncoeffs = (int)ofsvec.size();

    for( int y = 0; y < dst.rows; y++ )
    {
        const _Tp* sptr = src.ptr<_Tp>(y);
        double* dptr = dst.ptr<double>(y);

        for( int x = 0; x < width; x++ )
        {
            double s = 0;
            for( int i = 0; i < ncoeffs; i++ )
                s += sptr[x + ofs[i]]*coeff[i];
            dptr[x] = s;
        }
    }
}


void filter2D(const Mat& _src, Mat& dst, int ddepth, const Mat& kernel,
              Point anchor, double delta, int borderType, const Scalar& _borderValue)
{
    Mat src, _dst;
    Scalar borderValue = _borderValue;
    CV_Assert( kernel.type() == CV_32F || kernel.type() == CV_64F );
    if( anchor == Point(-1,-1) )
        anchor = Point(kernel.cols/2, kernel.rows/2);
    if( borderType == BORDER_CONSTANT )
        borderValue = getMinVal(src.depth());
    copyMakeBorder(_src, src, anchor.y, kernel.rows - anchor.y - 1,
                   anchor.x, kernel.cols - anchor.x - 1,
                   borderType, borderValue);
    _dst.create( _src.size(), CV_MAKETYPE(CV_64F, src.channels()) );

    vector<int> ofs;
    vector<double> coeff(kernel.rows*kernel.cols);
    Mat cmat(kernel.rows, kernel.cols, CV_64F, &coeff[0]);
    convert(kernel, cmat, cmat.type());

    int step = (int)(src.step/src.elemSize1()), cn = src.channels();
    for( int i = 0; i < kernel.rows; i++ )
        for( int j = 0; j < kernel.cols; j++ )
                ofs.push_back(i*step + j*cn);

    switch( src.depth() )
    {
    case CV_8U:
        filter2D_<uchar>(src, _dst, ofs, coeff);
        break;
    case CV_8S:
        filter2D_<schar>(src, _dst, ofs, coeff);
        break;
    case CV_16U:
        filter2D_<ushort>(src, _dst, ofs, coeff);
        break;
    case CV_16S:
        filter2D_<short>(src, _dst, ofs, coeff);
        break;
    case CV_32S:
        filter2D_<int>(src, _dst, ofs, coeff);
        break;
    case CV_32F:
        filter2D_<float>(src, _dst, ofs, coeff);
        break;
    case CV_64F:
        filter2D_<double>(src, _dst, ofs, coeff);
        break;
    default:
        CV_Assert(0);
    }

    convert(_dst, dst, ddepth, 1, delta);
}


static int borderInterpolate( int p, int len, int borderType )
{
    if( (unsigned)p < (unsigned)len )
        ;
    else if( borderType == BORDER_REPLICATE )
        p = p < 0 ? 0 : len - 1;
    else if( borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101 )
    {
        int delta = borderType == BORDER_REFLECT_101;
        if( len == 1 )
            return 0;
        do
        {
            if( p < 0 )
                p = -p - 1 + delta;
            else
                p = len - 1 - (p - len) - delta;
        }
        while( (unsigned)p >= (unsigned)len );
    }
    else if( borderType == BORDER_WRAP )
    {
        if( p < 0 )
            p -= ((p-len+1)/len)*len;
        if( p >= len )
            p %= len;
    }
    else if( borderType == BORDER_CONSTANT )
        p = -1;
    else
        CV_Error( Error::StsBadArg, "Unknown/unsupported border type" );
    return p;
}


void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
                    int borderType, const Scalar& borderValue)
{
    dst.create(src.rows + top + bottom, src.cols + left + right, src.type());
    int i, j, k, esz = (int)src.elemSize();
    int width = src.cols*esz, width1 = dst.cols*esz;

    if( borderType == BORDER_CONSTANT )
    {
        vector<uchar> valvec((src.cols + left + right)*esz);
        uchar* val = &valvec[0];
        scalarToRawData(borderValue, val, src.type(), (src.cols + left + right)*src.channels());

        left *= esz;
        right *= esz;
        for( i = 0; i < src.rows; i++ )
        {
            const uchar* sptr = src.ptr(i);
            uchar* dptr = dst.ptr(i + top) + left;
            for( j = 0; j < left; j++ )
                dptr[j - left] = val[j];
            if( dptr != sptr )
                for( j = 0; j < width; j++ )
                    dptr[j] = sptr[j];
            for( j = 0; j < right; j++ )
                dptr[j + width] = val[j];
        }

        for( i = 0; i < top; i++ )
        {
            uchar* dptr = dst.ptr(i);
            for( j = 0; j < width1; j++ )
                dptr[j] = val[j];
        }

        for( i = 0; i < bottom; i++ )
        {
            uchar* dptr = dst.ptr(i + top + src.rows);
            for( j = 0; j < width1; j++ )
                dptr[j] = val[j];
        }
    }
    else
    {
        vector<int> tabvec((left + right)*esz + 1);
        int* ltab = &tabvec[0];
        int* rtab = &tabvec[left*esz];
        for( i = 0; i < left; i++ )
        {
            j = borderInterpolate(i - left, src.cols, borderType)*esz;
            for( k = 0; k < esz; k++ )
                ltab[i*esz + k] = j + k;
        }
        for( i = 0; i < right; i++ )
        {
            j = borderInterpolate(src.cols + i, src.cols, borderType)*esz;
            for( k = 0; k < esz; k++ )
                rtab[i*esz + k] = j + k;
        }

        left *= esz;
        right *= esz;
        for( i = 0; i < src.rows; i++ )
        {
            const uchar* sptr = src.ptr(i);
            uchar* dptr = dst.ptr(i + top);

            for( j = 0; j < left; j++ )
                dptr[j] = sptr[ltab[j]];
            if( dptr + left != sptr )
            {
                for( j = 0; j < width; j++ )
                    dptr[j + left] = sptr[j];
            }
            for( j = 0; j < right; j++ )
                dptr[j + left + width] = sptr[rtab[j]];
        }

        for( i = 0; i < top; i++ )
        {
            j = borderInterpolate(i - top, src.rows, borderType);
            const uchar* sptr = dst.ptr(j + top);
            uchar* dptr = dst.ptr(i);

            for( k = 0; k < width1; k++ )
                dptr[k] = sptr[k];
        }

        for( i = 0; i < bottom; i++ )
        {
            j = borderInterpolate(i + src.rows, src.rows, borderType);
            const uchar* sptr = dst.ptr(j + top);
            uchar* dptr = dst.ptr(i + top + src.rows);

            for( k = 0; k < width1; k++ )
                dptr[k] = sptr[k];
        }
    }
}


template<typename _Tp> static void
minMaxLoc_(const _Tp* src, size_t total, size_t startidx,
           double* _minval, double* _maxval,
           size_t* _minpos, size_t* _maxpos,
           const uchar* mask)
{
    _Tp maxval = saturate_cast<_Tp>(*_maxval), minval = saturate_cast<_Tp>(*_minval);
    size_t minpos = *_minpos, maxpos = *_maxpos;

    if( !mask )
    {
        for( size_t i = 0; i < total; i++ )
        {
            _Tp val = src[i];
            if( minval > val || !minpos )
            {
                minval = val;
                minpos = startidx + i;
            }
            if( maxval < val || !maxpos )
            {
                maxval = val;
                maxpos = startidx + i;
            }
        }
    }
    else
    {
        for( size_t i = 0; i < total; i++ )
        {
            _Tp val = src[i];
            if( (minval > val || !minpos) && mask[i] )
            {
                minval = val;
                minpos = startidx + i;
            }
            if( (maxval < val || !maxpos) && mask[i] )
            {
                maxval = val;
                maxpos = startidx + i;
            }
        }
    }

    *_maxval = maxval;
    *_minval = minval;
    *_maxpos = maxpos;
    *_minpos = minpos;
}


static void setpos( const Mat& mtx, vector<int>& pos, size_t idx )
{
    pos.resize(mtx.dims);
    if( idx > 0 )
    {
        idx--;
        for( int i = mtx.dims-1; i >= 0; i-- )
        {
            int sz = mtx.size[i]*(i == mtx.dims-1 ? mtx.channels() : 1);
            pos[i] = (int)(idx % sz);
            idx /= sz;
        }
    }
    else
    {
        for( int i = mtx.dims-1; i >= 0; i-- )
            pos[i] = -1;
    }
}

void minMaxLoc(const Mat& src, double* _minval, double* _maxval,
               vector<int>* _minloc, vector<int>* _maxloc,
               const Mat& mask)
{
    CV_Assert( src.channels() == 1 );
    const Mat *arrays[]={&src, &mask, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t startidx = 1, total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    int depth = src.depth();
    double minval = 0;
    double maxval = 0;
    size_t maxidx = 0, minidx = 0;

    for( i = 0; i < nplanes; i++, ++it, startidx += total )
    {
        const uchar* sptr = planes[0].ptr();
        const uchar* mptr = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            minMaxLoc_((const uchar*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        case CV_8S:
            minMaxLoc_((const schar*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        case CV_16U:
            minMaxLoc_((const ushort*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        case CV_16S:
            minMaxLoc_((const short*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        case CV_32S:
            minMaxLoc_((const int*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        case CV_32F:
            minMaxLoc_((const float*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        case CV_64F:
            minMaxLoc_((const double*)sptr, total, startidx,
                       &minval, &maxval, &minidx, &maxidx, mptr);
            break;
        default:
            CV_Assert(0);
        }
    }

    if( _maxval )
        *_maxval = maxval;
    if( _minval )
        *_minval = minval;
    if( _maxloc )
        setpos( src, *_maxloc, maxidx );
    if( _minloc )
        setpos( src, *_minloc, minidx );
}


static int
normHamming(const uchar* src, size_t total, int cellSize)
{
    int result = 0;
    int mask = cellSize == 1 ? 1 : cellSize == 2 ? 3 : cellSize == 4 ? 15 : -1;
    CV_Assert( mask >= 0 );

    for( size_t i = 0; i < total; i++ )
    {
        unsigned a = src[i];
        for( ; a != 0; a >>= cellSize )
            result += (a & mask) != 0;
    }
    return result;
}


template<typename _Tp> static double
norm_(const _Tp* src, size_t total, int cn, int normType, double startval, const uchar* mask)
{
    size_t i;
    double result = startval;
    if( !mask )
        total *= cn;

    if( normType == NORM_INF )
    {
        if( !mask )
            for( i = 0; i < total; i++ )
                result = std::max(result, (double)std::abs(0+src[i]));// trick with 0 used to quiet gcc warning
        else
            for( int c = 0; c < cn; c++ )
            {
                for( i = 0; i < total; i++ )
                    if( mask[i] )
                        result = std::max(result, (double)std::abs(0+src[i*cn + c]));
            }
    }
    else if( normType == NORM_L1 )
    {
        if( !mask )
            for( i = 0; i < total; i++ )
                result += std::abs(0+src[i]);
        else
            for( int c = 0; c < cn; c++ )
            {
                for( i = 0; i < total; i++ )
                    if( mask[i] )
                        result += std::abs(0+src[i*cn + c]);
            }
    }
    else
    {
        if( !mask )
            for( i = 0; i < total; i++ )
            {
                double v = src[i];
                result += v*v;
            }
        else
            for( int c = 0; c < cn; c++ )
            {
                for( i = 0; i < total; i++ )
                    if( mask[i] )
                    {
                        double v = src[i*cn + c];
                        result += v*v;
                    }
            }
    }
    return result;
}


template<typename _Tp> static double
norm_(const _Tp* src1, const _Tp* src2, size_t total, int cn, int normType, double startval, const uchar* mask)
{
    size_t i;
    double result = startval;
    if( !mask )
        total *= cn;

    if( normType == NORM_INF )
    {
        if( !mask )
            for( i = 0; i < total; i++ )
                result = std::max(result, (double)std::abs(src1[i] - src2[i]));
        else
            for( int c = 0; c < cn; c++ )
            {
                for( i = 0; i < total; i++ )
                    if( mask[i] )
                        result = std::max(result, (double)std::abs(src1[i*cn + c] - src2[i*cn + c]));
            }
    }
    else if( normType == NORM_L1 )
    {
        if( !mask )
            for( i = 0; i < total; i++ )
                result += std::abs(src1[i] - src2[i]);
        else
            for( int c = 0; c < cn; c++ )
            {
                for( i = 0; i < total; i++ )
                    if( mask[i] )
                        result += std::abs(src1[i*cn + c] - src2[i*cn + c]);
            }
    }
    else
    {
        if( !mask )
            for( i = 0; i < total; i++ )
            {
                double v = src1[i] - src2[i];
                result += v*v;
            }
        else
            for( int c = 0; c < cn; c++ )
            {
                for( i = 0; i < total; i++ )
                    if( mask[i] )
                    {
                        double v = src1[i*cn + c] - src2[i*cn + c];
                        result += v*v;
                    }
            }
    }
    return result;
}


double norm(InputArray _src, int normType, InputArray _mask)
{
    Mat src = _src.getMat(), mask = _mask.getMat();
    if( src.depth() == CV_16F )
    {
        Mat src32f;
        src.convertTo(src32f, CV_32F);
        return cvtest::norm(src32f, normType, _mask);
    }

    if( normType == NORM_HAMMING || normType == NORM_HAMMING2 )
    {
        if( !mask.empty() )
        {
            Mat temp;
            bitwise_and(src, mask, temp);
            return cvtest::norm(temp, normType, Mat());
        }

        CV_Assert( src.depth() == CV_8U );

        const Mat *arrays[]={&src, 0};
        Mat planes[1];

        NAryMatIterator it(arrays, planes);
        size_t total = planes[0].total();
        size_t i, nplanes = it.nplanes;
        double result = 0;
        int cellSize = normType == NORM_HAMMING ? 1 : 2;

        for( i = 0; i < nplanes; i++, ++it )
            result += normHamming(planes[0].ptr(), total, cellSize);
        return result;
    }
    int normType0 = normType;
    normType = normType == NORM_L2SQR ? NORM_L2 : normType;

    CV_Assert( mask.empty() || (src.size == mask.size && mask.type() == CV_8U) );
    CV_Assert( normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2 );

    const Mat *arrays[]={&src, &mask, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    int depth = src.depth(), cn = planes[0].channels();
    double result = 0;

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr();
        const uchar* mptr = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            result = norm_((const uchar*)sptr, total, cn, normType, result, mptr);
            break;
        case CV_8S:
            result = norm_((const schar*)sptr, total, cn, normType, result, mptr);
            break;
        case CV_16U:
            result = norm_((const ushort*)sptr, total, cn, normType, result, mptr);
            break;
        case CV_16S:
            result = norm_((const short*)sptr, total, cn, normType, result, mptr);
            break;
        case CV_32S:
            result = norm_((const int*)sptr, total, cn, normType, result, mptr);
            break;
        case CV_32F:
            result = norm_((const float*)sptr, total, cn, normType, result, mptr);
            break;
        case CV_64F:
            result = norm_((const double*)sptr, total, cn, normType, result, mptr);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        };
    }
    if( normType0 == NORM_L2 )
        result = sqrt(result);
    return result;
}


double norm(InputArray _src1, InputArray _src2, int normType, InputArray _mask)
{
    Mat src1 = _src1.getMat(), src2 = _src2.getMat(), mask = _mask.getMat();
    if( src1.depth() == CV_16F )
    {
        Mat src1_32f, src2_32f;
        src1.convertTo(src1_32f, CV_32F);
        src2.convertTo(src2_32f, CV_32F);
        return cvtest::norm(src1_32f, src2_32f, normType, _mask);
    }

    bool isRelative = (normType & NORM_RELATIVE) != 0;
    normType &= ~NORM_RELATIVE;

    if( normType == NORM_HAMMING || normType == NORM_HAMMING2 )
    {
        Mat temp;
        bitwise_xor(src1, src2, temp);
        if( !mask.empty() )
            bitwise_and(temp, mask, temp);

        CV_Assert( temp.depth() == CV_8U );

        const Mat *arrays[]={&temp, 0};
        Mat planes[1];

        NAryMatIterator it(arrays, planes);
        size_t total = planes[0].total();
        size_t i, nplanes = it.nplanes;
        double result = 0;
        int cellSize = normType == NORM_HAMMING ? 1 : 2;

        for( i = 0; i < nplanes; i++, ++it )
            result += normHamming(planes[0].ptr(), total, cellSize);
        return result;
    }
    int normType0 = normType;
    normType = normType == NORM_L2SQR ? NORM_L2 : normType;

    CV_CheckTypeEQ(src1.type(), src2.type(), "");
    CV_Assert(src1.size == src2.size);
    CV_Assert( mask.empty() || (src1.size == mask.size && mask.type() == CV_8U) );
    CV_Assert( normType == NORM_INF || normType == NORM_L1 || normType == NORM_L2 );
    const Mat *arrays[]={&src1, &src2, &mask, 0};
    Mat planes[3];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    int depth = src1.depth(), cn = planes[0].channels();
    double result = 0;

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();
        const uchar* mptr = planes[2].ptr();

        switch( depth )
        {
        case CV_8U:
            result = norm_((const uchar*)sptr1, (const uchar*)sptr2, total, cn, normType, result, mptr);
            break;
        case CV_8S:
            result = norm_((const schar*)sptr1, (const schar*)sptr2, total, cn, normType, result, mptr);
            break;
        case CV_16U:
            result = norm_((const ushort*)sptr1, (const ushort*)sptr2, total, cn, normType, result, mptr);
            break;
        case CV_16S:
            result = norm_((const short*)sptr1, (const short*)sptr2, total, cn, normType, result, mptr);
            break;
        case CV_32S:
            result = norm_((const int*)sptr1, (const int*)sptr2, total, cn, normType, result, mptr);
            break;
        case CV_32F:
            result = norm_((const float*)sptr1, (const float*)sptr2, total, cn, normType, result, mptr);
            break;
        case CV_64F:
            result = norm_((const double*)sptr1, (const double*)sptr2, total, cn, normType, result, mptr);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        };
    }
    if( normType0 == NORM_L2 )
        result = sqrt(result);
    return isRelative ? result / (cvtest::norm(src2, normType) + DBL_EPSILON) : result;
}

double PSNR(InputArray _src1, InputArray _src2)
{
    CV_Assert( _src1.depth() == CV_8U );
    double diff = std::sqrt(cvtest::norm(_src1, _src2, NORM_L2SQR)/(_src1.total()*_src1.channels()));
    return 20*log10(255./(diff+DBL_EPSILON));
}

template<typename _Tp> static double
crossCorr_(const _Tp* src1, const _Tp* src2, size_t total)
{
    double result = 0;
    for( size_t i = 0; i < total; i++ )
        result += (double)src1[i]*src2[i];
    return result;
}

double crossCorr(const Mat& src1, const Mat& src2)
{
    CV_Assert( src1.size == src2.size && src1.type() == src2.type() );
    const Mat *arrays[]={&src1, &src2, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].channels();
    size_t i, nplanes = it.nplanes;
    int depth = src1.depth();
    double result = 0;

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            result += crossCorr_((const uchar*)sptr1, (const uchar*)sptr2, total);
            break;
        case CV_8S:
            result += crossCorr_((const schar*)sptr1, (const schar*)sptr2, total);
            break;
        case CV_16U:
            result += crossCorr_((const ushort*)sptr1, (const ushort*)sptr2, total);
            break;
        case CV_16S:
            result += crossCorr_((const short*)sptr1, (const short*)sptr2, total);
            break;
        case CV_32S:
            result += crossCorr_((const int*)sptr1, (const int*)sptr2, total);
            break;
        case CV_32F:
            result += crossCorr_((const float*)sptr1, (const float*)sptr2, total);
            break;
        case CV_64F:
            result += crossCorr_((const double*)sptr1, (const double*)sptr2, total);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        };
    }
    return result;
}


static void
logicOp_(const uchar* src1, const uchar* src2, uchar* dst, size_t total, char c)
{
    size_t i;
    if( c == '&' )
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] & src2[i];
    else if( c == '|' )
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] | src2[i];
    else
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] ^ src2[i];
}

static void
logicOpS_(const uchar* src, const uchar* scalar, uchar* dst, size_t total, char c)
{
    const size_t blockSize = 96;
    size_t i, j;
    if( c == '&' )
        for( i = 0; i < total; i += blockSize, dst += blockSize, src += blockSize )
        {
            size_t sz = MIN(total - i, blockSize);
            for( j = 0; j < sz; j++ )
                dst[j] = src[j] & scalar[j];
        }
    else if( c == '|' )
        for( i = 0; i < total; i += blockSize, dst += blockSize, src += blockSize )
        {
            size_t sz = MIN(total - i, blockSize);
            for( j = 0; j < sz; j++ )
                dst[j] = src[j] | scalar[j];
        }
    else if( c == '^' )
    {
        for( i = 0; i < total; i += blockSize, dst += blockSize, src += blockSize )
        {
            size_t sz = MIN(total - i, blockSize);
            for( j = 0; j < sz; j++ )
                dst[j] = src[j] ^ scalar[j];
        }
    }
    else
        for( i = 0; i < total; i++ )
            dst[i] = ~src[i];
}


void logicOp( const Mat& src1, const Mat& src2, Mat& dst, char op )
{
    CV_Assert( op == '&' || op == '|' || op == '^' );
    CV_Assert( src1.type() == src2.type() && src1.size == src2.size );
    dst.create( src1.dims, &src1.size[0], src1.type() );
    const Mat *arrays[]={&src1, &src2, &dst, 0};
    Mat planes[3];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].elemSize();
    size_t i, nplanes = it.nplanes;

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();
        uchar* dptr = planes[2].ptr();

        logicOp_(sptr1, sptr2, dptr, total, op);
    }
}


void logicOp(const Mat& src, const Scalar& s, Mat& dst, char op)
{
    CV_Assert( op == '&' || op == '|' || op == '^' || op == '~' );
    dst.create( src.dims, &src.size[0], src.type() );
    const Mat *arrays[]={&src, &dst, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].elemSize();
    size_t i, nplanes = it.nplanes;
    double buf[12];
    scalarToRawData(s, buf, src.type(), (int)(96/planes[0].elemSize1()));

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr();
        uchar* dptr = planes[1].ptr();

        logicOpS_(sptr, (uchar*)&buf[0], dptr, total, op);
    }
}


template<typename _Tp> static void
compare_(const _Tp* src1, const _Tp* src2, uchar* dst, size_t total, int cmpop)
{
    size_t i;
    switch( cmpop )
    {
    case CMP_LT:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] < src2[i] ? 255 : 0;
        break;
    case CMP_LE:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] <= src2[i] ? 255 : 0;
        break;
    case CMP_EQ:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] == src2[i] ? 255 : 0;
        break;
    case CMP_NE:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] != src2[i] ? 255 : 0;
        break;
    case CMP_GE:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] >= src2[i] ? 255 : 0;
        break;
    case CMP_GT:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] > src2[i] ? 255 : 0;
        break;
    default:
        CV_Error(Error::StsBadArg, "Unknown comparison operation");
    }
}


template<typename _Tp, typename _WTp> static void
compareS_(const _Tp* src1, _WTp value, uchar* dst, size_t total, int cmpop)
{
    size_t i;
    switch( cmpop )
    {
    case CMP_LT:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] < value ? 255 : 0;
        break;
    case CMP_LE:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] <= value ? 255 : 0;
        break;
    case CMP_EQ:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] == value ? 255 : 0;
        break;
    case CMP_NE:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] != value ? 255 : 0;
        break;
    case CMP_GE:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] >= value ? 255 : 0;
        break;
    case CMP_GT:
        for( i = 0; i < total; i++ )
            dst[i] = src1[i] > value ? 255 : 0;
        break;
    default:
        CV_Error(Error::StsBadArg, "Unknown comparison operation");
    }
}


void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop)
{
    CV_Assert( src1.type() == src2.type() && src1.channels() == 1 && src1.size == src2.size );
    dst.create( src1.dims, &src1.size[0], CV_8U );
    const Mat *arrays[]={&src1, &src2, &dst, 0};
    Mat planes[3];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    int depth = src1.depth();

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();
        uchar* dptr = planes[2].ptr();

        switch( depth )
        {
        case CV_8U:
            compare_((const uchar*)sptr1, (const uchar*)sptr2, dptr, total, cmpop);
            break;
        case CV_8S:
            compare_((const schar*)sptr1, (const schar*)sptr2, dptr, total, cmpop);
            break;
        case CV_16U:
            compare_((const ushort*)sptr1, (const ushort*)sptr2, dptr, total, cmpop);
            break;
        case CV_16S:
            compare_((const short*)sptr1, (const short*)sptr2, dptr, total, cmpop);
            break;
        case CV_32S:
            compare_((const int*)sptr1, (const int*)sptr2, dptr, total, cmpop);
            break;
        case CV_32F:
            compare_((const float*)sptr1, (const float*)sptr2, dptr, total, cmpop);
            break;
        case CV_64F:
            compare_((const double*)sptr1, (const double*)sptr2, dptr, total, cmpop);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }
}

void compare(const Mat& src, double value, Mat& dst, int cmpop)
{
    CV_Assert( src.channels() == 1 );
    dst.create( src.dims, &src.size[0], CV_8U );
    const Mat *arrays[]={&src, &dst, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    int depth = src.depth();
    int ivalue = saturate_cast<int>(value);

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr();
        uchar* dptr = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            compareS_((const uchar*)sptr, ivalue, dptr, total, cmpop);
            break;
        case CV_8S:
            compareS_((const schar*)sptr, ivalue, dptr, total, cmpop);
            break;
        case CV_16U:
            compareS_((const ushort*)sptr, ivalue, dptr, total, cmpop);
            break;
        case CV_16S:
            compareS_((const short*)sptr, ivalue, dptr, total, cmpop);
            break;
        case CV_32S:
            compareS_((const int*)sptr, ivalue, dptr, total, cmpop);
            break;
        case CV_32F:
            compareS_((const float*)sptr, value, dptr, total, cmpop);
            break;
        case CV_64F:
            compareS_((const double*)sptr, value, dptr, total, cmpop);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }
}


template<typename _Tp> double
cmpUlpsInt_(const _Tp* src1, const _Tp* src2, size_t total, int imaxdiff,
           size_t startidx, size_t& idx)
{
    size_t i;
    int realmaxdiff = 0;
    for( i = 0; i < total; i++ )
    {
        int diff = std::abs(src1[i] - src2[i]);
        if( realmaxdiff < diff )
        {
            realmaxdiff = diff;
            if( diff > imaxdiff && idx == 0 )
                idx = i + startidx;
        }
    }
    return realmaxdiff;
}


template<> double cmpUlpsInt_<int>(const int* src1, const int* src2,
                                          size_t total, int imaxdiff,
                                          size_t startidx, size_t& idx)
{
    size_t i;
    double realmaxdiff = 0;
    for( i = 0; i < total; i++ )
    {
        double diff = fabs((double)src1[i] - (double)src2[i]);
        if( realmaxdiff < diff )
        {
            realmaxdiff = diff;
            if( diff > imaxdiff && idx == 0 )
                idx = i + startidx;
        }
    }
    return realmaxdiff;
}


static double
cmpUlpsFlt_(const int* src1, const int* src2, size_t total, int imaxdiff, size_t startidx, size_t& idx)
{
    const int C = 0x7fffffff;
    int realmaxdiff = 0;
    size_t i;
    for( i = 0; i < total; i++ )
    {
        int a = src1[i], b = src2[i];
        if( a < 0 ) a ^= C;
        if( b < 0 ) b ^= C;
        int diff = std::abs(a - b);
        if( realmaxdiff < diff )
        {
            realmaxdiff = diff;
            if( diff > imaxdiff && idx == 0 )
                idx = i + startidx;
        }
    }
    return realmaxdiff;
}


static double
cmpUlpsFlt_(const int64* src1, const int64* src2, size_t total, int imaxdiff, size_t startidx, size_t& idx)
{
    const int64 C = CV_BIG_INT(0x7fffffffffffffff);
    double realmaxdiff = 0;
    size_t i;
    for( i = 0; i < total; i++ )
    {
        int64 a = src1[i], b = src2[i];
        if( a < 0 ) a ^= C;
        if( b < 0 ) b ^= C;
        double diff = fabs((double)a - (double)b);
        if( realmaxdiff < diff )
        {
            realmaxdiff = diff;
            if( diff > imaxdiff && idx == 0 )
                idx = i + startidx;
        }
    }
    return realmaxdiff;
}

bool cmpUlps(const Mat& src1, const Mat& src2, int imaxDiff, double* _realmaxdiff, vector<int>* loc)
{
    CV_Assert( src1.type() == src2.type() && src1.size == src2.size );
    const Mat *arrays[]={&src1, &src2, 0};
    Mat planes[2];
    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].channels();
    size_t i, nplanes = it.nplanes;
    int depth = src1.depth();
    size_t startidx = 1, idx = 0;
    if(_realmaxdiff)
        *_realmaxdiff = 0;

    for( i = 0; i < nplanes; i++, ++it, startidx += total )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();
        double realmaxdiff = 0;

        switch( depth )
        {
        case CV_8U:
            realmaxdiff = cmpUlpsInt_((const uchar*)sptr1, (const uchar*)sptr2, total, imaxDiff, startidx, idx);
            break;
        case CV_8S:
            realmaxdiff = cmpUlpsInt_((const schar*)sptr1, (const schar*)sptr2, total, imaxDiff, startidx, idx);
            break;
        case CV_16U:
            realmaxdiff = cmpUlpsInt_((const ushort*)sptr1, (const ushort*)sptr2, total, imaxDiff, startidx, idx);
            break;
        case CV_16S:
            realmaxdiff = cmpUlpsInt_((const short*)sptr1, (const short*)sptr2, total, imaxDiff, startidx, idx);
            break;
        case CV_32S:
            realmaxdiff = cmpUlpsInt_((const int*)sptr1, (const int*)sptr2, total, imaxDiff, startidx, idx);
            break;
        case CV_32F:
            realmaxdiff = cmpUlpsFlt_((const int*)sptr1, (const int*)sptr2, total, imaxDiff, startidx, idx);
            break;
        case CV_64F:
            realmaxdiff = cmpUlpsFlt_((const int64*)sptr1, (const int64*)sptr2, total, imaxDiff, startidx, idx);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }

        if(_realmaxdiff)
            *_realmaxdiff = std::max(*_realmaxdiff, realmaxdiff);
    }
    if(idx > 0 && loc)
        setpos(src1, *loc, idx);
    return idx == 0;
}


template<typename _Tp> static void
checkInt_(const _Tp* a, size_t total, int imin, int imax, size_t startidx, size_t& idx)
{
    for( size_t i = 0; i < total; i++ )
    {
        int val = a[i];
        if( val < imin || val > imax )
        {
            idx = i + startidx;
            break;
        }
    }
}


template<typename _Tp> static void
checkFlt_(const _Tp* a, size_t total, double fmin, double fmax, size_t startidx, size_t& idx)
{
    for( size_t i = 0; i < total; i++ )
    {
        double val = a[i];
        if( cvIsNaN(val) || cvIsInf(val) || val < fmin || val > fmax )
        {
            idx = i + startidx;
            break;
        }
    }
}


// checks that the array does not have NaNs and/or Infs and all the elements are
// within [min_val,max_val). idx is the index of the first "bad" element.
int check( const Mat& a, double fmin, double fmax, vector<int>* _idx )
{
    const Mat *arrays[]={&a, 0};
    Mat plane;
    NAryMatIterator it(arrays, &plane);
    size_t total = plane.total()*plane.channels();
    size_t i, nplanes = it.nplanes;
    int depth = a.depth();
    size_t startidx = 1, idx = 0;
    int imin = 0, imax = 0;

    if( depth <= CV_32S )
    {
        imin = cvCeil(fmin);
        imax = cvFloor(fmax);
    }

    for( i = 0; i < nplanes; i++, ++it, startidx += total )
    {
        const uchar* aptr = plane.ptr();

        switch( depth )
        {
            case CV_8U:
                checkInt_((const uchar*)aptr, total, imin, imax, startidx, idx);
                break;
            case CV_8S:
                checkInt_((const schar*)aptr, total, imin, imax, startidx, idx);
                break;
            case CV_16U:
                checkInt_((const ushort*)aptr, total, imin, imax, startidx, idx);
                break;
            case CV_16S:
                checkInt_((const short*)aptr, total, imin, imax, startidx, idx);
                break;
            case CV_32S:
                checkInt_((const int*)aptr, total, imin, imax, startidx, idx);
                break;
            case CV_32F:
                checkFlt_((const float*)aptr, total, fmin, fmax, startidx, idx);
                break;
            case CV_64F:
                checkFlt_((const double*)aptr, total, fmin, fmax, startidx, idx);
                break;
            default:
                CV_Error(Error::StsUnsupportedFormat, "");
        }

        if( idx != 0 )
            break;
    }

    if(idx != 0 && _idx)
        setpos(a, *_idx, idx);
    return idx == 0 ? 0 : -1;
}

#define CMP_EPS_OK 0
#define CMP_EPS_BIG_DIFF -1
#define CMP_EPS_INVALID_TEST_DATA -2 // there is NaN or Inf value in test data
#define CMP_EPS_INVALID_REF_DATA -3 // there is NaN or Inf value in reference data

// compares two arrays. max_diff is the maximum actual difference,
// success_err_level is maximum allowed difference, idx is the index of the first
// element for which difference is >success_err_level
// (or index of element with the maximum difference)
int cmpEps( const Mat& arr_, const Mat& refarr_, double* _realmaxdiff,
            double success_err_level, vector<int>* _idx,
            bool element_wise_relative_error )
{
    Mat arr = arr_, refarr = refarr_;
    CV_Assert( arr.type() == refarr.type() && arr.size == refarr.size );
    if( arr.depth() == CV_16F )
    {
        Mat arr32f, refarr32f;
        arr.convertTo(arr32f, CV_32F);
        refarr.convertTo(refarr32f, CV_32F);
        arr = arr32f;
        refarr = refarr32f;
    }

    int ilevel = refarr.depth() <= CV_32S ? cvFloor(success_err_level) : 0;
    int result = CMP_EPS_OK;

    const Mat *arrays[]={&arr, &refarr, 0};
    Mat planes[2];
    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].channels(), j = total;
    size_t i, nplanes = it.nplanes;
    int depth = arr.depth();
    size_t startidx = 1, idx = 0;
    double realmaxdiff = 0, maxval = 0;

    if(_realmaxdiff)
        *_realmaxdiff = 0;

    if( refarr.depth() >= CV_32F && !element_wise_relative_error )
    {
        maxval = cvtest::norm( refarr, NORM_INF );
        maxval = MAX(maxval, 1.);
    }

    for( i = 0; i < nplanes; i++, ++it, startidx += total )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            realmaxdiff = cmpUlpsInt_((const uchar*)sptr1, (const uchar*)sptr2, total, ilevel, startidx, idx);
            break;
        case CV_8S:
            realmaxdiff = cmpUlpsInt_((const schar*)sptr1, (const schar*)sptr2, total, ilevel, startidx, idx);
            break;
        case CV_16U:
            realmaxdiff = cmpUlpsInt_((const ushort*)sptr1, (const ushort*)sptr2, total, ilevel, startidx, idx);
            break;
        case CV_16S:
            realmaxdiff = cmpUlpsInt_((const short*)sptr1, (const short*)sptr2, total, ilevel, startidx, idx);
            break;
        case CV_32S:
            realmaxdiff = cmpUlpsInt_((const int*)sptr1, (const int*)sptr2, total, ilevel, startidx, idx);
            break;
        case CV_32F:
            for( j = 0; j < total; j++ )
            {
                double a_val = ((float*)sptr1)[j];
                double b_val = ((float*)sptr2)[j];
                double threshold;
                if( ((int*)sptr1)[j] == ((int*)sptr2)[j] )
                    continue;
                if( cvIsNaN(a_val) || cvIsInf(a_val) )
                {
                    result = CMP_EPS_INVALID_TEST_DATA;
                    idx = startidx + j;
                    break;
                }
                if( cvIsNaN(b_val) || cvIsInf(b_val) )
                {
                    result = CMP_EPS_INVALID_REF_DATA;
                    idx = startidx + j;
                    break;
                }
                a_val = fabs(a_val - b_val);
                threshold = element_wise_relative_error ? fabs(b_val) + 1 : maxval;
                if( a_val > threshold*success_err_level )
                {
                    realmaxdiff = a_val/threshold;
                    if( idx == 0 )
                        idx = startidx + j;
                    break;
                }
            }
            break;
        case CV_64F:
            for( j = 0; j < total; j++ )
            {
                double a_val = ((double*)sptr1)[j];
                double b_val = ((double*)sptr2)[j];
                double threshold;
                if( ((int64*)sptr1)[j] == ((int64*)sptr2)[j] )
                    continue;
                if( cvIsNaN(a_val) || cvIsInf(a_val) )
                {
                    result = CMP_EPS_INVALID_TEST_DATA;
                    idx = startidx + j;
                    break;
                }
                if( cvIsNaN(b_val) || cvIsInf(b_val) )
                {
                    result = CMP_EPS_INVALID_REF_DATA;
                    idx = startidx + j;
                    break;
                }
                a_val = fabs(a_val - b_val);
                threshold = element_wise_relative_error ? fabs(b_val) + 1 : maxval;
                if( a_val > threshold*success_err_level )
                {
                    realmaxdiff = a_val/threshold;
                    idx = startidx + j;
                    break;
                }
            }
            break;
        default:
            assert(0);
            return CMP_EPS_BIG_DIFF;
        }
        if(_realmaxdiff)
            *_realmaxdiff = MAX(*_realmaxdiff, realmaxdiff);
        if( idx != 0 )
            break;
    }

    if( result == 0 && idx != 0 )
        result = CMP_EPS_BIG_DIFF;

    if( result < -1 && _realmaxdiff )
        *_realmaxdiff = exp(1000.);
    if(idx > 0 && _idx)
        setpos(arr, *_idx, idx);

    return result;
}


int cmpEps2( TS* ts, const Mat& a, const Mat& b, double success_err_level,
             bool element_wise_relative_error, const char* desc )
{
    char msg[100];
    double diff = 0;
    vector<int> idx;
    int code = cmpEps( a, b, &diff, success_err_level, &idx, element_wise_relative_error );

    switch( code )
    {
    case CMP_EPS_BIG_DIFF:
        sprintf( msg, "%s: Too big difference (=%g > %g)", desc, diff, success_err_level );
        code = TS::FAIL_BAD_ACCURACY;
        break;
    case CMP_EPS_INVALID_TEST_DATA:
        sprintf( msg, "%s: Invalid output", desc );
        code = TS::FAIL_INVALID_OUTPUT;
        break;
    case CMP_EPS_INVALID_REF_DATA:
        sprintf( msg, "%s: Invalid reference output", desc );
        code = TS::FAIL_INVALID_OUTPUT;
        break;
    default:
        ;
    }

    if( code < 0 )
    {
        if( a.total() == 1 )
        {
            ts->printf( TS::LOG, "%s\n", msg );
        }
        else if( a.dims == 2 && (a.rows == 1 || a.cols == 1) )
        {
            ts->printf( TS::LOG, "%s at element %d\n", msg, idx[0] + idx[1] );
        }
        else
        {
            string idxstr = vec2str(", ", &idx[0], idx.size());
            ts->printf( TS::LOG, "%s at (%s)\n", msg, idxstr.c_str() );
        }
    }

    return code;
}


int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
             double eps, const char* param_name )
{
    Mat _val(1, len, CV_64F, (void*)val);
    Mat _refval(1, len, CV_64F, (void*)refval);

    return cmpEps2( ts, _val, _refval, eps, true, param_name );
}


template<typename _Tp> static void
GEMM_(const _Tp* a_data0, int a_step, int a_delta,
      const _Tp* b_data0, int b_step, int b_delta,
      const _Tp* c_data0, int c_step, int c_delta,
      _Tp* d_data, int d_step,
      int d_rows, int d_cols, int a_cols, int cn,
      double alpha, double beta)
{
    for( int i = 0; i < d_rows; i++, d_data += d_step, c_data0 += c_step, a_data0 += a_step )
    {
        for( int j = 0; j < d_cols; j++ )
        {
            const _Tp* a_data = a_data0;
            const _Tp* b_data = b_data0 + j*b_delta;
            const _Tp* c_data = c_data0 + j*c_delta;

            if( cn == 1 )
            {
                double s = 0;
                for( int k = 0; k < a_cols; k++ )
                {
                    s += ((double)a_data[0])*b_data[0];
                    a_data += a_delta;
                    b_data += b_step;
                }
                d_data[j] = (_Tp)(s*alpha + (c_data ? c_data[0]*beta : 0));
            }
            else
            {
                double s_re = 0, s_im = 0;

                for( int k = 0; k < a_cols; k++ )
                {
                    s_re += ((double)a_data[0])*b_data[0] - ((double)a_data[1])*b_data[1];
                    s_im += ((double)a_data[0])*b_data[1] + ((double)a_data[1])*b_data[0];
                    a_data += a_delta;
                    b_data += b_step;
                }

                s_re *= alpha;
                s_im *= alpha;

                if( c_data )
                {
                    s_re += c_data[0]*beta;
                    s_im += c_data[1]*beta;
                }

                d_data[j*2] = (_Tp)s_re;
                d_data[j*2+1] = (_Tp)s_im;
            }
        }
    }
}


void gemm( const Mat& _a, const Mat& _b, double alpha,
           const Mat& _c, double beta, Mat& d, int flags )
{
    Mat a = _a, b = _b, c = _c;

    if( a.data == d.data )
        a = a.clone();

    if( b.data == d.data )
        b = b.clone();

    if( !c.empty() && c.data == d.data && (flags & cv::GEMM_3_T) )
        c = c.clone();

    int a_rows = a.rows, a_cols = a.cols, b_rows = b.rows, b_cols = b.cols;
    int cn = a.channels();
    int a_step = (int)a.step1(), a_delta = cn;
    int b_step = (int)b.step1(), b_delta = cn;
    int c_rows = 0, c_cols = 0, c_step = 0, c_delta = 0;

    CV_Assert( a.type() == b.type() && a.dims == 2 && b.dims == 2 && cn <= 2 );

    if( flags & cv::GEMM_1_T )
    {
        std::swap( a_rows, a_cols );
        std::swap( a_step, a_delta );
    }

    if( flags & cv::GEMM_2_T )
    {
        std::swap( b_rows, b_cols );
        std::swap( b_step, b_delta );
    }

    if( !c.empty() )
    {
        c_rows = c.rows;
        c_cols = c.cols;
        c_step = (int)c.step1();
        c_delta = cn;

        if( flags & cv::GEMM_3_T )
        {
            std::swap( c_rows, c_cols );
            std::swap( c_step, c_delta );
        }

        CV_Assert( c.dims == 2 && c.type() == a.type() && c_rows == a_rows && c_cols == b_cols );
    }

    d.create(a_rows, b_cols, a.type());

    if( a.depth() == CV_32F )
        GEMM_(a.ptr<float>(), a_step, a_delta, b.ptr<float>(), b_step, b_delta,
              !c.empty() ? c.ptr<float>() : 0, c_step, c_delta, d.ptr<float>(),
              (int)d.step1(), a_rows, b_cols, a_cols, cn, alpha, beta );
    else
        GEMM_(a.ptr<double>(), a_step, a_delta, b.ptr<double>(), b_step, b_delta,
              !c.empty() ? c.ptr<double>() : 0, c_step, c_delta, d.ptr<double>(),
              (int)d.step1(), a_rows, b_cols, a_cols, cn, alpha, beta );
}


template<typename _Tp> static void
transform_(const _Tp* sptr, _Tp* dptr, size_t total, int scn, int dcn, const double* mat)
{
    for( size_t i = 0; i < total; i++, sptr += scn, dptr += dcn )
    {
        for( int j = 0; j < dcn; j++ )
        {
            double s = mat[j*(scn + 1) + scn];
            for( int k = 0; k < scn; k++ )
                s += mat[j*(scn + 1) + k]*sptr[k];
            dptr[j] = saturate_cast<_Tp>(s);
        }
    }
}


void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& _shift )
{
    double mat[20];

    int scn = src.channels();
    int dcn = dst.channels();
    int depth = src.depth();
    int mattype = transmat.depth();
    Mat shift = _shift.reshape(1, 0);
    bool haveShift = !shift.empty();

    CV_Assert( scn <= 4 && dcn <= 4 &&
              (mattype == CV_32F || mattype == CV_64F) &&
              (!haveShift || (shift.type() == mattype && (shift.rows == 1 || shift.cols == 1))) );

    // prepare cn x (cn + 1) transform matrix
    if( mattype == CV_32F )
    {
        for( int i = 0; i < transmat.rows; i++ )
        {
            mat[i*(scn+1)+scn] = 0.;
            for( int j = 0; j < transmat.cols; j++ )
                mat[i*(scn+1)+j] = transmat.at<float>(i,j);
            if( haveShift )
                mat[i*(scn+1)+scn] = shift.at<float>(i);
        }
    }
    else
    {
        for( int i = 0; i < transmat.rows; i++ )
        {
            mat[i*(scn+1)+scn] = 0.;
            for( int j = 0; j < transmat.cols; j++ )
                mat[i*(scn+1)+j] = transmat.at<double>(i,j);
            if( haveShift )
                mat[i*(scn+1)+scn] = shift.at<double>(i);
        }
    }

    const Mat *arrays[]={&src, &dst, 0};
    Mat planes[2];
    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total();
    size_t i, nplanes = it.nplanes;

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr();
        uchar* dptr = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            transform_((const uchar*)sptr, (uchar*)dptr, total, scn, dcn, mat);
            break;
        case CV_8S:
            transform_((const schar*)sptr, (schar*)dptr, total, scn, dcn, mat);
            break;
        case CV_16U:
            transform_((const ushort*)sptr, (ushort*)dptr, total, scn, dcn, mat);
            break;
        case CV_16S:
            transform_((const short*)sptr, (short*)dptr, total, scn, dcn, mat);
            break;
        case CV_32S:
            transform_((const int*)sptr, (int*)dptr, total, scn, dcn, mat);
            break;
        case CV_32F:
            transform_((const float*)sptr, (float*)dptr, total, scn, dcn, mat);
            break;
        case CV_64F:
            transform_((const double*)sptr, (double*)dptr, total, scn, dcn, mat);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }
}

template<typename _Tp> static void
minmax_(const _Tp* src1, const _Tp* src2, _Tp* dst, size_t total, char op)
{
    if( op == 'M' )
        for( size_t i = 0; i < total; i++ )
            dst[i] = std::max(src1[i], src2[i]);
    else
        for( size_t i = 0; i < total; i++ )
            dst[i] = std::min(src1[i], src2[i]);
}

static void minmax(const Mat& src1, const Mat& src2, Mat& dst, char op)
{
    dst.create(src1.dims, src1.size, src1.type());
    CV_Assert( src1.type() == src2.type() && src1.size == src2.size );
    const Mat *arrays[]={&src1, &src2, &dst, 0};
    Mat planes[3];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].channels();
    size_t i, nplanes = it.nplanes, depth = src1.depth();

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();
        uchar* dptr = planes[2].ptr();

        switch( depth )
        {
        case CV_8U:
            minmax_((const uchar*)sptr1, (const uchar*)sptr2, (uchar*)dptr, total, op);
            break;
        case CV_8S:
            minmax_((const schar*)sptr1, (const schar*)sptr2, (schar*)dptr, total, op);
            break;
        case CV_16U:
            minmax_((const ushort*)sptr1, (const ushort*)sptr2, (ushort*)dptr, total, op);
            break;
        case CV_16S:
            minmax_((const short*)sptr1, (const short*)sptr2, (short*)dptr, total, op);
            break;
        case CV_32S:
            minmax_((const int*)sptr1, (const int*)sptr2, (int*)dptr, total, op);
            break;
        case CV_32F:
            minmax_((const float*)sptr1, (const float*)sptr2, (float*)dptr, total, op);
            break;
        case CV_64F:
            minmax_((const double*)sptr1, (const double*)sptr2, (double*)dptr, total, op);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }
}


void min(const Mat& src1, const Mat& src2, Mat& dst)
{
    minmax( src1, src2, dst, 'm' );
}

void max(const Mat& src1, const Mat& src2, Mat& dst)
{
    minmax( src1, src2, dst, 'M' );
}


template<typename _Tp> static void
minmax_(const _Tp* src1, _Tp val, _Tp* dst, size_t total, char op)
{
    if( op == 'M' )
        for( size_t i = 0; i < total; i++ )
            dst[i] = std::max(src1[i], val);
    else
        for( size_t i = 0; i < total; i++ )
            dst[i] = std::min(src1[i], val);
}

static void minmax(const Mat& src1, double val, Mat& dst, char op)
{
    dst.create(src1.dims, src1.size, src1.type());
    const Mat *arrays[]={&src1, &dst, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total()*planes[0].channels();
    size_t i, nplanes = it.nplanes, depth = src1.depth();
    int ival = saturate_cast<int>(val);

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        uchar* dptr = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            minmax_((const uchar*)sptr1, saturate_cast<uchar>(ival), (uchar*)dptr, total, op);
            break;
        case CV_8S:
            minmax_((const schar*)sptr1, saturate_cast<schar>(ival), (schar*)dptr, total, op);
            break;
        case CV_16U:
            minmax_((const ushort*)sptr1, saturate_cast<ushort>(ival), (ushort*)dptr, total, op);
            break;
        case CV_16S:
            minmax_((const short*)sptr1, saturate_cast<short>(ival), (short*)dptr, total, op);
            break;
        case CV_32S:
            minmax_((const int*)sptr1, saturate_cast<int>(ival), (int*)dptr, total, op);
            break;
        case CV_32F:
            minmax_((const float*)sptr1, saturate_cast<float>(val), (float*)dptr, total, op);
            break;
        case CV_64F:
            minmax_((const double*)sptr1, saturate_cast<double>(val), (double*)dptr, total, op);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }
}


void min(const Mat& src1, double val, Mat& dst)
{
    minmax( src1, val, dst, 'm' );
}

void max(const Mat& src1, double val, Mat& dst)
{
    minmax( src1, val, dst, 'M' );
}


template<typename _Tp> static void
muldiv_(const _Tp* src1, const _Tp* src2, _Tp* dst, size_t total, double scale, char op)
{
    if( op == '*' )
        for( size_t i = 0; i < total; i++ )
            dst[i] = saturate_cast<_Tp>((scale*src1[i])*src2[i]);
    else if( src1 )
        for( size_t i = 0; i < total; i++ )
            dst[i] = src2[i] ? saturate_cast<_Tp>((scale*src1[i])/src2[i]) : 0;
    else
        for( size_t i = 0; i < total; i++ )
            dst[i] = src2[i] ? saturate_cast<_Tp>(scale/src2[i]) : 0;
}

static void muldiv(const Mat& src1, const Mat& src2, Mat& dst, double scale, char op)
{
    dst.create(src2.dims, src2.size, src2.type());
    CV_Assert( src1.empty() || (src1.type() == src2.type() && src1.size == src2.size) );
    const Mat *arrays[]={&src1, &src2, &dst, 0};
    Mat planes[3];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[1].total()*planes[1].channels();
    size_t i, nplanes = it.nplanes, depth = src2.depth();

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr1 = planes[0].ptr();
        const uchar* sptr2 = planes[1].ptr();
        uchar* dptr = planes[2].ptr();

        switch( depth )
        {
        case CV_8U:
            muldiv_((const uchar*)sptr1, (const uchar*)sptr2, (uchar*)dptr, total, scale, op);
            break;
        case CV_8S:
            muldiv_((const schar*)sptr1, (const schar*)sptr2, (schar*)dptr, total, scale, op);
            break;
        case CV_16U:
            muldiv_((const ushort*)sptr1, (const ushort*)sptr2, (ushort*)dptr, total, scale, op);
            break;
        case CV_16S:
            muldiv_((const short*)sptr1, (const short*)sptr2, (short*)dptr, total, scale, op);
            break;
        case CV_32S:
            muldiv_((const int*)sptr1, (const int*)sptr2, (int*)dptr, total, scale, op);
            break;
        case CV_32F:
            muldiv_((const float*)sptr1, (const float*)sptr2, (float*)dptr, total, scale, op);
            break;
        case CV_64F:
            muldiv_((const double*)sptr1, (const double*)sptr2, (double*)dptr, total, scale, op);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }
}


void multiply(const Mat& src1, const Mat& src2, Mat& dst, double scale)
{
    muldiv( src1, src2, dst, scale, '*' );
}

void divide(const Mat& src1, const Mat& src2, Mat& dst, double scale)
{
    muldiv( src1, src2, dst, scale, '/' );
}


template<typename _Tp> static void
mean_(const _Tp* src, const uchar* mask, size_t total, int cn, Scalar& sum, int& nz)
{
    if( !mask )
    {
        nz += (int)total;
        total *= cn;
        for( size_t i = 0; i < total; i += cn )
        {
            for( int c = 0; c < cn; c++ )
                sum[c] += src[i + c];
        }
    }
    else
    {
        for( size_t i = 0; i < total; i++ )
            if( mask[i] )
            {
                nz++;
                for( int c = 0; c < cn; c++ )
                    sum[c] += src[i*cn + c];
            }
    }
}

Scalar mean(const Mat& src, const Mat& mask)
{
    CV_Assert(mask.empty() || (mask.type() == CV_8U && mask.size == src.size));
    Scalar sum;
    int nz = 0;

    const Mat *arrays[]={&src, &mask, 0};
    Mat planes[2];

    NAryMatIterator it(arrays, planes);
    size_t total = planes[0].total();
    size_t i, nplanes = it.nplanes;
    int depth = src.depth(), cn = src.channels();

    for( i = 0; i < nplanes; i++, ++it )
    {
        const uchar* sptr = planes[0].ptr();
        const uchar* mptr = planes[1].ptr();

        switch( depth )
        {
        case CV_8U:
            mean_((const uchar*)sptr, mptr, total, cn, sum, nz);
            break;
        case CV_8S:
            mean_((const schar*)sptr, mptr, total, cn, sum, nz);
            break;
        case CV_16U:
            mean_((const ushort*)sptr, mptr, total, cn, sum, nz);
            break;
        case CV_16S:
            mean_((const short*)sptr, mptr, total, cn, sum, nz);
            break;
        case CV_32S:
            mean_((const int*)sptr, mptr, total, cn, sum, nz);
            break;
        case CV_32F:
            mean_((const float*)sptr, mptr, total, cn, sum, nz);
            break;
        case CV_64F:
            mean_((const double*)sptr, mptr, total, cn, sum, nz);
            break;
        default:
            CV_Error(Error::StsUnsupportedFormat, "");
        }
    }

    return sum * (1./std::max(nz, 1));
}


void  patchZeros( Mat& mat, double level )
{
    int j, ncols = mat.cols * mat.channels();
    int depth = mat.depth();
    CV_Assert( depth == CV_32F || depth == CV_64F );

    for( int i = 0; i < mat.rows; i++ )
    {
        if( depth == CV_32F )
        {
            float* data = mat.ptr<float>(i);
            for( j = 0; j < ncols; j++ )
                if( fabs(data[j]) < level )
                    data[j] += 1;
        }
        else
        {
            double* data = mat.ptr<double>(i);
            for( j = 0; j < ncols; j++ )
                if( fabs(data[j]) < level )
                    data[j] += 1;
        }
    }
}


static void calcSobelKernel1D( int order, int _aperture_size, int size, vector<int>& kernel )
{
    int i, j, oldval, newval;
    kernel.resize(size + 1);

    if( _aperture_size < 0 )
    {
        static const int scharr[8] = { 3, 10, 3, -1, 0, 1, 0, 0 };  // extra elements to eliminate "-Warray-bounds" bogus warning
        assert( size == 3 );
        for( i = 0; i < size; i++ )
            kernel[i] = scharr[order*3 + i];
        return;
    }

    for( i = 1; i <= size; i++ )
        kernel[i] = 0;
    kernel[0] = 1;

    for( i = 0; i < size - order - 1; i++ )
    {
        oldval = kernel[0];
        for( j = 1; j <= size; j++ )
        {
            newval = kernel[j] + kernel[j-1];
            kernel[j-1] = oldval;
            oldval = newval;
        }
    }

    for( i = 0; i < order; i++ )
    {
        oldval = -kernel[0];
        for( j = 1; j <= size; j++ )
        {
            newval = kernel[j-1] - kernel[j];
            kernel[j-1] = oldval;
            oldval = newval;
        }
    }
}


Mat calcSobelKernel2D( int dx, int dy, int _aperture_size, int origin )
{
    CV_Assert( (_aperture_size == -1 || (_aperture_size >= 1 && _aperture_size % 2 == 1)) &&
              dx >= 0 && dy >= 0 && dx + dy <= 3 );
    Size ksize = _aperture_size == -1 ? Size(3,3) : _aperture_size > 1 ?
        Size(_aperture_size, _aperture_size) : dx > 0 ? Size(3, 1) : Size(1, 3);

    Mat kernel(ksize, CV_32F);
    vector<int> kx, ky;

    calcSobelKernel1D( dx, _aperture_size, ksize.width, kx );
    calcSobelKernel1D( dy, _aperture_size, ksize.height, ky );

    for( int i = 0; i < kernel.rows; i++ )
    {
        float ay = (float)ky[i]*(origin && (dy & 1) ? -1 : 1);
        for( int j = 0; j < kernel.cols; j++ )
            kernel.at<float>(i, j) = kx[j]*ay;
    }

    return kernel;
}


Mat calcLaplaceKernel2D( int aperture_size )
{
    int ksize = aperture_size == 1 ? 3 : aperture_size;
    Mat kernel(ksize, ksize, CV_32F);

    vector<int> kx, ky;

    calcSobelKernel1D( 2, aperture_size, ksize, kx );
    if( aperture_size > 1 )
        calcSobelKernel1D( 0, aperture_size, ksize, ky );
    else
    {
        ky.resize(3);
        ky[0] = ky[2] = 0; ky[1] = 1;
    }

    for( int i = 0; i < ksize; i++ )
        for( int j = 0; j < ksize; j++ )
            kernel.at<float>(i, j) = (float)(kx[j]*ky[i] + kx[i]*ky[j]);

    return kernel;
}


void initUndistortMap( const Mat& _a0, const Mat& _k0, const Mat& _R0, const Mat& _new_cam0, Size sz, Mat& __mapx, Mat& __mapy, int map_type )
{
    Mat _mapx(sz, CV_32F), _mapy(sz, CV_32F);

    double a[9], k[5]={0,0,0,0,0}, iR[9]={1, 0, 0, 0, 1, 0, 0, 0, 1}, a1[9];
    Mat _a(3, 3, CV_64F, a), _a1(3, 3, CV_64F, a1);
    Mat _k(_k0.rows,_k0.cols, CV_MAKETYPE(CV_64F,_k0.channels()),k);
    Mat _iR(3, 3, CV_64F, iR);
    double fx, fy, cx, cy, ifx, ify, cxn, cyn;

    CV_Assert(_k0.empty() ||
              _k0.size() == Size(5, 1) ||
              _k0.size() == Size(1, 5) ||
              _k0.size() == Size(4, 1) ||
              _k0.size() == Size(1, 4));
    CV_Assert(_a0.size() == Size(3, 3));

    _a0.convertTo(_a, CV_64F);
    if( !_k0.empty() )
        _k0.convertTo(_k, CV_64F);
    if( !_R0.empty() )
    {
        CV_Assert(_R0.size() == Size(3, 3));
        Mat tmp;
        _R0.convertTo(tmp, CV_64F);
        invert(tmp, _iR, DECOMP_LU);
    }
    if( !_new_cam0.empty() )
    {
        CV_Assert(_new_cam0.size() == Size(3, 3));
        _new_cam0.convertTo(_a1, CV_64F);
    }
    else
        _a.copyTo(_a1);

    fx = a[0]; fy = a[4]; cx = a[2]; cy = a[5];
    ifx = 1./a1[0]; ify = 1./a1[4];
    cxn = a1[2];
    cyn = a1[5];

    for( int v = 0; v < sz.height; v++ )
    {
        for( int u = 0; u < sz.width; u++ )
        {
            double x_ = (u - cxn)*ifx;
            double y_ = (v - cyn)*ify;
            double X = iR[0]*x_ + iR[1]*y_ + iR[2];
            double Y = iR[3]*x_ + iR[4]*y_ + iR[5];
            double Z = iR[6]*x_ + iR[7]*y_ + iR[8];
            double x = X/Z;
            double y = Y/Z;
            double x2 = x*x, y2 = y*y;
            double r2 = x2 + y2;
            double cdist = 1 + (k[0] + (k[1] + k[4]*r2)*r2)*r2;
            double x1 = x*cdist + k[2]*2*x*y + k[3]*(r2 + 2*x2);
            double y1 = y*cdist + k[3]*2*x*y + k[2]*(r2 + 2*y2);

            _mapy.at<float>(v, u) = (float)(y1*fy + cy);
            _mapx.at<float>(v, u) = (float)(x1*fx + cx);
        }
    }

    _mapx.convertTo(__mapx, map_type);
    _mapy.convertTo(__mapy, map_type);
}

std::ostream& operator << (std::ostream& out, const MatInfo& m)
{
    if( !m.m || m.m->empty() )
        out << "<Empty>";
    else
    {
        static const char* depthstr[] = {"8u", "8s", "16u", "16s", "32s", "32f", "64f", "?"};
        out << depthstr[m.m->depth()] << "C" << m.m->channels() << " " << m.m->dims << "-dim (";
        for( int i = 0; i < m.m->dims; i++ )
            out << m.m->size[i] << (i < m.m->dims-1 ? " x " : ")");
    }
    return out;
}


static Mat getSubArray(const Mat& m, int border, vector<int>& ofs0, vector<int>& ofs)
{
    ofs.resize(ofs0.size());
    if( border < 0 )
    {
        std::copy(ofs0.begin(), ofs0.end(), ofs.begin());
        return m;
    }
    int i, d = m.dims;
    CV_Assert(d == (int)ofs.size());
    vector<Range> r(d);
    for( i = 0; i < d; i++ )
    {
        r[i].start = std::max(0, ofs0[i] - border);
        r[i].end = std::min(ofs0[i] + 1 + border, m.size[i]);
        ofs[i] = std::min(ofs0[i], border);
    }
    return m(&r[0]);
}

template<typename _Tp, typename _WTp> static void
writeElems(std::ostream& out, const void* data, int nelems, int starpos)
{
    for(int i = 0; i < nelems; i++)
    {
        if( i == starpos )
            out << "*";
        out << (_WTp)((_Tp*)data)[i];
        if( i == starpos )
            out << "*";
        out << (i+1 < nelems ? ", " : "");
    }
}


static void writeElems(std::ostream& out, const void* data, int nelems, int depth, int starpos)
{
    if(depth == CV_8U)
        writeElems<uchar, int>(out, data, nelems, starpos);
    else if(depth == CV_8S)
        writeElems<schar, int>(out, data, nelems, starpos);
    else if(depth == CV_16U)
        writeElems<ushort, int>(out, data, nelems, starpos);
    else if(depth == CV_16S)
        writeElems<short, int>(out, data, nelems, starpos);
    else if(depth == CV_32S)
        writeElems<int, int>(out, data, nelems, starpos);
    else if(depth == CV_32F)
    {
        std::streamsize pp = out.precision();
        out.precision(8);
        writeElems<float, float>(out, data, nelems, starpos);
        out.precision(pp);
    }
    else if(depth == CV_64F)
    {
        std::streamsize pp = out.precision();
        out.precision(16);
        writeElems<double, double>(out, data, nelems, starpos);
        out.precision(pp);
    }
    else
        CV_Error(Error::StsUnsupportedFormat, "");
}


struct MatPart
{
    MatPart(const Mat& _m, const vector<int>* _loc)
    : m(&_m), loc(_loc) {}
    const Mat* m;
    const vector<int>* loc;
};

static std::ostream& operator << (std::ostream& out, const MatPart& m)
{
    CV_Assert( !m.loc || ((int)m.loc->size() == m.m->dims && m.m->dims <= 2) );
    if( !m.loc )
        out << *m.m;
    else
    {
        int i, depth = m.m->depth(), cn = m.m->channels(), width = m.m->cols*cn;
        for( i = 0; i < m.m->rows; i++ )
        {
            writeElems(out, m.m->ptr(i), width, depth, i == (*m.loc)[0] ? (*m.loc)[1] : -1);
            out << (i < m.m->rows-1 ? ";\n" : "");
        }
    }
    return out;
}

MatComparator::MatComparator(double _maxdiff, int _context)
    : maxdiff(_maxdiff), realmaxdiff(DBL_MAX), context(_context) {}

::testing::AssertionResult
MatComparator::operator()(const char* expr1, const char* expr2,
                          const Mat& m1, const Mat& m2)
{
    if( m1.type() != m2.type() || m1.size != m2.size )
        return ::testing::AssertionFailure()
        << "The reference and the actual output arrays have different type or size:\n"
        << expr1 << " ~ " << MatInfo(m1) << "\n"
        << expr2 << " ~ " << MatInfo(m2) << "\n";

    //bool ok = cvtest::cmpUlps(m1, m2, maxdiff, &realmaxdiff, &loc0);
    int code = cmpEps( m1, m2, &realmaxdiff, maxdiff, &loc0, true);

    if(code >= 0)
        return ::testing::AssertionSuccess();

    Mat m[] = {m1.reshape(1,0), m2.reshape(1,0)};
    int dims = m[0].dims;
    vector<int> loc;
    int border = dims <= 2 ? context : 0;

    Mat m1part, m2part;
    if( border == 0 )
    {
        loc = loc0;
        m1part = Mat(1, 1, m[0].depth(), m[0].ptr(&loc[0]));
        m2part = Mat(1, 1, m[1].depth(), m[1].ptr(&loc[0]));
    }
    else
    {
        m1part = getSubArray(m[0], border, loc0, loc);
        m2part = getSubArray(m[1], border, loc0, loc);
    }

    return ::testing::AssertionFailure()
    << "too big relative difference (" << realmaxdiff << " > "
    << maxdiff << ") between "
    << MatInfo(m1) << " '" << expr1 << "' and '" << expr2 << "' at " << Mat(loc0).t() << ".\n"
    << "- " << expr1 << ":\n" << MatPart(m1part, border > 0 ? &loc : 0) << ".\n"
    << "- " << expr2 << ":\n" << MatPart(m2part, border > 0 ? &loc : 0) << ".\n";
}

void threshold( const Mat& _src, Mat& _dst,
                            double thresh, double maxval, int thresh_type )
{
    int i, j;
    int depth = _src.depth(), cn = _src.channels();
    int width_n = _src.cols*cn, height = _src.rows;
    int ithresh = cvFloor(thresh);
    int imaxval, ithresh2;

    if( depth == CV_8U )
    {
        ithresh2 = saturate_cast<uchar>(ithresh);
        imaxval = saturate_cast<uchar>(maxval);
    }
    else if( depth == CV_16S )
    {
        ithresh2 = saturate_cast<short>(ithresh);
        imaxval = saturate_cast<short>(maxval);
    }
    else
    {
        ithresh2 = cvRound(ithresh);
        imaxval = cvRound(maxval);
    }

    assert( depth == CV_8U || depth == CV_16S || depth == CV_32F );

    switch( thresh_type )
    {
    case CV_THRESH_BINARY:
        for( i = 0; i < height; i++ )
        {
            if( depth == CV_8U )
            {
                const uchar* src = _src.ptr<uchar>(i);
                uchar* dst = _dst.ptr<uchar>(i);
                for( j = 0; j < width_n; j++ )
                    dst[j] = (uchar)(src[j] > ithresh ? imaxval : 0);
            }
            else if( depth == CV_16S )
            {
                const short* src = _src.ptr<short>(i);
                short* dst = _dst.ptr<short>(i);
                for( j = 0; j < width_n; j++ )
                    dst[j] = (short)(src[j] > ithresh ? imaxval : 0);
            }
            else
            {
                const float* src = _src.ptr<float>(i);
                float* dst = _dst.ptr<float>(i);
                for( j = 0; j < width_n; j++ )
                    dst[j] = (float)((double)src[j] > thresh ? maxval : 0.f);
            }
        }
        break;
    case CV_THRESH_BINARY_INV:
        for( i = 0; i < height; i++ )
        {
            if( depth == CV_8U )
            {
                const uchar* src = _src.ptr<uchar>(i);
                uchar* dst = _dst.ptr<uchar>(i);
                for( j = 0; j < width_n; j++ )
                    dst[j] = (uchar)(src[j] > ithresh ? 0 : imaxval);
            }
            else if( depth == CV_16S )
            {
                const short* src = _src.ptr<short>(i);
                short* dst = _dst.ptr<short>(i);
                for( j = 0; j < width_n; j++ )
                    dst[j] = (short)(src[j] > ithresh ? 0 : imaxval);
            }
            else
            {
                const float* src = _src.ptr<float>(i);
                float* dst = _dst.ptr<float>(i);
                for( j = 0; j < width_n; j++ )
                    dst[j] = (float)((double)src[j] > thresh ? 0.f : maxval);
            }
        }
        break;
    case CV_THRESH_TRUNC:
        for( i = 0; i < height; i++ )
        {
            if( depth == CV_8U )
            {
                const uchar* src = _src.ptr<uchar>(i);
                uchar* dst = _dst.ptr<uchar>(i);
                for( j = 0; j < width_n; j++ )
                {
                    int s = src[j];
                    dst[j] = (uchar)(s > ithresh ? ithresh2 : s);
                }
            }
            else if( depth == CV_16S )
            {
                const short* src = _src.ptr<short>(i);
                short* dst = _dst.ptr<short>(i);
                for( j = 0; j < width_n; j++ )
                {
                    int s = src[j];
                    dst[j] = (short)(s > ithresh ? ithresh2 : s);
                }
            }
            else
            {
                const float* src = _src.ptr<float>(i);
                float* dst = _dst.ptr<float>(i);
                for( j = 0; j < width_n; j++ )
                {
                    double s = src[j];
                    dst[j] = (float)(s > thresh ? thresh : s);
                }
            }
        }
        break;
    case CV_THRESH_TOZERO:
        for( i = 0; i < height; i++ )
        {
            if( depth == CV_8U )
            {
                const uchar* src = _src.ptr<uchar>(i);
                uchar* dst = _dst.ptr<uchar>(i);
                for( j = 0; j < width_n; j++ )
                {
                    int s = src[j];
                    dst[j] = (uchar)(s > ithresh ? s : 0);
                }
            }
            else if( depth == CV_16S )
            {
                const short* src = _src.ptr<short>(i);
                short* dst = _dst.ptr<short>(i);
                for( j = 0; j < width_n; j++ )
                {
                    int s = src[j];
                    dst[j] = (short)(s > ithresh ? s : 0);
                }
            }
            else
            {
                const float* src = _src.ptr<float>(i);
                float* dst = _dst.ptr<float>(i);
                for( j = 0; j < width_n; j++ )
                {
                    float s = src[j];
                    dst[j] = s > thresh ? s : 0.f;
                }
            }
        }
        break;
    case CV_THRESH_TOZERO_INV:
        for( i = 0; i < height; i++ )
        {
            if( depth == CV_8U )
            {
                const uchar* src = _src.ptr<uchar>(i);
                uchar* dst = _dst.ptr<uchar>(i);
                for( j = 0; j < width_n; j++ )
                {
                    int s = src[j];
                    dst[j] = (uchar)(s > ithresh ? 0 : s);
                }
            }
            else if( depth == CV_16S )
            {
                const short* src = _src.ptr<short>(i);
                short* dst = _dst.ptr<short>(i);
                for( j = 0; j < width_n; j++ )
                {
                    int s = src[j];
                    dst[j] = (short)(s > ithresh ? 0 : s);
                }
            }
            else
            {
                const float* src = _src.ptr<float>(i);
                float* dst = _dst.ptr<float>(i);
                for( j = 0; j < width_n; j++ )
                {
                    float s = src[j];
                    dst[j] = s > thresh ? 0.f : s;
                }
            }
        }
        break;
    default:
        assert(0);
    }
}


static void
_minMaxIdx( const float* src, const uchar* mask, double* _minVal, double* _maxVal,
            size_t* _minIdx, size_t* _maxIdx, int len, size_t startIdx )
{
    double minVal = FLT_MAX, maxVal = -FLT_MAX;
    size_t minIdx = 0, maxIdx = 0;

    if( !mask )
    {
        for( int i = 0; i < len; i++ )
        {
            float val = src[i];
            if( val < minVal )
            {
                minVal = val;
                minIdx = startIdx + i;
            }
            if( val > maxVal )
            {
                maxVal = val;
                maxIdx = startIdx + i;
            }
        }
    }
    else
    {
        for( int i = 0; i < len; i++ )
        {
            float val = src[i];
            if( mask[i] && val < minVal )
            {
                minVal = val;
                minIdx = startIdx + i;
            }
            if( mask[i] && val > maxVal )
            {
                maxVal = val;
                maxIdx = startIdx + i;
            }
        }
    }

    if (_minIdx)
        *_minIdx = minIdx;
    if (_maxIdx)
        *_maxIdx = maxIdx;
    if (_minVal)
        *_minVal = minVal;
    if (_maxVal)
        *_maxVal = maxVal;
}


void minMaxIdx( InputArray _img, double* minVal, double* maxVal,
                    Point* minLoc, Point* maxLoc, InputArray _mask )
{
    Mat img = _img.getMat();
    Mat mask = _mask.getMat();
    CV_Assert(img.dims <= 2);

    _minMaxIdx((const float*)img.data, mask.data, minVal, maxVal, (size_t*)minLoc, (size_t*)maxLoc, (int)img.total(),1);
    if( minLoc )
        std::swap(minLoc->x, minLoc->y);
    if( maxLoc )
        std::swap(maxLoc->x, maxLoc->y);
}

}