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 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203
|
\section{Operations on Arrays}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% C %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ifCPy
\cvCPyFunc{AbsDiff}
Calculates absolute difference between two arrays.
\cvdefC{void cvAbsDiff(const CvArr* src1, const CvArr* src2, CvArr* dst);}
\cvdefPy{AbsDiff(src1,src2,dst)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\end{description}
The function calculates absolute difference between two arrays.
\[ \texttt{dst}(i)_c = |\texttt{src1}(I)_c - \texttt{src2}(I)_c| \]
All the arrays must have the same data type and the same size (or ROI size).
\cvCPyFunc{AbsDiffS}
Calculates absolute difference between an array and a scalar.
\cvdefC{void cvAbsDiffS(const CvArr* src, CvArr* dst, CvScalar value);}
\cvdefPy{AbsDiffS(src,value,dst)-> None}
\ifC
\begin{lstlisting}
#define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))
\end{lstlisting}
\fi
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array}
\cvarg{value}{The scalar}
\end{description}
The function calculates absolute difference between an array and a scalar.
\[ \texttt{dst}(i)_c = |\texttt{src}(I)_c - \texttt{value}_c| \]
All the arrays must have the same data type and the same size (or ROI size).
\cvCPyFunc{Add}
Computes the per-element sum of two arrays.
\cvdefC{void cvAdd(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{Add(src1,src2,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function adds one array to another:
\begin{lstlisting}
dst(I)=src1(I)+src2(I) if mask(I)!=0
\end{lstlisting}
All the arrays must have the same type, except the mask, and the same size (or ROI size).
For types that have limited range this operation is saturating.
\cvCPyFunc{AddS}
Computes the sum of an array and a scalar.
\cvdefC{void cvAddS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{AddS(src,value,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{value}{Added scalar}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function adds a scalar \texttt{value} to every element in the source array \texttt{src1} and stores the result in \texttt{dst}.
For types that have limited range this operation is saturating.
\begin{lstlisting}
dst(I)=src(I)+value if mask(I)!=0
\end{lstlisting}
All the arrays must have the same type, except the mask, and the same size (or ROI size).
\cvCPyFunc{AddWeighted}
Computes the weighted sum of two arrays.
\cvdefC{void cvAddWeighted(const CvArr* src1, double alpha,
const CvArr* src2, double beta,
double gamma, CvArr* dst);}
\cvdefPy{AddWeighted(src1,alpha,src2,beta,gamma,dst)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{alpha}{Weight for the first array elements}
\cvarg{src2}{The second source array}
\cvarg{beta}{Weight for the second array elements}
\cvarg{dst}{The destination array}
\cvarg{gamma}{Scalar, added to each sum}
\end{description}
The function calculates the weighted sum of two arrays as follows:
\begin{lstlisting}
dst(I)=src1(I)*alpha+src2(I)*beta+gamma
\end{lstlisting}
All the arrays must have the same type and the same size (or ROI size).
For types that have limited range this operation is saturating.
\cvCPyFunc{And}
Calculates per-element bit-wise conjunction of two arrays.
\cvdefC{void cvAnd(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{And(src1,src2,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function calculates per-element bit-wise logical conjunction of two arrays:
\begin{lstlisting}
dst(I)=src1(I)&src2(I) if mask(I)!=0
\end{lstlisting}
In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
\cvCPyFunc{AndS}
Calculates per-element bit-wise conjunction of an array and a scalar.
\cvdefC{void cvAndS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{AndS(src,value,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{value}{Scalar to use in the operation}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function calculates per-element bit-wise conjunction of an array and a scalar:
\begin{lstlisting}
dst(I)=src(I)&value if mask(I)!=0
\end{lstlisting}
Prior to the actual operation, the scalar is converted to the same type as that of the array(s). In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
\ifC
The following sample demonstrates how to calculate the absolute value of floating-point array elements by clearing the most-significant bit:
\begin{lstlisting}
float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
CvMat A = cvMat(3, 3, CV\_32F, &a);
int i, absMask = 0x7fffffff;
cvAndS(&A, cvRealScalar(*(float*)&absMask), &A, 0);
for(i = 0; i < 9; i++ )
printf("%.1f ", a[i]);
\end{lstlisting}
The code should print:
\begin{lstlisting}
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
\end{lstlisting}
\fi
\cvCPyFunc{Avg}
Calculates average (mean) of array elements.
\cvdefC{CvScalar cvAvg(const CvArr* arr, const CvArr* mask=NULL);}
\cvdefPy{Avg(arr,mask=NULL)-> CvScalar}
\begin{description}
\cvarg{arr}{The array}
\cvarg{mask}{The optional operation mask}
\end{description}
The function calculates the average value \texttt{M} of array elements, independently for each channel:
\[
\begin{array}{l}
N = \sum_I (\texttt{mask}(I) \ne 0)\\
M_c = \frac{\sum_{I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c}{N}
\end{array}
\]
If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average to the first scalar component $ S_0 $ .
\cvCPyFunc{AvgSdv}
Calculates average (mean) of array elements.
\cvdefC{void cvAvgSdv(const CvArr* arr, CvScalar* mean, CvScalar* stdDev, const CvArr* mask=NULL);}
\cvdefPy{AvgSdv(arr,mask=NULL)-> (mean, stdDev)}
\begin{description}
\cvarg{arr}{The array}
\ifC
\cvarg{mean}{Pointer to the output mean value, may be NULL if it is not needed}
\cvarg{stdDev}{Pointer to the output standard deviation}
\fi
\cvarg{mask}{The optional operation mask}
\ifPy
\cvarg{mean}{Mean value, a CvScalar}
\cvarg{stdDev}{Standard deviation, a CvScalar}
\fi
\end{description}
The function calculates the average value and standard deviation of array elements, independently for each channel:
\[
\begin{array}{l}
N = \sum_I (\texttt{mask}(I) \ne 0)\\
mean_c = \frac{1}{N} \, \sum_{ I, \, \texttt{mask}(I) \ne 0} \texttt{arr}(I)_c\\
stdDev_c = \sqrt{\frac{1}{N} \, \sum_{ I, \, \texttt{mask}(I) \ne 0} (\texttt{arr}(I)_c - mean_c)^2}
\end{array}
\]
If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the average and standard deviation to the first components of the output scalars ($mean_0$ and $stdDev_0$).
\cvCPyFunc{CalcCovarMatrix}
Calculates covariance matrix of a set of vectors.
\cvdefC{
void cvCalcCovarMatrix(\par const CvArr** vects,\par int count,\par CvArr* covMat,\par CvArr* avg,\par int flags);}
\cvdefPy{CalcCovarMatrix(vects,covMat,avg,flags)-> None}
\begin{description}
\cvarg{vects}{The input vectors, all of which must have the same type and the same size. The vectors do not have to be 1D, they can be 2D (e.g., images) and so forth}
\ifC
\cvarg{count}{The number of input vectors}
\fi
\cvarg{covMat}{The output covariance matrix that should be floating-point and square}
\cvarg{avg}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
\cvarg{flags}{The operation flags, a combination of the following values
\begin{description}
\cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
\[
\texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...]^T \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]
\],
that is, the covariance matrix is
$\texttt{count} \times \texttt{count}$.
Such an unusual covariance matrix is used for fast PCA
of a set of very large vectors (see, for example, the EigenFaces technique
for face recognition). Eigenvalues of this "scrambled" matrix will
match the eigenvalues of the true covariance matrix and the "true"
eigenvectors can be easily calculated from the eigenvectors of the
"scrambled" covariance matrix.}
\cvarg{CV\_COVAR\_NORMAL}{The output covariance matrix is calculated as:
\[
\texttt{scale} * [ \texttt{vects} [0]- \texttt{avg} ,\texttt{vects} [1]- \texttt{avg} ,...] \cdot [\texttt{vects} [0]-\texttt{avg} ,\texttt{vects} [1]-\texttt{avg} ,...]^T
\],
that is, \texttt{covMat} will be a covariance matrix
with the same linear size as the total number of elements in each
input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
\texttt{CV\_COVAR\_NORMAL} must be specified}
\cvarg{CV\_COVAR\_USE\_AVG}{If the flag is specified, the function does not calculate \texttt{avg} from the input vectors, but, instead, uses the passed \texttt{avg} vector. This is useful if \texttt{avg} has been already calculated somehow, or if the covariance matrix is calculated by parts - in this case, \texttt{avg} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
\cvarg{CV\_COVAR\_SCALE}{If the flag is specified, the covariance matrix is scaled. In the "normal" mode \texttt{scale} is '1./count'; in the "scrambled" mode \texttt{scale} is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified) the covariance matrix is not scaled ('scale=1').}
\cvarg{CV\_COVAR\_ROWS}{Means that all the input vectors are stored as rows of a single matrix, \texttt{vects[0]}. \texttt{count} is ignored in this case, and \texttt{avg} should be a single-row vector of an appropriate size.}
\cvarg{CV\_COVAR\_COLS}{Means that all the input vectors are stored as columns of a single matrix, \texttt{vects[0]}. \texttt{count} is ignored in this case, and \texttt{avg} should be a single-column vector of an appropriate size.}
\end{description}}
\end{description}
The function calculates the covariance matrix
and, optionally, the mean vector of the set of input vectors. The function
can be used for PCA, for comparing vectors using Mahalanobis distance and so forth.
\cvCPyFunc{CartToPolar}
Calculates the magnitude and/or angle of 2d vectors.
\cvdefC{void cvCartToPolar(\par const CvArr* x,\par const CvArr* y,\par CvArr* magnitude,\par CvArr* angle=NULL,\par int angleInDegrees=0);}
\cvdefPy{CartToPolar(x,y,magnitude,angle=NULL,angleInDegrees=0)-> None}
\begin{description}
\cvarg{x}{The array of x-coordinates}
\cvarg{y}{The array of y-coordinates}
\cvarg{magnitude}{The destination array of magnitudes, may be set to NULL if it is not needed}
\cvarg{angle}{The destination array of angles, may be set to NULL if it is not needed. The angles are measured in radians $(0$ to $2 \pi )$ or in degrees (0 to 360 degrees).}
\cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
\end{description}
The function calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
\begin{lstlisting}
magnitude(I)=sqrt(x(I)^2^+y(I)^2^ ),
angle(I)=atan(y(I)/x(I) )
\end{lstlisting}
The angles are calculated with 0.1 degree accuracy. For the (0,0) point, the angle is set to 0.
\cvCPyFunc{Cbrt}
Calculates the cubic root
\cvdefC{float cvCbrt(float value);}
\cvdefPy{Cbrt(value)-> float}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
The function calculates the cubic root of the argument, and normally it is faster than \texttt{pow(value,1./3)}. In addition, negative arguments are handled properly. Special values ($\pm \infty $, NaN) are not handled.
\cvCPyFunc{ClearND}
Clears a specific array element.
\cvdefC{void cvClearND(CvArr* arr, int* idx);}
\cvdefPy{ClearND(arr,idx)-> None}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx}{Array of the element indices}
\end{description}
The function \cvCPyCross{ClearND} clears (sets to zero) a specific element of a dense array or deletes the element of a sparse array. If the sparse array element does not exists, the function does nothing.
\cvCPyFunc{CloneImage}
Makes a full copy of an image, including the header, data, and ROI.
\cvdefC{IplImage* cvCloneImage(const IplImage* image);}
\cvdefPy{CloneImage(image)-> copy}
\begin{description}
\cvarg{image}{The original image}
\end{description}
The returned \texttt{IplImage*} points to the image copy.
\cvCPyFunc{CloneMat}
Creates a full matrix copy.
\cvdefC{CvMat* cvCloneMat(const CvMat* mat);}
\cvdefPy{CloneMat(mat)-> copy}
\begin{description}
\cvarg{mat}{Matrix to be copied}
\end{description}
Creates a full copy of a matrix and returns a pointer to the copy.
\cvCPyFunc{CloneMatND}
Creates full copy of a multi-dimensional array and returns a pointer to the copy.
\cvdefC{CvMatND* cvCloneMatND(const CvMatND* mat);}
\cvdefPy{CloneMatND(mat)-> copy}
\begin{description}
\cvarg{mat}{Input array}
\end{description}
\ifC % {
\cvCPyFunc{CloneSparseMat}
Creates full copy of sparse array.
\cvdefC{CvSparseMat* cvCloneSparseMat(const CvSparseMat* mat);}
\cvdefPy{CloneSparseMat(mat) -> mat}
\begin{description}
\cvarg{mat}{Input array}
\end{description}
The function creates a copy of the input array and returns pointer to the copy.
\fi % }
\cvCPyFunc{Cmp}
Performs per-element comparison of two arrays.
\cvdefC{void cvCmp(const CvArr* src1, const CvArr* src2, CvArr* dst, int cmpOp);}
\cvdefPy{Cmp(src1,src2,dst,cmpOp)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array. Both source arrays must have a single channel.}
\cvarg{dst}{The destination array, must have 8u or 8s type}
\cvarg{cmpOp}{The flag specifying the relation between the elements to be checked
\begin{description}
\cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
\cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
\cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
\cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
\cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
\cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
\end{description}}
\end{description}
The function compares the corresponding elements of two arrays and fills the destination mask array:
\begin{lstlisting}
dst(I)=src1(I) op src2(I),
\end{lstlisting}
\texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the specific relation between the elements is true and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)
\cvCPyFunc{CmpS}
Performs per-element comparison of an array and a scalar.
\cvdefC{void cvCmpS(const CvArr* src, double value, CvArr* dst, int cmpOp);}
\cvdefPy{CmpS(src,value,dst,cmpOp)-> None}
\begin{description}
\cvarg{src}{The source array, must have a single channel}
\cvarg{value}{The scalar value to compare each array element with}
\cvarg{dst}{The destination array, must have 8u or 8s type}
\cvarg{cmpOp}{The flag specifying the relation between the elements to be checked
\begin{description}
\cvarg{CV\_CMP\_EQ}{src1(I) "equal to" value}
\cvarg{CV\_CMP\_GT}{src1(I) "greater than" value}
\cvarg{CV\_CMP\_GE}{src1(I) "greater or equal" value}
\cvarg{CV\_CMP\_LT}{src1(I) "less than" value}
\cvarg{CV\_CMP\_LE}{src1(I) "less or equal" value}
\cvarg{CV\_CMP\_NE}{src1(I) "not equal" value}
\end{description}}
\end{description}
The function compares the corresponding elements of an array and a scalar and fills the destination mask array:
\begin{lstlisting}
dst(I)=src(I) op scalar
\end{lstlisting}
where \texttt{op} is $=,\; >,\; \ge,\; <,\; \le\; or\; \ne$.
\texttt{dst(I)} is set to 0xff (all \texttt{1}-bits) if the specific relation between the elements is true and 0 otherwise. All the arrays must have the same size (or ROI size).
\ifPy % {
\cvCPyFunc{Convert}
Converts one array to another.
\cvdefPy{Convert(src,dst)-> None}
\begin{description}
\cvarg{src}{Source array}
\cvarg{dst}{Destination array}
\end{description}
The type of conversion is done with rounding and saturation, that is if the
result of scaling + conversion can not be represented exactly by a value
of the destination array element type, it is set to the nearest representable
value on the real axis.
All the channels of multi-channel arrays are processed independently.
\fi % }
\cvCPyFunc{ConvertScale}
Converts one array to another with optional linear transformation.
\cvdefC{void cvConvertScale(const CvArr* src, CvArr* dst, double scale=1, double shift=0);}
\cvdefPy{ConvertScale(src,dst,scale=1.0,shift=0.0)-> None}
\ifC
\begin{lstlisting}
#define cvCvtScale cvConvertScale
#define cvScale cvConvertScale
#define cvConvert(src, dst ) cvConvertScale((src), (dst), 1, 0 )
\end{lstlisting}
\fi
\begin{description}
\cvarg{src}{Source array}
\cvarg{dst}{Destination array}
\cvarg{scale}{Scale factor}
\cvarg{shift}{Value added to the scaled source array elements}
\end{description}
The function has several different purposes, and thus has several different names. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:
\[
\texttt{dst}(I) = \texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)
\]
All the channels of multi-channel arrays are processed independently.
The type of conversion is done with rounding and saturation, that is if the
result of scaling + conversion can not be represented exactly by a value
of the destination array element type, it is set to the nearest representable
value on the real axis.
In the case of \texttt{scale=1, shift=0} no prescaling is done. This is a specially
optimized case and it has the appropriate \cvCPyCross{Convert} name. If
source and destination array types have equal types, this is also a
special case that can be used to scale and shift a matrix or an image
and that is caled \cvCPyCross{Scale}.
\cvCPyFunc{ConvertScaleAbs}
Converts input array elements to another 8-bit unsigned integer with optional linear transformation.
\cvdefC{void cvConvertScaleAbs(const CvArr* src, CvArr* dst, double scale=1, double shift=0);}
\cvdefPy{ConvertScaleAbs(src,dst,scale=1.0,shift=0.0)-> None}
\begin{description}
\cvarg{src}{Source array}
\cvarg{dst}{Destination array (should have 8u depth)}
\cvarg{scale}{ScaleAbs factor}
\cvarg{shift}{Value added to the scaled source array elements}
\end{description}
The function is similar to \cvCPyCross{ConvertScale}, but it stores absolute values of the conversion results:
\[
\texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
\]
The function supports only destination arrays of 8u (8-bit unsigned integers) type; for other types the function can be emulated by a combination of \cvCPyCross{ConvertScale} and \cvCPyCross{Abs} functions.
\cvCPyFunc{CvtScaleAbs}
Converts input array elements to another 8-bit unsigned integer with optional linear transformation.
\cvdefC{void cvCvtScaleAbs(const CvArr* src, CvArr* dst, double scale=1, double shift=0);}
\cvdefPy{CvtScaleAbs(src,dst,scale=1.0,shift=0.0)-> None}
\begin{description}
\cvarg{src}{Source array}
\cvarg{dst}{Destination array (should have 8u depth)}
\cvarg{scale}{ScaleAbs factor}
\cvarg{shift}{Value added to the scaled source array elements}
\end{description}
The function is similar to \cvCPyCross{ConvertScale}, but it stores absolute values of the conversion results:
\[
\texttt{dst}(I) = |\texttt{scale} \texttt{src}(I) + (\texttt{shift}_0,\texttt{shift}_1,...)|
\]
The function supports only destination arrays of 8u (8-bit unsigned integers) type; for other types the function can be emulated by a combination of \cvCPyCross{ConvertScale} and \cvCPyCross{Abs} functions.
\cvCPyFunc{Copy}
Copies one array to another.
\cvdefC{void cvCopy(const CvArr* src, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{Copy(src,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function copies selected elements from an input array to an output array:
\[
\texttt{dst}(I)=\texttt{src}(I) \quad \text{if} \quad \texttt{mask}(I) \ne 0.
\]
If any of the passed arrays is of \texttt{IplImage} type, then its ROI
and COI fields are used. Both arrays must have the same type, the same
number of dimensions, and the same size. The function can also copy sparse
arrays (mask is not supported in this case).
\cvCPyFunc{CountNonZero}
Counts non-zero array elements.
\cvdefC{int cvCountNonZero(const CvArr* arr);}
\cvdefPy{CountNonZero(arr)-> int}
\begin{description}
\cvarg{arr}{The array must be a single-channel array or a multi-channel image with COI set}
\end{description}
The function returns the number of non-zero elements in arr:
\[ \sum_I (\texttt{arr}(I) \ne 0) \]
In the case of \texttt{IplImage} both ROI and COI are supported.
\cvCPyFunc{CreateData}
Allocates array data
\cvdefC{void cvCreateData(CvArr* arr);}
\cvdefPy{CreateData(arr) -> None}
\begin{description}
\cvarg{arr}{Array header}
\end{description}
The function allocates image, matrix or
multi-dimensional array data. Note that in the case of matrix types OpenCV
allocation functions are used and in the case of IplImage they are used
unless \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} was called. In the
latter case IPL functions are used to allocate the data.
\cvCPyFunc{CreateImage}
Creates an image header and allocates the image data.
\cvdefC{IplImage* cvCreateImage(CvSize size, int depth, int channels);}
\cvdefPy{CreateImage(size, depth, channels)->image}
\begin{description}
\cvarg{size}{Image width and height}
\cvarg{depth}{Bit depth of image elements. See \cross{IplImage} for valid depths.}
\cvarg{channels}{Number of channels per pixel. See \cross{IplImage} for details. This function only creates images with interleaved channels.}
\end{description}
\ifC
This call is a shortened form of
\begin{lstlisting}
header = cvCreateImageHeader(size, depth, channels);
cvCreateData(header);
\end{lstlisting}
\fi
\cvCPyFunc{CreateImageHeader}
Creates an image header but does not allocate the image data.
\cvdefC{IplImage* cvCreateImageHeader(CvSize size, int depth, int channels);}
\cvdefPy{CreateImageHeader(size, depth, channels) -> image}
\begin{description}
\cvarg{size}{Image width and height}
\cvarg{depth}{Image depth (see \cvCPyCross{CreateImage})}
\cvarg{channels}{Number of channels (see \cvCPyCross{CreateImage})}
\end{description}
\ifC
This call is an analogue of
\begin{lstlisting}
hdr=iplCreateImageHeader(channels, 0, depth,
channels == 1 ? "GRAY" : "RGB",
channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
channels == 4 ? "BGRA" : "",
IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
size.width, size.height,
0,0,0,0);
\end{lstlisting}
but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
\fi
\cvCPyFunc{CreateMat}\label{cvCreateMat}
Creates a matrix header and allocates the matrix data.
\cvdefC{CvMat* cvCreateMat(\par int rows,\par int cols,\par int type);}
\cvdefPy{CreateMat(rows, cols, type) -> mat}
\begin{description}
\cvarg{rows}{Number of rows in the matrix}
\cvarg{cols}{Number of columns in the matrix}
\cvarg{type}{The type of the matrix elements in the form \texttt{CV\_<bit depth><S|U|F>C<number of channels>}, where S=signed, U=unsigned, F=float. For example, CV\_8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV\_32SC2 means the elements are 32-bit signed and there are 2 channels.}
\end{description}
\ifC
This is the concise form for:
\begin{lstlisting}
CvMat* mat = cvCreateMatHeader(rows, cols, type);
cvCreateData(mat);
\end{lstlisting}
\fi
\cvCPyFunc{CreateMatHeader}
Creates a matrix header but does not allocate the matrix data.
\cvdefC{CvMat* cvCreateMatHeader(\par int rows,\par int cols,\par int type);}
\cvdefPy{CreateMatHeader(rows, cols, type) -> mat}
\begin{description}
\cvarg{rows}{Number of rows in the matrix}
\cvarg{cols}{Number of columns in the matrix}
\cvarg{type}{Type of the matrix elements, see \cvCPyCross{CreateMat}}
\end{description}
The function allocates a new matrix header and returns a pointer to it. The matrix data can then be allocated using \cvCPyCross{CreateData} or set explicitly to user-allocated data via \cvCPyCross{SetData}.
\cvCPyFunc{CreateMatND}
Creates the header and allocates the data for a multi-dimensional dense array.
\cvdefC{CvMatND* cvCreateMatND(\par int dims,\par const int* sizes,\par int type);}
\cvdefPy{CreateMatND(dims, type) -> None}
\begin{description}
\ifPy
\cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
\else
\cvarg{dims}{Number of array dimensions. This must not exceed CV\_MAX\_DIM (32 by default, but can be changed at build time).}
\cvarg{sizes}{Array of dimension sizes.}
\fi
\cvarg{type}{Type of array elements, see \cvCPyCross{CreateMat}.}
\end{description}
This is a short form for:
\ifC
\begin{lstlisting}
CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type);
cvCreateData(mat);
\end{lstlisting}
\fi
\cvCPyFunc{CreateMatNDHeader}
Creates a new matrix header but does not allocate the matrix data.
\cvdefC{CvMatND* cvCreateMatNDHeader(\par int dims,\par const int* sizes,\par int type);}
\cvdefPy{CreateMatNDHeader(dims, type) -> None}
\begin{description}
\ifPy
\cvarg{dims}{List or tuple of array dimensions, up to 32 in length.}
\else
\cvarg{dims}{Number of array dimensions}
\cvarg{sizes}{Array of dimension sizes}
\fi
\cvarg{type}{Type of array elements, see \cvCPyCross{CreateMat}}
\end{description}
The function allocates a header for a multi-dimensional dense array. The array data can further be allocated using \cvCPyCross{CreateData} or set explicitly to user-allocated data via \cvCPyCross{SetData}.
\ifC % {
\cvCPyFunc{CreateSparseMat}
Creates sparse array.
\cvdefC{CvSparseMat* cvCreateSparseMat(int dims, const int* sizes, int type);}
\cvdefPy{CreateSparseMat(dims, type) -> cvmat}
\begin{description}
\ifC
\cvarg{dims}{Number of array dimensions. In contrast to the dense matrix, the number of dimensions is practically unlimited (up to $2^{16}$).}
\cvarg{sizes}{Array of dimension sizes}
\else
\cvarg{dims}{List or tuple of array dimensions.}
\fi
\cvarg{type}{Type of array elements. The same as for CvMat}
\end{description}
The function allocates a multi-dimensional sparse array. Initially the array contain no elements, that is \cvCPyCross{Get} or \cvCPyCross{GetReal} returns zero for every index.
\fi % }
\cvCPyFunc{CrossProduct}
Calculates the cross product of two 3D vectors.
\cvdefC{void cvCrossProduct(const CvArr* src1, const CvArr* src2, CvArr* dst);}
\cvdefPy{CrossProduct(src1,src2,dst)-> None}
\begin{description}
\cvarg{src1}{The first source vector}
\cvarg{src2}{The second source vector}
\cvarg{dst}{The destination vector}
\end{description}
The function calculates the cross product of two 3D vectors:
\[ \texttt{dst} = \texttt{src1} \times \texttt{src2} \]
or:
\[
\begin{array}{l}
\texttt{dst}_1 = \texttt{src1}_2 \texttt{src2}_3 - \texttt{src1}_3 \texttt{src2}_2\\
\texttt{dst}_2 = \texttt{src1}_3 \texttt{src2}_1 - \texttt{src1}_1 \texttt{src2}_3\\
\texttt{dst}_3 = \texttt{src1}_1 \texttt{src2}_2 - \texttt{src1}_2 \texttt{src2}_1
\end{array}
\]
\subsection{CvtPixToPlane}
Synonym for \cross{Split}.
\cvCPyFunc{DCT}
Performs a forward or inverse Discrete Cosine transform of a 1D or 2D floating-point array.
\cvdefC{void cvDCT(const CvArr* src, CvArr* dst, int flags);}
\cvdefPy{DCT(src,dst,flags)-> None}
\begin{description}
\cvarg{src}{Source array, real 1D or 2D array}
\cvarg{dst}{Destination array of the same size and same type as the source}
\cvarg{flags}{Transformation flags, a combination of the following values
\begin{description}
\cvarg{CV\_DXT\_FORWARD}{do a forward 1D or 2D transform.}
\cvarg{CV\_DXT\_INVERSE}{do an inverse 1D or 2D transform.}
\cvarg{CV\_DXT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
\end{description}}
\end{description}
The function performs a forward or inverse transform of a 1D or 2D floating-point array:
Forward Cosine transform of 1D vector of $N$ elements:
\[Y = C^{(N)} \cdot X\]
where
\[C^{(N)}_{jk}=\sqrt{\alpha_j/N}\cos\left(\frac{\pi(2k+1)j}{2N}\right)\]
and $\alpha_0=1$, $\alpha_j=2$ for $j > 0$.
Inverse Cosine transform of 1D vector of N elements:
\[X = \left(C^{(N)}\right)^{-1} \cdot Y = \left(C^{(N)}\right)^T \cdot Y\]
(since $C^{(N)}$ is orthogonal matrix, $C^{(N)} \cdot \left(C^{(N)}\right)^T = I$)
Forward Cosine transform of 2D $M \times N$ matrix:
\[Y = C^{(N)} \cdot X \cdot \left(C^{(N)}\right)^T\]
Inverse Cosine transform of 2D vector of $M \times N$ elements:
\[X = \left(C^{(N)}\right)^T \cdot X \cdot C^{(N)}\]
\cvCPyFunc{DFT}
Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
\cvdefC{void cvDFT(const CvArr* src, CvArr* dst, int flags, int nonzeroRows=0);}
\cvdefPy{DFT(src,dst,flags,nonzeroRows=0)-> None}
\begin{description}
\cvarg{src}{Source array, real or complex}
\cvarg{dst}{Destination array of the same size and same type as the source}
\cvarg{flags}{Transformation flags, a combination of the following values
\begin{description}
\cvarg{CV\_DXT\_FORWARD}{do a forward 1D or 2D transform. The result is not scaled.}
\cvarg{CV\_DXT\_INVERSE}{do an inverse 1D or 2D transform. The result is not scaled. \texttt{CV\_DXT\_FORWARD} and \texttt{CV\_DXT\_INVERSE} are mutually exclusive, of course.}
\cvarg{CV\_DXT\_SCALE}{scale the result: divide it by the number of array elements. Usually, it is combined with \texttt{CV\_DXT\_INVERSE}, and one may use a shortcut \texttt{CV\_DXT\_INV\_SCALE}.}
\cvarg{CV\_DXT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows the user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
\cvarg{CV\_DXT\_INVERSE\_SCALE}{same as \texttt{CV\_DXT\_INVERSE + CV\_DXT\_SCALE}}
\end{description}}
\cvarg{nonzeroRows}{Number of nonzero rows in the source array
(in the case of a forward 2d transform), or a number of rows of interest in
the destination array (in the case of an inverse 2d transform). If the value
is negative, zero, or greater than the total number of rows, it is
ignored. The parameter can be used to speed up 2d convolution/correlation
when computing via DFT. See the example below.}
\end{description}
The function performs a forward or inverse transform of a 1D or 2D floating-point array:
Forward Fourier transform of 1D vector of N elements:
\[y = F^{(N)} \cdot x, where F^{(N)}_{jk}=exp(-i \cdot 2\pi \cdot j \cdot k/N)\],
\[i=sqrt(-1)\]
Inverse Fourier transform of 1D vector of N elements:
\[x'= (F^{(N)})^{-1} \cdot y = conj(F^(N)) \cdot y
x = (1/N) \cdot x\]
Forward Fourier transform of 2D vector of M $\times$ N elements:
\[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
Inverse Fourier transform of 2D vector of M $\times$ N elements:
\[X'= conj(F^{(M)}) \cdot Y \cdot conj(F^{(N)})
X = (1/(M \cdot N)) \cdot X'\]
In the case of real (single-channel) data, the packed format, borrowed from IPL, is used to represent the result of a forward Fourier transform or input for an inverse Fourier transform:
\[\begin{bmatrix}
Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\
Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\
Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\
\hdotsfor{9} \\
Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\
Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\
Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2}
\end{bmatrix}
\]
Note: the last column is present if \texttt{N} is even, the last row is present if \texttt{M} is even.
In the case of 1D real transform the result looks like the first row of the above matrix.
Here is the example of how to compute 2D convolution using DFT.
\ifC
\begin{lstlisting}
CvMat* A = cvCreateMat(M1, N1, CVg32F);
CvMat* B = cvCreateMat(M2, N2, A->type);
// it is also possible to have only abs(M2-M1)+1 times abs(N2-N1)+1
// part of the full convolution result
CvMat* conv = cvCreateMat(A->rows + B->rows - 1, A->cols + B->cols - 1,
A->type);
// initialize A and B
...
int dftgM = cvGetOptimalDFTSize(A->rows + B->rows - 1);
int dftgN = cvGetOptimalDFTSize(A->cols + B->cols - 1);
CvMat* dftgA = cvCreateMat(dft\_M, dft\_N, A->type);
CvMat* dftgB = cvCreateMat(dft\_M, dft\_N, B->type);
CvMat tmp;
// copy A to dftgA and pad dft\_A with zeros
cvGetSubRect(dftgA, &tmp, cvRect(0,0,A->cols,A->rows));
cvCopy(A, &tmp);
cvGetSubRect(dftgA, &tmp, cvRect(A->cols,0,dft\_A->cols - A->cols,A->rows));
cvZero(&tmp);
// no need to pad bottom part of dftgA with zeros because of
// use nonzerogrows parameter in cvDFT() call below
cvDFT(dftgA, dft\_A, CV\_DXT\_FORWARD, A->rows);
// repeat the same with the second array
cvGetSubRect(dftgB, &tmp, cvRect(0,0,B->cols,B->rows));
cvCopy(B, &tmp);
cvGetSubRect(dftgB, &tmp, cvRect(B->cols,0,dft\_B->cols - B->cols,B->rows));
cvZero(&tmp);
// no need to pad bottom part of dftgB with zeros because of
// use nonzerogrows parameter in cvDFT() call below
cvDFT(dftgB, dft\_B, CV\_DXT\_FORWARD, B->rows);
cvMulSpectrums(dftgA, dft\_B, dft\_A, 0 /* or CV\_DXT\_MUL\_CONJ to get
correlation rather than convolution */);
cvDFT(dftgA, dft\_A, CV\_DXT\_INV\_SCALE, conv->rows); // calculate only
// the top part
cvGetSubRect(dftgA, &tmp, cvRect(0,0,conv->cols,conv->rows));
cvCopy(&tmp, conv);
\end{lstlisting}
\fi
\ifC
\cvCPyFunc{DecRefData}
Decrements an array data reference counter.
\cvdefC{void cvDecRefData(CvArr* arr);}
\begin{description}
\cvarg{arr}{Pointer to an array header}
\end{description}
The function decrements the data reference counter in a \cross{CvMat} or
\cross{CvMatND} if the reference counter pointer
is not NULL. If the counter reaches zero, the data is deallocated. In the
current implementation the reference counter is not NULL only if the data
was allocated using the \cvCPyCross{CreateData} function. The counter will be NULL in other cases such as:
external data was assigned to the header using \cvCPyCross{SetData}, the matrix
header is part of a larger matrix or image, or the header was converted from an image or n-dimensional matrix header.
\fi
\cvCPyFunc{Det}
Returns the determinant of a matrix.
\cvdefC{double cvDet(const CvArr* mat);}
\cvdefPy{Det(mat)-> double}
\begin{description}
\cvarg{mat}{The source matrix}
\end{description}
The function returns the determinant of the square matrix \texttt{mat}. The direct method is used for small matrices and Gaussian elimination is used for larger matrices. For symmetric positive-determined matrices, it is also possible to run
\cvCPyCross{SVD}
with $U = V = 0$ and then calculate the determinant as a product of the diagonal elements of $W$.
\cvCPyFunc{Div}
Performs per-element division of two arrays.
\cvdefC{void cvDiv(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1);}
\cvdefPy{Div(src1,src2,dst,scale)-> None}
\begin{description}
\cvarg{src1}{The first source array. If the pointer is NULL, the array is assumed to be all 1's.}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{scale}{Optional scale factor}
\end{description}
The function divides one array by another:
\[
\texttt{dst}(I)=\fork
{\texttt{scale} \cdot \texttt{src1}(I)/\texttt{src2}(I)}{if \texttt{src1} is not \texttt{NULL}}
{\texttt{scale}/\texttt{src2}(I)}{otherwise}
\]
All the arrays must have the same type and the same size (or ROI size).
\cvCPyFunc{DotProduct}
Calculates the dot product of two arrays in Euclidian metrics.
\cvdefC{double cvDotProduct(const CvArr* src1, const CvArr* src2);}
\cvdefPy{DotProduct(src1,src2)-> double}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\end{description}
The function calculates and returns the Euclidean dot product of two arrays.
\[
src1 \bullet src2 = \sum_I (\texttt{src1}(I) \texttt{src2}(I))
\]
In the case of multiple channel arrays, the results for all channels are accumulated. In particular, \texttt{cvDotProduct(a,a)} where \texttt{a} is a complex vector, will return $||\texttt{a}||^2$.
The function can process multi-dimensional arrays, row by row, layer by layer, and so on.
\cvCPyFunc{EigenVV}
Computes eigenvalues and eigenvectors of a symmetric matrix.
\cvdefC{
void cvEigenVV(\par CvArr* mat,\par CvArr* evects,\par CvArr* evals,\par double eps=0,
\par int lowindex = -1, \par int highindex = -1);}
\cvdefPy{EigenVV(mat,evects,evals,eps,lowindex,highindex)-> None}
\begin{description}
\cvarg{mat}{The input symmetric square matrix, modified during the processing}
\cvarg{evects}{The output matrix of eigenvectors, stored as subsequent rows}
\cvarg{evals}{The output vector of eigenvalues, stored in the descending order (order of eigenvalues and eigenvectors is syncronized, of course)}
\cvarg{eps}{Accuracy of diagonalization. Typically, \texttt{DBL\_EPSILON} (about $ 10^{-15} $) works well.
THIS PARAMETER IS CURRENTLY IGNORED.}
\cvarg{lowindex}{Optional index of largest eigenvalue/-vector to calculate.
(See below.)}
\cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
(See below.)}
\end{description}
The function computes the eigenvalues and eigenvectors of matrix \texttt{A}:
\begin{lstlisting}
mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)
\end{lstlisting}
If either low- or highindex is supplied the other is required, too.
Indexing is 0-based. Example: To calculate the largest eigenvector/-value set
\texttt{lowindex=highindex=0}. To calculate all the eigenvalues, leave \texttt{lowindex=highindex=-1}.
For legacy reasons this function always returns a square matrix the same size
as the source matrix with eigenvectors and a vector the length of the source
matrix with eigenvalues. The selected eigenvectors/-values are always in the
first highindex - lowindex + 1 rows.
The contents of matrix \texttt{A} is destroyed by the function.
Currently the function is slower than \cvCPyCross{SVD} yet less accurate,
so if \texttt{A} is known to be positively-defined (for example, it
is a covariance matrix)it is recommended to use \cvCPyCross{SVD} to find
eigenvalues and eigenvectors of \texttt{A}, especially if eigenvectors
are not required.
\cvCPyFunc{Exp}
Calculates the exponent of every array element.
\cvdefC{void cvExp(const CvArr* src, CvArr* dst);}
\cvdefPy{Exp(src,dst)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
\end{description}
The function calculates the exponent of every element of the input array:
\[
\texttt{dst} [I] = e^{\texttt{src}(I)}
\]
The maximum relative error is about $7 \times 10^{-6}$. Currently, the function converts denormalized values to zeros on output.
\cvCPyFunc{FastArctan}
Calculates the angle of a 2D vector.
\cvdefC{float cvFastArctan(float y, float x);}
\cvdefPy{FastArctan(y,x)-> float}
\begin{description}
\cvarg{x}{x-coordinate of 2D vector}
\cvarg{y}{y-coordinate of 2D vector}
\end{description}
The function calculates the full-range angle of an input 2D vector. The angle is
measured in degrees and varies from 0 degrees to 360 degrees. The accuracy is about 0.1 degrees.
\cvCPyFunc{Flip}
Flip a 2D array around vertical, horizontal or both axes.
\cvdefC{void cvFlip(const CvArr* src, CvArr* dst=NULL, int flipMode=0);}
\cvdefPy{Flip(src,dst=NULL,flipMode=0)-> None}
\begin{description}
\cvarg{src}{Source array}
\cvarg{dst}{Destination array.
If $\texttt{dst} = \texttt{NULL}$ the flipping is done in place.}
\cvarg{flipMode}{Specifies how to flip the array:
0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas:}
\end{description}
The function flips the array in one of three different ways (row and column indices are 0-based):
\[
dst(i,j) = \forkthree
{\texttt{src}(rows(\texttt{src})-i-1,j)}{if $\texttt{flipMode} = 0$}
{\texttt{src}(i,cols(\texttt{src})-j-1)}{if $\texttt{flipMode} > 0$}
{\texttt{src}(rows(\texttt{src})-i-1,cols(\texttt{src})-j-1)}{if $\texttt{flipMode} < 0$}
\]
The example scenarios of function use are:
\begin{itemize}
\item vertical flipping of the image (flipMode = 0) to switch between top-left and bottom-left image origin, which is a typical operation in video processing under Win32 systems.
\item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry (flipMode $>$ 0)
\item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry (flipMode $<$ 0)
\item reversing the order of 1d point arrays (flipMode > 0)
\end{itemize}
\ifPy
\cvCPyFunc{fromarray}
Create a CvMat from an object that supports the array interface.
\cvdefPy{fromarray(object, allowND = False) -> CvMat}
\begin{description}
\cvarg{object}{Any object that supports the array interface}
\cvarg{allowND}{If true, will return a CvMatND}
\end{description}
If the object supports the
\href{http://docs.scipy.org/doc/numpy/reference/arrays.interface.html}{array interface},
return a \cross{CvMat} (\texttt{allowND = False}) or \cross{CvMatND} (\texttt{allowND = True}).
If \texttt{allowND = False}, then the object's array must be either 2D or 3D. If it is 2D, then the returned CvMat has a single channel. If it is 3D, then the returned CvMat will have N channels, where N is the last dimension of the array. In this case, N cannot be greater than OpenCV's channel limit, \texttt{CV\_CN\_MAX}.
If \texttt{allowND = True}, then \texttt{fromarray} returns a single-channel \cross{CvMatND} with the same shape as the original array.
For example, \href{http://numpy.scipy.org/}{NumPy} arrays support the array interface, so can be converted to OpenCV objects:
\begin{lstlisting}
>>> import cv, numpy
>>> a = numpy.ones((480, 640))
>>> mat = cv.fromarray(a)
>>> print cv.GetDims(mat), cv.CV_MAT_CN(cv.GetElemType(mat))
(480, 640) 1
>>> a = numpy.ones((480, 640, 3))
>>> mat = cv.fromarray(a)
>>> print cv.GetDims(mat), cv.CV_MAT_CN(cv.GetElemType(mat))
(480, 640) 3
>>> a = numpy.ones((480, 640, 3))
>>> mat = cv.fromarray(a, allowND = True)
>>> print cv.GetDims(mat), cv.CV_MAT_CN(cv.GetElemType(mat))
(480, 640, 3) 1
\end{lstlisting}
\fi
\cvCPyFunc{GEMM}
Performs generalized matrix multiplication.
\cvdefC{void cvGEMM(\par const CvArr* src1, \par const CvArr* src2, double alpha,
\par const CvArr* src3, \par double beta, \par CvArr* dst, \par int tABC=0);\newline
\#define cvMatMulAdd(src1, src2, src3, dst ) cvGEMM(src1, src2, 1, src3, 1, dst, 0 )\par
\#define cvMatMul(src1, src2, dst ) cvMatMulAdd(src1, src2, 0, dst )}
\cvdefPy{GEMM(src1,src2,alphs,src3,beta,dst,tABC=0)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{src3}{The third source array (shift). Can be NULL, if there is no shift.}
\cvarg{dst}{The destination array}
\cvarg{tABC}{The operation flags that can be 0 or a combination of the following values
\begin{description}
\cvarg{CV\_GEMM\_A\_T}{transpose src1}
\cvarg{CV\_GEMM\_B\_T}{transpose src2}
\cvarg{CV\_GEMM\_C\_T}{transpose src3}
\end{description}
For example, \texttt{CV\_GEMM\_A\_T+CV\_GEMM\_C\_T} corresponds to
\[
\texttt{alpha} \, \texttt{src1} ^T \, \texttt{src2} + \texttt{beta} \, \texttt{src3} ^T
\]}
\end{description}
The function performs generalized matrix multiplication:
\[
\texttt{dst} = \texttt{alpha} \, op(\texttt{src1}) \, op(\texttt{src2}) + \texttt{beta} \, op(\texttt{src3}) \quad \text{where $op(X)$ is $X$ or $X^T$}
\]
All the matrices should have the same data type and coordinated sizes. Real or complex floating-point matrices are supported.
\ifC % {
\cvCPyFunc{Get?D}
Return a specific array element.
\cvdefC{
CvScalar cvGet1D(const CvArr* arr, int idx0);
CvScalar cvGet2D(const CvArr* arr, int idx0, int idx1);
CvScalar cvGet3D(const CvArr* arr, int idx0, int idx1, int idx2);
CvScalar cvGetND(const CvArr* arr, int* idx);
}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{The first zero-based component of the element index}
\cvarg{idx1}{The second zero-based component of the element index}
\cvarg{idx2}{The third zero-based component of the element index}
\cvarg{idx}{Array of the element indices}
\end{description}
The functions return a specific array element. In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
\else % }{
\cvCPyFunc{Get1D}
Return a specific array element.
\cvdefPy{Get1D(arr, idx) -> scalar}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx}{Zero-based element index}
\end{description}
Return a specific array element. Array must have dimension 3.
\cvCPyFunc{Get2D}
Return a specific array element.
\cvdefPy{ Get2D(arr, idx0, idx1) -> scalar }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{Zero-based element row index}
\cvarg{idx1}{Zero-based element column index}
\end{description}
Return a specific array element. Array must have dimension 2.
\cvCPyFunc{Get3D}
Return a specific array element.
\cvdefPy{ Get3D(arr, idx0, idx1, idx2) -> scalar }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{Zero-based element index}
\cvarg{idx1}{Zero-based element index}
\cvarg{idx2}{Zero-based element index}
\end{description}
Return a specific array element. Array must have dimension 3.
\cvCPyFunc{GetND}
Return a specific array element.
\cvdefPy{ GetND(arr, indices) -> scalar }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{indices}{List of zero-based element indices}
\end{description}
Return a specific array element. The length of array indices must be the same as the dimension of the array.
\fi % }
\ifC % {
\cvCPyFunc{GetCol(s)}
Returns array column or column span.
\cvdefC{CvMat* cvGetCol(const CvArr* arr, CvMat* submat, int col);}
\cvdefPy{GetCol(arr,row)-> submat}
\cvdefC{CvMat* cvGetCols(const CvArr* arr, CvMat* submat, int startCol, int endCol);}
\cvdefPy{GetCols(arr,startCol,endCol)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{submat}{Pointer to the resulting sub-array header}
\cvarg{col}{Zero-based index of the selected column}
\cvarg{startCol}{Zero-based index of the starting column (inclusive) of the span}
\cvarg{endCol}{Zero-based index of the ending column (exclusive) of the span}
\end{description}
The functions \texttt{GetCol} and \texttt{GetCols} return the header, corresponding to a specified column span of the input array. \texttt{GetCol} is a shortcut for \cvCPyCross{GetCols}:
\begin{lstlisting}
cvGetCol(arr, submat, col); // ~ cvGetCols(arr, submat, col, col + 1);
\end{lstlisting}
\else % }{
\cvCPyFunc{GetCol}
Returns array column.
\cvdefPy{GetCol(arr,col)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{col}{Zero-based index of the selected column}
\cvarg{submat}{resulting single-column array}
\end{description}
The function \texttt{GetCol} returns a single column from the input array.
\cvCPyFunc{GetCols}
Returns array column span.
\cvdefPy{GetCols(arr,startCol,endCol)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{startCol}{Zero-based index of the starting column (inclusive) of the span}
\cvarg{endCol}{Zero-based index of the ending column (exclusive) of the span}
\cvarg{submat}{resulting multi-column array}
\end{description}
The function \texttt{GetCols} returns a column span from the input array.
\fi % }
\cvCPyFunc{GetDiag}
Returns one of array diagonals.
\cvdefC{CvMat* cvGetDiag(const CvArr* arr, CvMat* submat, int diag=0);}
\cvdefPy{GetDiag(arr,diag=0)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{submat}{Pointer to the resulting sub-array header}
\cvarg{diag}{Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above the main , 1 corresponds to the diagonal below the main, and so forth.}
\end{description}
The function returns the header, corresponding to a specified diagonal of the input array.
\ifC
\subsection{cvGetDims, cvGetDimSize}\label{cvGetDims}
Return number of array dimensions and their sizes or the size of a particular dimension.
\cvdefC{int cvGetDims(const CvArr* arr, int* sizes=NULL);}
\cvdefC{int cvGetDimSize(const CvArr* arr, int index);}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{sizes}{Optional output vector of the array dimension sizes. For
2d arrays the number of rows (height) goes first, number of columns
(width) next.}
\cvarg{index}{Zero-based dimension index (for matrices 0 means number
of rows, 1 means number of columns; for images 0 means height, 1 means
width)}
\end{description}
The function \texttt{cvGetDims} returns the array dimensionality and the
array of dimension sizes. In the case of \texttt{IplImage} or \cross{CvMat} it always
returns 2 regardless of number of image/matrix rows. The function
\texttt{cvGetDimSize} returns the particular dimension size (number of
elements per that dimension). For example, the following code calculates
total number of array elements in two ways:
\begin{lstlisting}
// via cvGetDims()
int sizes[CV_MAX_DIM];
int i, total = 1;
int dims = cvGetDims(arr, size);
for(i = 0; i < dims; i++ )
total *= sizes[i];
// via cvGetDims() and cvGetDimSize()
int i, total = 1;
int dims = cvGetDims(arr);
for(i = 0; i < dims; i++ )
total *= cvGetDimsSize(arr, i);
\end{lstlisting}
\fi
\ifPy
\cvCPyFunc{GetDims}
Returns list of array dimensions
\cvdefPy{GetDims(arr)-> list}
\begin{description}
\cvarg{arr}{Input array}
\end{description}
The function returns a list of array dimensions.
In the case of \texttt{IplImage} or \cross{CvMat} it always
returns a list of length 2.
\fi
\cvCPyFunc{GetElemType}
Returns type of array elements.
\cvdefC{int cvGetElemType(const CvArr* arr);}
\cvdefPy{GetElemType(arr)-> int}
\begin{description}
\cvarg{arr}{Input array}
\end{description}
The function returns type of the array elements
as described in \cvCPyCross{CreateMat} discussion: \texttt{CV\_8UC1} ... \texttt{CV\_64FC4}.
\cvCPyFunc{GetImage}
Returns image header for arbitrary array.
\cvdefC{IplImage* cvGetImage(const CvArr* arr, IplImage* imageHeader);}
\cvdefPy{GetImage(arr) -> iplimage}
\begin{description}
\cvarg{arr}{Input array}
\ifC
\cvarg{imageHeader}{Pointer to \texttt{IplImage} structure used as a temporary buffer}
\fi
\end{description}
The function returns the image header for the input array
that can be a matrix - \cross{CvMat}, or an image - \texttt{IplImage*}. In
the case of an image the function simply returns the input pointer. In the
case of \cross{CvMat} it initializes an \texttt{imageHeader} structure
with the parameters of the input matrix. Note that if we transform
\texttt{IplImage} to \cross{CvMat} and then transform CvMat back to
IplImage, we can get different headers if the ROI is set, and thus some
IPL functions that calculate image stride from its width and align may
fail on the resultant image.
\cvCPyFunc{GetImageCOI}
Returns the index of the channel of interest.
\cvdefC{int cvGetImageCOI(const IplImage* image);}
\cvdefPy{GetImageCOI(image)-> channel}
\begin{description}
\cvarg{image}{A pointer to the image header}
\end{description}
Returns the channel of interest of in an IplImage. Returned values correspond to the \texttt{coi} in \cvCPyCross{SetImageCOI}.
\cvCPyFunc{GetImageROI}
Returns the image ROI.
\cvdefC{CvRect cvGetImageROI(const IplImage* image);}
\cvdefPy{GetImageROI(image)-> CvRect}
\begin{description}
\cvarg{image}{A pointer to the image header}
\end{description}
If there is no ROI set, \texttt{cvRect(0,0,image->width,image->height)} is returned.
\cvCPyFunc{GetMat}
Returns matrix header for arbitrary array.
\cvdefC{CvMat* cvGetMat(const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0);}
\cvdefPy{GetMat(arr, allowND=0) -> cvmat }
\begin{description}
\cvarg{arr}{Input array}
\ifC
\cvarg{header}{Pointer to \cross{CvMat} structure used as a temporary buffer}
\cvarg{coi}{Optional output parameter for storing COI}
\fi
\cvarg{allowND}{If non-zero, the function accepts multi-dimensional dense arrays (CvMatND*) and returns 2D (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The array must be continuous.}
\end{description}
The function returns a matrix header for the input array that can be a matrix -
\cross{CvMat}, an image - \texttt{IplImage} or a multi-dimensional dense array - \cross{CvMatND} (latter case is allowed only if \texttt{allowND != 0}) . In the case of matrix the function simply returns the input pointer. In the case of \texttt{IplImage*} or \cross{CvMatND} it initializes the \texttt{header} structure with parameters of the current image ROI and returns the pointer to this temporary structure. Because COI is not supported by \cross{CvMat}, it is returned separately.
The function provides an easy way to handle both types of arrays - \texttt{IplImage} and \cross{CvMat} - using the same code. Reverse transform from \cross{CvMat} to \texttt{IplImage} can be done using the \cvCPyCross{GetImage} function.
Input array must have underlying data allocated or attached, otherwise the function fails.
If the input array is \texttt{IplImage} with planar data layout and COI set, the function returns the pointer to the selected plane and COI = 0. It enables per-plane processing of multi-channel images with planar data layout using OpenCV functions.
\ifC
\cvCPyFunc{GetNextSparseNode}
Returns the next sparse matrix element
\cvdefC{CvSparseNode* cvGetNextSparseNode(CvSparseMatIterator* matIterator);}
\begin{description}
\cvarg{matIterator}{Sparse array iterator}
\end{description}
The function moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in the hash table. The sample below demonstrates how to iterate through the sparse matrix:
Using \cvCPyCross{InitSparseMatIterator} and \cvCPyCross{GetNextSparseNode} to calculate sum of floating-point sparse array.
\begin{lstlisting}
double sum;
int i, dims = cvGetDims(array);
CvSparseMatIterator mat_iterator;
CvSparseNode* node = cvInitSparseMatIterator(array, &mat_iterator);
for(; node != 0; node = cvGetNextSparseNode(&mat_iterator ))
{
/* get pointer to the element indices */
int* idx = CV_NODE_IDX(array, node);
/* get value of the element (assume that the type is CV_32FC1) */
float val = *(float*)CV_NODE_VAL(array, node);
printf("(");
for(i = 0; i < dims; i++ )
printf("%4d%s", idx[i], i < dims - 1 "," : "): ");
printf("%g\n", val);
sum += val;
}
printf("\nTotal sum = %g\n", sum);
\end{lstlisting}
\fi
\cvCPyFunc{GetOptimalDFTSize}
Returns optimal DFT size for a given vector size.
\cvdefC{int cvGetOptimalDFTSize(int size0);}
\cvdefPy{GetOptimalDFTSize(size0)-> int}
\begin{description}
\cvarg{size0}{Vector size}
\end{description}
The function returns the minimum number
\texttt{N} that is greater than or equal to \texttt{size0}, such that the DFT
of a vector of size \texttt{N} can be computed fast. In the current
implementation $N=2^p \times 3^q \times 5^r$, for some $p$, $q$, $r$.
The function returns a negative number if \texttt{size0} is too large
(very close to \texttt{INT\_MAX})
\ifC
\cvCPyFunc{GetRawData}
Retrieves low-level information about the array.
\cvdefC{void cvGetRawData(const CvArr* arr, uchar** data,
int* step=NULL, CvSize* roiSize=NULL);}
\begin{description}
\cvarg{arr}{Array header}
\cvarg{data}{Output pointer to the whole image origin or ROI origin if ROI is set}
\cvarg{step}{Output full row length in bytes}
\cvarg{roiSize}{Output ROI size}
\end{description}
The function fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to \texttt{NULL}. If the array is \texttt{IplImage} with ROI set, the parameters of ROI are returned.
The following example shows how to get access to array elements. GetRawData calculates the absolute value of the elements in a single-channel, floating-point array.
\begin{lstlisting}
float* data;
int step;
CvSize size;
int x, y;
cvGetRawData(array, (uchar**)&data, &step, &size);
step /= sizeof(data[0]);
for(y = 0; y < size.height; y++, data += step )
for(x = 0; x < size.width; x++ )
data[x] = (float)fabs(data[x]);
\end{lstlisting}
\cvCPyFunc{GetReal?D}
Return a specific element of single-channel array.
\cvdefC{
double cvGetReal1D(const CvArr* arr, int idx0); \newline
double cvGetReal2D(const CvArr* arr, int idx0, int idx1); \newline
double cvGetReal3D(const CvArr* arr, int idx0, int idx1, int idx2); \newline
double cvGetRealND(const CvArr* arr, int* idx);
}
\begin{description}
\cvarg{arr}{Input array. Must have a single channel.}
\cvarg{idx0}{The first zero-based component of the element index}
\cvarg{idx1}{The second zero-based component of the element index}
\cvarg{idx2}{The third zero-based component of the element index}
\cvarg{idx}{Array of the element indices}
\end{description}
The functions \texttt{cvGetReal*D} return a specific element of a single-channel array. If the array has multiple channels, a runtime error is raised. Note that \cvCPyCross{Get} function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.
In the case of a sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions).
\fi
\ifC %{
\cvCPyFunc{GetRow(s)}
Returns array row or row span.
\cvdefC{CvMat* cvGetRow(const CvArr* arr, CvMat* submat, int row);}
\cvdefPy{GetRow(arr,row)-> submat}
\cvdefC{CvMat* cvGetRows(const CvArr* arr, CvMat* submat, int startRow, int endRow, int deltaRow=1);}
\cvdefPy{GetRows(arr,startRow,endRow,deltaRow=1)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{submat}{Pointer to the resulting sub-array header}
\cvarg{row}{Zero-based index of the selected row}
\cvarg{startRow}{Zero-based index of the starting row (inclusive) of the span}
\cvarg{endRow}{Zero-based index of the ending row (exclusive) of the span}
\cvarg{deltaRow}{Index step in the row span. That is, the function extracts every \texttt{deltaRow}-th row from \texttt{startRow} and up to (but not including) \texttt{endRow}.}
\end{description}
The functions return the header, corresponding to a specified row/row span of the input array. Note that \texttt{GetRow} is a shortcut for \cvCPyCross{GetRows}:
\begin{lstlisting}
cvGetRow(arr, submat, row ) ~ cvGetRows(arr, submat, row, row + 1, 1);
\end{lstlisting}
\else % }{
\cvCPyFunc{GetRow}
Returns array row.
\cvdefPy{GetRow(arr,row)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{row}{Zero-based index of the selected row}
\cvarg{submat}{resulting single-row array}
\end{description}
The function \texttt{GetRow} returns a single row from the input array.
\cvCPyFunc{GetRows}
Returns array row span.
\cvdefPy{GetRows(arr,startRow,endRow,deltaRow=1)-> submat}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{startRow}{Zero-based index of the starting row (inclusive) of the span}
\cvarg{endRow}{Zero-based index of the ending row (exclusive) of the span}
\cvarg{deltaRow}{Index step in the row span.}
\cvarg{submat}{resulting multi-row array}
\end{description}
The function \texttt{GetRows} returns a row span from the input array.
\fi % }
\cvCPyFunc{GetSize}
Returns size of matrix or image ROI.
\cvdefC{CvSize cvGetSize(const CvArr* arr);}
\cvdefPy{GetSize(arr)-> CvSize}
\begin{description}
\cvarg{arr}{array header}
\end{description}
The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In the case of image the size of ROI is returned.
\cvCPyFunc{GetSubRect}
Returns matrix header corresponding to the rectangular sub-array of input image or matrix.
\cvdefC{CvMat* cvGetSubRect(const CvArr* arr, CvMat* submat, CvRect rect);}
\cvdefPy{GetSubRect(arr, rect) -> cvmat}
\begin{description}
\cvarg{arr}{Input array}
\ifC
\cvarg{submat}{Pointer to the resultant sub-array header}
\fi
\cvarg{rect}{Zero-based coordinates of the rectangle of interest}
\end{description}
The function returns header, corresponding to
a specified rectangle of the input array. In other words, it allows
the user to treat a rectangular part of input array as a stand-alone
array. ROI is taken into account by the function so the sub-array of
ROI is actually extracted.
\cvCPyFunc{InRange}
Checks that array elements lie between the elements of two other arrays.
\cvdefC{void cvInRange(const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst);}
\cvdefPy{InRange(src,lower,upper,dst)-> None}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{lower}{The inclusive lower boundary array}
\cvarg{upper}{The exclusive upper boundary array}
\cvarg{dst}{The destination array, must have 8u or 8s type}
\end{description}
The function does the range check for every element of the input array:
\[
\texttt{dst}(I)=\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0
\]
For single-channel arrays,
\[
\texttt{dst}(I)=
\texttt{lower}(I)_0 <= \texttt{src}(I)_0 < \texttt{upper}(I)_0 \land
\texttt{lower}(I)_1 <= \texttt{src}(I)_1 < \texttt{upper}(I)_1
\]
For two-channel arrays and so forth,
dst(I) is set to 0xff (all \texttt{1}-bits) if src(I) is within the range and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size).
\cvCPyFunc{InRangeS}
Checks that array elements lie between two scalars.
\cvdefC{void cvInRangeS(const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst);}
\cvdefPy{InRangeS(src,lower,upper,dst)-> None}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{lower}{The inclusive lower boundary}
\cvarg{upper}{The exclusive upper boundary}
\cvarg{dst}{The destination array, must have 8u or 8s type}
\end{description}
The function does the range check for every element of the input array:
\[
\texttt{dst}(I)=\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0
\]
For single-channel arrays,
\[
\texttt{dst}(I)=
\texttt{lower}_0 <= \texttt{src}(I)_0 < \texttt{upper}_0 \land
\texttt{lower}_1 <= \texttt{src}(I)_1 < \texttt{upper}_1
\]
For two-channel arrays nd so forth,
'dst(I)' is set to 0xff (all \texttt{1}-bits) if 'src(I)' is within the range and 0 otherwise. All the arrays must have the same size (or ROI size).
\ifC
\cvCPyFunc{IncRefData}
Increments array data reference counter.
\cvdefC{int cvIncRefData(CvArr* arr);}
\begin{description}
\cvarg{arr}{Array header}
\end{description}
The function increments \cross{CvMat} or
\cross{CvMatND} data reference counter and returns the new counter value
if the reference counter pointer is not NULL, otherwise it returns zero.
\cvCPyFunc{InitImageHeader}
Initializes an image header that was previously allocated.
\cvdefC{IplImage* cvInitImageHeader(\par IplImage* image,\par CvSize size,\par int depth,\par int channels,\par int origin=0,\par int align=4);}
\begin{description}
\cvarg{image}{Image header to initialize}
\cvarg{size}{Image width and height}
\cvarg{depth}{Image depth (see \cvCPyCross{CreateImage})}
\cvarg{channels}{Number of channels (see \cvCPyCross{CreateImage})}
\cvarg{origin}{Top-left \texttt{IPL\_ORIGIN\_TL} or bottom-left \texttt{IPL\_ORIGIN\_BL}}
\cvarg{align}{Alignment for image rows, typically 4 or 8 bytes}
\end{description}
The returned \texttt{IplImage*} points to the initialized header.
\cvCPyFunc{InitMatHeader}
Initializes a pre-allocated matrix header.
\cvdefC{
CvMat* cvInitMatHeader(\par CvMat* mat,\par int rows,\par int cols,\par int type, \par void* data=NULL,\par int step=CV\_AUTOSTEP);
}
\begin{description}
\cvarg{mat}{A pointer to the matrix header to be initialized}
\cvarg{rows}{Number of rows in the matrix}
\cvarg{cols}{Number of columns in the matrix}
\cvarg{type}{Type of the matrix elements, see \cvCPyCross{CreateMat}.}
\cvarg{data}{Optional: data pointer assigned to the matrix header}
\cvarg{step}{Optional: full row width in bytes of the assigned data. By default, the minimal possible step is used which assumes there are no gaps between subsequent rows of the matrix.}
\end{description}
This function is often used to process raw data with OpenCV matrix functions. For example, the following code computes the matrix product of two matrices, stored as ordinary arrays:
\begin{lstlisting}
double a[] = { 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12 };
double b[] = { 1, 5, 9,
2, 6, 10,
3, 7, 11,
4, 8, 12 };
double c[9];
CvMat Ma, Mb, Mc ;
cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a);
cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b);
cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c);
cvMatMulAdd(&Ma, &Mb, 0, &Mc);
// the c array now contains the product of a (3x4) and b (4x3)
\end{lstlisting}
\cvCPyFunc{InitMatNDHeader}
Initializes a pre-allocated multi-dimensional array header.
\cvdefC{CvMatND* cvInitMatNDHeader(\par CvMatND* mat,\par int dims,\par const int* sizes,\par int type,\par void* data=NULL);}
\begin{description}
\cvarg{mat}{A pointer to the array header to be initialized}
\cvarg{dims}{The number of array dimensions}
\cvarg{sizes}{An array of dimension sizes}
\cvarg{type}{Type of array elements, see \cvCPyCross{CreateMat}}
\cvarg{data}{Optional data pointer assigned to the matrix header}
\end{description}
\cvCPyFunc{InitSparseMatIterator}
Initializes sparse array elements iterator.
\cvdefC{CvSparseNode* cvInitSparseMatIterator(const CvSparseMat* mat,
CvSparseMatIterator* matIterator);}
\begin{description}
\cvarg{mat}{Input array}
\cvarg{matIterator}{Initialized iterator}
\end{description}
The function initializes iterator of
sparse array elements and returns pointer to the first element, or NULL
if the array is empty.
\fi
\cvCPyFunc{InvSqrt}
Calculates the inverse square root.
\cvdefC{float cvInvSqrt(float value);}
\cvdefPy{InvSqrt(value)-> float}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
The function calculates the inverse square root of the argument, and normally it is faster than \texttt{1./sqrt(value)}. If the argument is zero or negative, the result is not determined. Special values ($\pm \infty $ , NaN) are not handled.
\cvCPyFunc{Inv}
Synonym for \cross{Invert}
\cvCPyFunc{Invert}
Finds the inverse or pseudo-inverse of a matrix.
\cvdefC{double cvInvert(const CvArr* src, CvArr* dst, int method=CV\_LU);}
\cvdefPy{Invert(src,dst,method=CV\_LU)-> double}
\begin{description}
\cvarg{src}{The source matrix}
\cvarg{dst}{The destination matrix}
\cvarg{method}{Inversion method
\begin{description}
\cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chosen}
\cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
\cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix}
\end{description}}
\end{description}
The function inverts matrix \texttt{src1} and stores the result in \texttt{src2}.
In the case of \texttt{LU} method, the function returns the \texttt{src1} determinant (src1 must be square). If it is 0, the matrix is not inverted and \texttt{src2} is filled with zeros.
In the case of \texttt{SVD} methods, the function returns the inversed condition of \texttt{src1} (ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src1} is all zeros. The SVD methods calculate a pseudo-inverse matrix if \texttt{src1} is singular.
\cvCPyFunc{IsInf}
Determines if the argument is Infinity.
\cvdefC{int cvIsInf(double value);}
\cvdefPy{IsInf(value)-> int}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
The function returns 1 if the argument is $\pm \infty $ (as defined by IEEE754 standard), 0 otherwise.
\cvCPyFunc{IsNaN}
Determines if the argument is Not A Number.
\cvdefC{int cvIsNaN(double value);}
\cvdefPy{IsNaN(value)-> int}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.
\cvCPyFunc{LUT}
Performs a look-up table transform of an array.
\cvdefC{void cvLUT(const CvArr* src, CvArr* dst, const CvArr* lut);}
\cvdefPy{LUT(src,dst,lut)-> None}
\begin{description}
\cvarg{src}{Source array of 8-bit elements}
\cvarg{dst}{Destination array of a given depth and of the same number of channels as the source array}
\cvarg{lut}{Look-up table of 256 elements; should have the same depth as the destination array. In the case of multi-channel source and destination arrays, the table should either have a single-channel (in this case the same table is used for all channels) or the same number of channels as the source/destination array.}
\end{description}
The function fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as follows:
\[
\texttt{dst}_i \leftarrow \texttt{lut}_{\texttt{src}_i + d}
\]
where
\[
d = \fork
{0}{if \texttt{src} has depth \texttt{CV\_8U}}
{128}{if \texttt{src} has depth \texttt{CV\_8S}}
\]
\cvCPyFunc{Log}
Calculates the natural logarithm of every array element's absolute value.
\cvdefC{void cvLog(const CvArr* src, CvArr* dst);}
\cvdefPy{Log(src,dst)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array, it should have \texttt{double} type or the same type as the source}
\end{description}
The function calculates the natural logarithm of the absolute value of every element of the input array:
\[
\texttt{dst} [I] = \fork
{\log{|\texttt{src}(I)}}{if $\texttt{src}[I] \ne 0$ }
{\texttt{C}}{otherwise}
\]
Where \texttt{C} is a large negative number (about -700 in the current implementation).
\cvCPyFunc{Mahalonobis}
Calculates the Mahalonobis distance between two vectors.
\cvdefC{double cvMahalanobis(\par const CvArr* vec1,\par const CvArr* vec2,\par CvArr* mat);}
\cvdefPy{Mahalonobis(vec1,vec2,mat)-> None}
\begin{description}
\cvarg{vec1}{The first 1D source vector}
\cvarg{vec2}{The second 1D source vector}
\cvarg{mat}{The inverse covariance matrix}
\end{description}
The function calculates and returns the weighted distance between two vectors:
\[
d(\texttt{vec1},\texttt{vec2})=\sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})}}
\]
The covariance matrix may be calculated using the \cvCPyCross{CalcCovarMatrix} function and further inverted using the \cvCPyCross{Invert} function (CV\_SVD method is the prefered one because the matrix might be singular).
\ifC
\cvCPyFunc{Mat}
Initializes matrix header (lightweight variant).
\cvdefC{CvMat cvMat(\par int rows,\par int cols,\par int type,\par void* data=NULL);}
\begin{description}
\cvarg{rows}{Number of rows in the matrix}
\cvarg{cols}{Number of columns in the matrix}
\cvarg{type}{Type of the matrix elements - see \cvCPyCross{CreateMat}}
\cvarg{data}{Optional data pointer assigned to the matrix header}
\end{description}
Initializes a matrix header and assigns data to it. The matrix is filled \textit{row}-wise (the first \texttt{cols} elements of data form the first row of the matrix, etc.)
This function is a fast inline substitution for \cvCPyCross{InitMatHeader}. Namely, it is equivalent to:
\begin{lstlisting}
CvMat mat;
cvInitMatHeader(&mat, rows, cols, type, data, CV\_AUTOSTEP);
\end{lstlisting}
\fi
\cvCPyFunc{Max}
Finds per-element maximum of two arrays.
\cvdefC{void cvMax(const CvArr* src1, const CvArr* src2, CvArr* dst);}
\cvdefPy{Max(src1,src2,dst)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\end{description}
The function calculates per-element maximum of two arrays:
\[
\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))
\]
All the arrays must have a single channel, the same data type and the same size (or ROI size).
\cvCPyFunc{MaxS}
Finds per-element maximum of array and scalar.
\cvdefC{void cvMaxS(const CvArr* src, double value, CvArr* dst);}
\cvdefPy{MaxS(src,value,dst)-> None}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{value}{The scalar value}
\cvarg{dst}{The destination array}
\end{description}
The function calculates per-element maximum of array and scalar:
\[
\texttt{dst}(I)=\max(\texttt{src}(I), \texttt{value})
\]
All the arrays must have a single channel, the same data type and the same size (or ROI size).
\cvCPyFunc{Merge}
Composes a multi-channel array from several single-channel arrays or inserts a single channel into the array.
\cvdefC{void cvMerge(const CvArr* src0, const CvArr* src1,
const CvArr* src2, const CvArr* src3, CvArr* dst);}
\ifC
\begin{lstlisting}
#define cvCvtPlaneToPix cvMerge
\end{lstlisting}
\fi
\cvdefPy{Merge(src0,src1,src2,src3,dst)-> None}
\begin{description}
\cvarg{src0}{Input channel 0}
\cvarg{src1}{Input channel 1}
\cvarg{src2}{Input channel 2}
\cvarg{src3}{Input channel 3}
\cvarg{dst}{Destination array}
\end{description}
The function is the opposite to \cvCPyCross{Split}. If the destination array has N channels then if the first N input channels are not NULL, they all are copied to the destination array; if only a single source channel of the first N is not NULL, this particular channel is copied into the destination array; otherwise an error is raised. The rest of the source channels (beyond the first N) must always be NULL. For IplImage \cvCPyCross{Copy} with COI set can be also used to insert a single channel into the image.
\cvCPyFunc{Min}
Finds per-element minimum of two arrays.
\cvdefC{void cvMin(const CvArr* src1, const CvArr* src2, CvArr* dst);}
\cvdefPy{Min(src1,src2,dst)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\end{description}
The function calculates per-element minimum of two arrays:
\[
\texttt{dst}(I)=\min(\texttt{src1}(I),\texttt{src2}(I))
\]
All the arrays must have a single channel, the same data type and the same size (or ROI size).
\cvCPyFunc{MinMaxLoc}
Finds global minimum and maximum in array or subarray.
\cvdefC{void cvMinMaxLoc(const CvArr* arr, double* minVal, double* maxVal,
CvPoint* minLoc=NULL, CvPoint* maxLoc=NULL, const CvArr* mask=NULL);}
\cvdefPy{MinMaxLoc(arr,mask=NULL)-> (minVal,maxVal,minLoc,maxLoc)}
\begin{description}
\cvarg{arr}{The source array, single-channel or multi-channel with COI set}
\cvarg{minVal}{Pointer to returned minimum value}
\cvarg{maxVal}{Pointer to returned maximum value}
\cvarg{minLoc}{Pointer to returned minimum location}
\cvarg{maxLoc}{Pointer to returned maximum location}
\cvarg{mask}{The optional mask used to select a subarray}
\end{description}
The function finds minimum and maximum element values
and their positions. The extremums are searched across the whole array,
selected \texttt{ROI} (in the case of \texttt{IplImage}) or, if \texttt{mask}
is not \texttt{NULL}, in the specified array region. If the array has
more than one channel, it must be \texttt{IplImage} with \texttt{COI}
set. In the case of multi-dimensional arrays, \texttt{minLoc->x} and \texttt{maxLoc->x}
will contain raw (linear) positions of the extremums.
\cvCPyFunc{MinS}
Finds per-element minimum of an array and a scalar.
\cvdefC{void cvMinS(const CvArr* src, double value, CvArr* dst);}
\cvdefPy{MinS(src,value,dst)-> None}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{value}{The scalar value}
\cvarg{dst}{The destination array}
\end{description}
The function calculates minimum of an array and a scalar:
\[
\texttt{dst}(I)=\min(\texttt{src}(I), \texttt{value})
\]
All the arrays must have a single channel, the same data type and the same size (or ROI size).
\subsection{Mirror}
Synonym for \cross{Flip}.
\cvCPyFunc{MixChannels}
Copies several channels from input arrays to certain channels of output arrays
\cvdefC{void cvMixChannels(const CvArr** src, int srcCount, \par
CvArr** dst, int dstCount, \par
const int* fromTo, int pairCount);}
\cvdefPy{MixChannels(src, dst, fromTo) -> None}
\begin{description}
\cvarg{src}{Input arrays}
\cvC{\cvarg{srcCount}{The number of input arrays.}}
\cvarg{dst}{Destination arrays}
\cvC{\cvarg{dstCount}{The number of output arrays.}}
\cvarg{fromTo}{The array of pairs of indices of the planes
copied. \cvC{\texttt{fromTo[k*2]} is the 0-based index of the input channel in \texttt{src} and
\texttt{fromTo[k*2+1]} is the index of the output channel in \texttt{dst}.
Here the continuous channel numbering is used, that is, the first input image channels are indexed
from \texttt{0} to \texttt{channels(src[0])-1}, the second input image channels are indexed from
\texttt{channels(src[0])} to \texttt{channels(src[0]) + channels(src[1])-1} etc., and the same
scheme is used for the output image channels.
As a special case, when \texttt{fromTo[k*2]} is negative,
the corresponding output channel is filled with zero.}\cvPy{Each pair \texttt{fromTo[k]=(i,j)}
means that i-th plane from \texttt{src} is copied to the j-th plane in \texttt{dst}, where continuous
plane numbering is used both in the input array list and the output array list.
As a special case, when the \texttt{fromTo[k][0]} is negative, the corresponding output plane \texttt{j}
is filled with zero.}}
\end{description}
The function is a generalized form of \cvCPyCross{cvSplit} and \cvCPyCross{Merge}
and some forms of \cross{CvtColor}. It can be used to change the order of the
planes, add/remove alpha channel, extract or insert a single plane or
multiple planes etc.
As an example, this code splits a 4-channel RGBA image into a 3-channel
BGR (i.e. with R and B swapped) and separate alpha channel image:
\ifPy
\begin{lstlisting}
rgba = cv.CreateMat(100, 100, cv.CV_8UC4)
bgr = cv.CreateMat(100, 100, cv.CV_8UC3)
alpha = cv.CreateMat(100, 100, cv.CV_8UC1)
cv.Set(rgba, (1,2,3,4))
cv.MixChannels([rgba], [bgr, alpha], [
(0, 2), # rgba[0] -> bgr[2]
(1, 1), # rgba[1] -> bgr[1]
(2, 0), # rgba[2] -> bgr[0]
(3, 3) # rgba[3] -> alpha[0]
])
\end{lstlisting}
\fi
\ifC
\begin{lstlisting}
CvMat* rgba = cvCreateMat(100, 100, CV_8UC4);
CvMat* bgr = cvCreateMat(rgba->rows, rgba->cols, CV_8UC3);
CvMat* alpha = cvCreateMat(rgba->rows, rgba->cols, CV_8UC1);
cvSet(rgba, cvScalar(1,2,3,4));
CvArr* out[] = { bgr, alpha };
int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
cvMixChannels(&bgra, 1, out, 2, from_to, 4);
\end{lstlisting}
\fi
\subsection{MulAddS}
Synonym for \cross{ScaleAdd}.
\cvCPyFunc{Mul}
Calculates the per-element product of two arrays.
\cvdefC{void cvMul(const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1);}
\cvdefPy{Mul(src1,src2,dst,scale)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{scale}{Optional scale factor}
\end{description}
The function calculates the per-element product of two arrays:
\[
\texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I)
\]
All the arrays must have the same type and the same size (or ROI size).
For types that have limited range this operation is saturating.
\cvCPyFunc{MulSpectrums}
Performs per-element multiplication of two Fourier spectrums.
\cvdefC{void cvMulSpectrums(\par const CvArr* src1,\par const CvArr* src2,\par CvArr* dst,\par int flags);}
\cvdefPy{MulSpectrums(src1,src2,dst,flags)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array of the same type and the same size as the source arrays}
\cvarg{flags}{A combination of the following values;
\begin{description}
\cvarg{CV\_DXT\_ROWS}{treats each row of the arrays as a separate spectrum (see \cvCPyCross{DFT} parameters description).}
\cvarg{CV\_DXT\_MUL\_CONJ}{conjugate the second source array before the multiplication.}
\end{description}}
\end{description}
The function performs per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
The function, together with \cvCPyCross{DFT}, may be used to calculate convolution of two arrays rapidly.
\cvCPyFunc{MulTransposed}
Calculates the product of an array and a transposed array.
\cvdefC{void cvMulTransposed(const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL, double scale=1.0);}
\cvdefPy{MulTransposed(src,dst,order,delta=NULL,scale)-> None}
\begin{description}
\cvarg{src}{The source matrix}
\cvarg{dst}{The destination matrix. Must be \texttt{CV\_32F} or \texttt{CV\_64F}.}
\cvarg{order}{Order of multipliers}
\cvarg{delta}{An optional array, subtracted from \texttt{src} before multiplication}
\cvarg{scale}{An optional scaling}
\end{description}
The function calculates the product of src and its transposition:
\[
\texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
\]
if $\texttt{order}=0$, and
\[
\texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
\]
otherwise.
\cvCPyFunc{Norm}
Calculates absolute array norm, absolute difference norm, or relative difference norm.
\cvdefC{double cvNorm(const CvArr* arr1, const CvArr* arr2=NULL, int normType=CV\_L2, const CvArr* mask=NULL);}
\cvdefPy{Norm(arr1,arr2,normType=CV\_L2,mask=NULL)-> double}
\begin{description}
\cvarg{arr1}{The first source image}
\cvarg{arr2}{The second source image. If it is NULL, the absolute norm of \texttt{arr1} is calculated, otherwise the absolute or relative norm of \texttt{arr1}-\texttt{arr2} is calculated.}
\cvarg{normType}{Type of norm, see the discussion}
\cvarg{mask}{The optional operation mask}
\end{description}
The function calculates the absolute norm of \texttt{arr1} if \texttt{arr2} is NULL:
\[
norm = \forkthree
{||\texttt{arr1}||_C = \max_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
{||\texttt{arr1}||_{L1} = \sum_I |\texttt{arr1}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
{||\texttt{arr1}||_{L2} = \sqrt{\sum_I \texttt{arr1}(I)^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
\]
or the absolute difference norm if \texttt{arr2} is not NULL:
\[
norm = \forkthree
{||\texttt{arr1}-\texttt{arr2}||_C = \max_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_C}$}
{||\texttt{arr1}-\texttt{arr2}||_{L1} = \sum_I |\texttt{arr1}(I) - \texttt{arr2}(I)|}{if $\texttt{normType} = \texttt{CV\_L1}$}
{||\texttt{arr1}-\texttt{arr2}||_{L2} = \sqrt{\sum_I (\texttt{arr1}(I) - \texttt{arr2}(I))^2}}{if $\texttt{normType} = \texttt{CV\_L2}$}
\]
or the relative difference norm if \texttt{arr2} is not NULL and \texttt{(normType \& CV\_RELATIVE) != 0}:
\[
norm = \forkthree
{\frac{||\texttt{arr1}-\texttt{arr2}||_C }{||\texttt{arr2}||_C }}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_C}$}
{\frac{||\texttt{arr1}-\texttt{arr2}||_{L1} }{||\texttt{arr2}||_{L1}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L1}$}
{\frac{||\texttt{arr1}-\texttt{arr2}||_{L2} }{||\texttt{arr2}||_{L2}}}{if $\texttt{normType} = \texttt{CV\_RELATIVE\_L2}$}
\]
The function returns the calculated norm. A multiple-channel array is treated as a single-channel, that is, the results for all channels are combined.
\cvCPyFunc{Not}
Performs per-element bit-wise inversion of array elements.
\cvdefC{void cvNot(const CvArr* src, CvArr* dst);}
\cvdefPy{Not(src,dst)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array}
\end{description}
The function Not inverses every bit of every array element:
\begin{lstlisting}
dst(I)=~src(I)
\end{lstlisting}
\cvCPyFunc{Or}
Calculates per-element bit-wise disjunction of two arrays.
\cvdefC{void cvOr(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{Or(src1,src2,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function calculates per-element bit-wise disjunction of two arrays:
\begin{lstlisting}
dst(I)=src1(I)|src2(I)
\end{lstlisting}
In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
\cvCPyFunc{OrS}
Calculates a per-element bit-wise disjunction of an array and a scalar.
\cvdefC{void cvOrS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{OrS(src,value,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{value}{Scalar to use in the operation}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function OrS calculates per-element bit-wise disjunction of an array and a scalar:
\begin{lstlisting}
dst(I)=src(I)|value if mask(I)!=0
\end{lstlisting}
Prior to the actual operation, the scalar is converted to the same type as that of the array(s). In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
\cvCPyFunc{PerspectiveTransform}
Performs perspective matrix transformation of a vector array.
\cvdefC{void cvPerspectiveTransform(const CvArr* src, CvArr* dst, const CvMat* mat);}
\cvdefPy{PerspectiveTransform(src,dst,mat)-> None}
\begin{description}
\cvarg{src}{The source three-channel floating-point array}
\cvarg{dst}{The destination three-channel floating-point array}
\cvarg{mat}{$3\times 3$ or $4 \times 4$ transformation matrix}
\end{description}
The function transforms every element of \texttt{src} (by treating it as 2D or 3D vector) in the following way:
\[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
where
\[
(x', y', z', w') = \texttt{mat} \cdot
\begin{bmatrix} x & y & z & 1 \end{bmatrix}
\]
and
\[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
\cvCPyFunc{PolarToCart}
Calculates Cartesian coordinates of 2d vectors represented in polar form.
\cvdefC{void cvPolarToCart(\par const CvArr* magnitude,\par const CvArr* angle,\par CvArr* x,\par CvArr* y,\par int angleInDegrees=0);}
\cvdefPy{PolarToCart(magnitude,angle,x,y,angleInDegrees=0)-> None}
\begin{description}
\cvarg{magnitude}{The array of magnitudes. If it is NULL, the magnitudes are assumed to be all 1's.}
\cvarg{angle}{The array of angles, whether in radians or degrees}
\cvarg{x}{The destination array of x-coordinates, may be set to NULL if it is not needed}
\cvarg{y}{The destination array of y-coordinates, mau be set to NULL if it is not needed}
\cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
\end{description}
The function calculates either the x-coodinate, y-coordinate or both of every vector \texttt{magnitude(I)*exp(angle(I)*j), j=sqrt(-1)}:
\begin{lstlisting}
x(I)=magnitude(I)*cos(angle(I)),
y(I)=magnitude(I)*sin(angle(I))
\end{lstlisting}
\cvCPyFunc{Pow}
Raises every array element to a power.
\cvdefC{void cvPow(\par const CvArr* src,\par CvArr* dst,\par double power);}
\cvdefPy{Pow(src,dst,power)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array, should be the same type as the source}
\cvarg{power}{The exponent of power}
\end{description}
The function raises every element of the input array to \texttt{p}:
\[
\texttt{dst} [I] = \fork
{\texttt{src}(I)^p}{if \texttt{p} is integer}
{|\texttt{src}(I)^p|}{otherwise}
\]
That is, for a non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following example, computing the cube root of array elements, shows:
\ifC
\begin{lstlisting}
CvSize size = cvGetSize(src);
CvMat* mask = cvCreateMat(size.height, size.width, CV_8UC1);
cvCmpS(src, 0, mask, CV_CMP_LT); /* find negative elements */
cvPow(src, dst, 1./3);
cvSubRS(dst, cvScalarAll(0), dst, mask); /* negate the results of negative inputs */
cvReleaseMat(&mask);
\end{lstlisting}
\else
\begin{lstlisting}
>>> import cv
>>> src = cv.CreateMat(1, 10, cv.CV_32FC1)
>>> mask = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
>>> dst = cv.CreateMat(src.rows, src.cols, cv.CV_32FC1)
>>> cv.CmpS(src, 0, mask, cv.CV_CMP_LT) # find negative elements
>>> cv.Pow(src, dst, 1. / 3)
>>> cv.SubRS(dst, cv.ScalarAll(0), dst, mask) # negate the results of negative inputs
\end{lstlisting}
\fi
For some values of \texttt{power}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
\ifC
\cvCPyFunc{Ptr?D}
Return pointer to a particular array element.
\cvdefC{
uchar* cvPtr1D(const CvArr* arr, int idx0, int* type=NULL); \newline
uchar* cvPtr2D(const CvArr* arr, int idx0, int idx1, int* type=NULL); \newline
uchar* cvPtr3D(const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL); \newline
uchar* cvPtrND(const CvArr* arr, int* idx, int* type=NULL, int createNode=1, unsigned* precalcHashval=NULL);
}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{The first zero-based component of the element index}
\cvarg{idx1}{The second zero-based component of the element index}
\cvarg{idx2}{The third zero-based component of the element index}
\cvarg{idx}{Array of the element indices}
\cvarg{type}{Optional output parameter: type of matrix elements}
\cvarg{createNode}{Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already.}
\cvarg{precalcHashval}{Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example)}
\end{description}
The functions return a pointer to a specific array element. Number of array dimension should match to the number of indices passed to the function except for \texttt{cvPtr1D} function that can be used for sequential access to 1D, 2D or nD dense arrays.
The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero.
All these as well as other functions accessing array elements (\cvCPyCross{Get}, \cvCPyCross{GetReal},
\cvCPyCross{Set}, \cvCPyCross{SetReal}) raise an error in case if the element index is out of range.
\fi
\cvCPyFunc{RNG}
Initializes a random number generator state.
\cvdefC{CvRNG cvRNG(int64 seed=-1);}
\cvdefPy{RNG(seed=-1LL)-> CvRNG}
\begin{description}
\cvarg{seed}{64-bit value used to initiate a random sequence}
\end{description}
The function initializes a random number generator
and returns the state. The pointer to the state can be then passed to the
\cvCPyCross{RandInt}, \cvCPyCross{RandReal} and \cvCPyCross{RandArr} functions. In the
current implementation a multiply-with-carry generator is used.
\cvCPyFunc{RandArr}
Fills an array with random numbers and updates the RNG state.
\cvdefC{void cvRandArr(\par CvRNG* rng,\par CvArr* arr,\par int distType,\par CvScalar param1,\par CvScalar param2);}
\cvdefPy{RandArr(rng,arr,distType,param1,param2)-> None}
\begin{description}
\cvarg{rng}{RNG state initialized by \cvCPyCross{RNG}}
\cvarg{arr}{The destination array}
\cvarg{distType}{Distribution type
\begin{description}
\cvarg{CV\_RAND\_UNI}{uniform distribution}
\cvarg{CV\_RAND\_NORMAL}{normal or Gaussian distribution}
\end{description}}
\cvarg{param1}{The first parameter of the distribution. In the case of a uniform distribution it is the inclusive lower boundary of the random numbers range. In the case of a normal distribution it is the mean value of the random numbers.}
\cvarg{param2}{The second parameter of the distribution. In the case of a uniform distribution it is the exclusive upper boundary of the random numbers range. In the case of a normal distribution it is the standard deviation of the random numbers.}
\end{description}
The function fills the destination array with uniformly
or normally distributed random numbers.
\ifC
In the example below, the function
is used to add a few normally distributed floating-point numbers to
random locations within a 2d array.
\begin{lstlisting}
/* let noisy_screen be the floating-point 2d array that is to be "crapped" */
CvRNG rng_state = cvRNG(0xffffffff);
int i, pointCount = 1000;
/* allocate the array of coordinates of points */
CvMat* locations = cvCreateMat(pointCount, 1, CV_32SC2);
/* arr of random point values */
CvMat* values = cvCreateMat(pointCount, 1, CV_32FC1);
CvSize size = cvGetSize(noisy_screen);
/* initialize the locations */
cvRandArr(&rng_state, locations, CV_RAND_UNI, cvScalar(0,0,0,0),
cvScalar(size.width,size.height,0,0));
/* generate values */
cvRandArr(&rng_state, values, CV_RAND_NORMAL,
cvRealScalar(100), // average intensity
cvRealScalar(30) // deviation of the intensity
);
/* set the points */
for(i = 0; i < pointCount; i++ )
{
CvPoint pt = *(CvPoint*)cvPtr1D(locations, i, 0);
float value = *(float*)cvPtr1D(values, i, 0);
*((float*)cvPtr2D(noisy_screen, pt.y, pt.x, 0 )) += value;
}
/* not to forget to release the temporary arrays */
cvReleaseMat(&locations);
cvReleaseMat(&values);
/* RNG state does not need to be deallocated */
\end{lstlisting}
\fi
\cvCPyFunc{RandInt}
Returns a 32-bit unsigned integer and updates RNG.
\cvdefC{unsigned cvRandInt(CvRNG* rng);}
\cvdefPy{RandInt(rng)-> unsigned}
\begin{description}
\cvarg{rng}{RNG state initialized by \texttt{RandInit} and, optionally, customized by \texttt{RandSetRange} (though, the latter function does not affect the discussed function outcome)}
\end{description}
The function returns a uniformly-distributed random
32-bit unsigned integer and updates the RNG state. It is similar to the rand()
function from the C runtime library, but it always generates a 32-bit number
whereas rand() returns a number in between 0 and \texttt{RAND\_MAX}
which is $2^{16}$ or $2^{32}$, depending on the platform.
The function is useful for generating scalar random numbers, such as
points, patch sizes, table indices, etc., where integer numbers of a certain
range can be generated using a modulo operation and floating-point numbers
can be generated by scaling from 0 to 1 or any other specific range.
\ifC
Here is the example from the previous function discussion rewritten using
\cvCPyCross{RandInt}:
\begin{lstlisting}
/* the input and the task is the same as in the previous sample. */
CvRNG rnggstate = cvRNG(0xffffffff);
int i, pointCount = 1000;
/* ... - no arrays are allocated here */
CvSize size = cvGetSize(noisygscreen);
/* make a buffer for normally distributed numbers to reduce call overhead */
#define bufferSize 16
float normalValueBuffer[bufferSize];
CvMat normalValueMat = cvMat(bufferSize, 1, CVg32F, normalValueBuffer);
int valuesLeft = 0;
for(i = 0; i < pointCount; i++ )
{
CvPoint pt;
/* generate random point */
pt.x = cvRandInt(&rnggstate ) % size.width;
pt.y = cvRandInt(&rnggstate ) % size.height;
if(valuesLeft <= 0 )
{
/* fulfill the buffer with normally distributed numbers
if the buffer is empty */
cvRandArr(&rnggstate, &normalValueMat, CV\_RAND\_NORMAL,
cvRealScalar(100), cvRealScalar(30));
valuesLeft = bufferSize;
}
*((float*)cvPtr2D(noisygscreen, pt.y, pt.x, 0 ) =
normalValueBuffer[--valuesLeft];
}
/* there is no need to deallocate normalValueMat because we have
both the matrix header and the data on stack. It is a common and efficient
practice of working with small, fixed-size matrices */
\end{lstlisting}
\fi
\cvCPyFunc{RandReal}
Returns a floating-point random number and updates RNG.
\cvdefC{double cvRandReal(CvRNG* rng);}
\cvdefPy{RandReal(rng)-> double}
\begin{description}
\cvarg{rng}{RNG state initialized by \cvCPyCross{RNG}}
\end{description}
The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not included).
\cvCPyFunc{Reduce}
Reduces a matrix to a vector.
\cvdefC{void cvReduce(const CvArr* src, CvArr* dst, int dim = -1, int op=CV\_REDUCE\_SUM);}
\cvdefPy{Reduce(src,dst,dim=-1,op=CV\_REDUCE\_SUM)-> None}
\begin{description}
\cvarg{src}{The input matrix.}
\cvarg{dst}{The output single-row/single-column vector that accumulates somehow all the matrix rows/columns.}
\cvarg{dim}{The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row, 1 means that the matrix is reduced to a single column and -1 means that the dimension is chosen automatically by analysing the dst size.}
\cvarg{op}{The reduction operation. It can take of the following values:
\begin{description}
\cvarg{CV\_REDUCE\_SUM}{The output is the sum of all of the matrix's rows/columns.}
\cvarg{CV\_REDUCE\_AVG}{The output is the mean vector of all of the matrix's rows/columns.}
\cvarg{CV\_REDUCE\_MAX}{The output is the maximum (column/row-wise) of all of the matrix's rows/columns.}
\cvarg{CV\_REDUCE\_MIN}{The output is the minimum (column/row-wise) of all of the matrix's rows/columns.}
\end{description}}
\end{description}
The function reduces matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of an raster image. In the case of \texttt{CV\_REDUCE\_SUM} and \texttt{CV\_REDUCE\_AVG} the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.
\ifC
\cvCPyFunc{ReleaseData}
Releases array data.
\cvdefC{void cvReleaseData(CvArr* arr);}
\begin{description}
\cvarg{arr}{Array header}
\end{description}
The function releases the array data. In the case of \cross{CvMat} or \cross{CvMatND} it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to \cvCPyCross{CreateData}.
\cvCPyFunc{ReleaseImage}
Deallocates the image header and the image data.
\cvdefC{void cvReleaseImage(IplImage** image);}
\begin{description}
\cvarg{image}{Double pointer to the image header}
\end{description}
This call is a shortened form of
\begin{lstlisting}
if(*image )
{
cvReleaseData(*image);
cvReleaseImageHeader(image);
}
\end{lstlisting}
\cvCPyFunc{ReleaseImageHeader}
Deallocates an image header.
\cvdefC{void cvReleaseImageHeader(IplImage** image);}
\begin{description}
\cvarg{image}{Double pointer to the image header}
\end{description}
This call is an analogue of
\begin{lstlisting}
if(image )
{
iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI);
*image = 0;
}
\end{lstlisting}
but it does not use IPL functions by default (see the \texttt{CV\_TURN\_ON\_IPL\_COMPATIBILITY} macro).
\cvCPyFunc{ReleaseMat}
Deallocates a matrix.
\cvdefC{void cvReleaseMat(CvMat** mat);}
\begin{description}
\cvarg{mat}{Double pointer to the matrix}
\end{description}
The function decrements the matrix data reference counter and deallocates matrix header. If the data reference counter is 0, it also deallocates the data.
\begin{lstlisting}
if(*mat )
cvDecRefData(*mat);
cvFree((void**)mat);
\end{lstlisting}
\cvCPyFunc{ReleaseMatND}
Deallocates a multi-dimensional array.
\cvdefC{void cvReleaseMatND(CvMatND** mat);}
\begin{description}
\cvarg{mat}{Double pointer to the array}
\end{description}
The function decrements the array data reference counter and releases the array header. If the reference counter reaches 0, it also deallocates the data.
\begin{lstlisting}
if(*mat )
cvDecRefData(*mat);
cvFree((void**)mat);
\end{lstlisting}
\cvCPyFunc{ReleaseSparseMat}
Deallocates sparse array.
\cvdefC{void cvReleaseSparseMat(CvSparseMat** mat);}
\begin{description}
\cvarg{mat}{Double pointer to the array}
\end{description}
The function releases the sparse array and clears the array pointer upon exit.
\fi
\cvCPyFunc{Repeat}
Fill the destination array with repeated copies of the source array.
\cvdefC{void cvRepeat(const CvArr* src, CvArr* dst);}
\cvdefPy{Repeat(src,dst)-> None}
\begin{description}
\cvarg{src}{Source array, image or matrix}
\cvarg{dst}{Destination array, image or matrix}
\end{description}
The function fills the destination array with repeated copies of the source array:
\begin{lstlisting}
dst(i,j)=src(i mod rows(src), j mod cols(src))
\end{lstlisting}
So the destination array may be as larger as well as smaller than the source array.
\cvCPyFunc{ResetImageROI}
Resets the image ROI to include the entire image and releases the ROI structure.
\cvdefC{void cvResetImageROI(IplImage* image);}
\cvdefPy{ResetImageROI(image)-> None}
\begin{description}
\cvarg{image}{A pointer to the image header}
\end{description}
This produces a similar result to the following
\ifC
, but in addition it releases the ROI structure.
\begin{lstlisting}
cvSetImageROI(image, cvRect(0, 0, image->width, image->height ));
cvSetImageCOI(image, 0);
\end{lstlisting}
\else
\begin{lstlisting}
cv.SetImageROI(image, (0, 0, image.width, image.height))
cv.SetImageCOI(image, 0)
\end{lstlisting}
\fi
\cvCPyFunc{Reshape}
Changes shape of matrix/image without copying data.
\cvdefC{CvMat* cvReshape(const CvArr* arr, CvMat* header, int newCn, int newRows=0);}
\cvdefPy{Reshape(arr, newCn, newRows=0) -> cvmat}
\begin{description}
\cvarg{arr}{Input array}
\ifC
\cvarg{header}{Output header to be filled}
\fi
\cvarg{newCn}{New number of channels. 'newCn = 0' means that the number of channels remains unchanged.}
\cvarg{newRows}{New number of rows. 'newRows = 0' means that the number of rows remains unchanged unless it needs to be changed according to \texttt{newCn} value.}
\end{description}
The function initializes the CvMat header so that it points to the same data as the original array but has a different shape - different number of channels, different number of rows, or both.
\ifC
The following example code creates one image buffer and two image headers, the first is for a 320x240x3 image and the second is for a 960x240x1 image:
\begin{lstlisting}
IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
CvMat gray_mat_hdr;
IplImage gray_img_hdr, *gray_img;
cvReshape(color_img, &gray_mat_hdr, 1);
gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr);
\end{lstlisting}
And the next example converts a 3x3 matrix to a single 1x9 vector:
\begin{lstlisting}
CvMat* mat = cvCreateMat(3, 3, CV_32F);
CvMat row_header, *row;
row = cvReshape(mat, &row_header, 0, 1);
\end{lstlisting}
\fi
\cvCPyFunc{ReshapeMatND}
Changes the shape of a multi-dimensional array without copying the data.
\cvdefC{CvArr* cvReshapeMatND(const CvArr* arr,
int sizeofHeader, CvArr* header,
int newCn, int newDims, int* newSizes);}
\cvdefPy{ReshapeMatND(arr, newCn, newDims) -> cvmat}
\ifC
\begin{lstlisting}
#define cvReshapeND(arr, header, newCn, newDims, newSizes ) \
cvReshapeMatND((arr), sizeof(*(header)), (header), \
(newCn), (newDims), (newSizes))
\end{lstlisting}
\fi
\begin{description}
\cvarg{arr}{Input array}
\ifC
\cvarg{sizeofHeader}{Size of output header to distinguish between IplImage, CvMat and CvMatND output headers}
\cvarg{header}{Output header to be filled}
\cvarg{newCn}{New number of channels. $\texttt{newCn} = 0$ means that the number of channels remains unchanged.}
\cvarg{newDims}{New number of dimensions. $\texttt{newDims} = 0$ means that the number of dimensions remains the same.}
\cvarg{newSizes}{Array of new dimension sizes. Only $\texttt{newDims}-1$ values are used, because the total number of elements must remain the same.
Thus, if $\texttt{newDims} = 1$, \texttt{newSizes} array is not used.}
\else
\cvarg{newCn}{New number of channels. $\texttt{newCn} = 0$ means that the number of channels remains unchanged.}
\cvarg{newDims}{List of new dimensions.}
\fi
\end{description}
\ifC
The function is an advanced version of \cvCPyCross{Reshape} that can work with multi-dimensional arrays as well (though it can work with ordinary images and matrices) and change the number of dimensions.
Below are the two samples from the \cvCPyCross{Reshape} description rewritten using \cvCPyCross{ReshapeMatND}:
\begin{lstlisting}
IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3);
IplImage gray_img_hdr, *gray_img;
gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0);
...
/* second example is modified to convert 2x2x2 array to 8x1 vector */
int size[] = { 2, 2, 2 };
CvMatND* mat = cvCreateMatND(3, size, CV_32F);
CvMat row_header, *row;
row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0);
\end{lstlisting}
\fi
\ifPy
Returns a new \cross{CvMatND} that shares the same data as \texttt{arr}
but has different dimensions or number of channels. The only requirement
is that the total length of the data is unchanged.
\begin{lstlisting}
>>> import cv
>>> mat = cv.CreateMatND([24], cv.CV_32FC1)
>>> print cv.GetDims(cv.ReshapeMatND(mat, 0, [8, 3]))
(8, 3)
>>> m2 = cv.ReshapeMatND(mat, 4, [3, 2])
>>> print cv.GetDims(m2)
(3, 2)
>>> print m2.channels
4
\end{lstlisting}
\fi
\ifC
\cvfunc{cvRound, cvFloor, cvCeil}\label{cvRound}
Converts a floating-point number to an integer.
\cvdefC{
int cvRound(double value);
int cvFloor(double value);
int cvCeil(double value);
}\cvdefPy{Round, Floor, Ceil(value)-> int}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
The functions convert the input floating-point number to an integer using one of the rounding
modes. \texttt{Round} returns the nearest integer value to the
argument. \texttt{Floor} returns the maximum integer value that is not
larger than the argument. \texttt{Ceil} returns the minimum integer
value that is not smaller than the argument. On some architectures the
functions work much faster than the standard cast
operations in C. If the absolute value of the argument is greater than
$2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
are not handled.
\else
\cvCPyFunc{Round}
Converts a floating-point number to the nearest integer value.
\cvdefPy{Round(value) -> int}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
On some architectures this function is much faster than the standard cast
operations. If the absolute value of the argument is greater than
$2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
are not handled.
\cvCPyFunc{Floor}
Converts a floating-point number to the nearest integer value that is not larger than the argument.
\cvdefPy{Floor(value) -> int}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
On some architectures this function is much faster than the standard cast
operations. If the absolute value of the argument is greater than
$2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
are not handled.
\cvCPyFunc{Ceil}
Converts a floating-point number to the nearest integer value that is not smaller than the argument.
\cvdefPy{Ceil(value) -> int}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
On some architectures this function is much faster than the standard cast
operations. If the absolute value of the argument is greater than
$2^{31}$, the result is not determined. Special values ($\pm \infty$ , NaN)
are not handled.
\fi
\cvCPyFunc{ScaleAdd}
Calculates the sum of a scaled array and another array.
\cvdefC{void cvScaleAdd(const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst);}
\cvdefPy{ScaleAdd(src1,scale,src2,dst)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{scale}{Scale factor for the first array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\end{description}
The function calculates the sum of a scaled array and another array:
\[
\texttt{dst}(I)=\texttt{scale} \, \texttt{src1}(I) + \texttt{src2}(I)
\]
All array parameters should have the same type and the same size.
\cvCPyFunc{Set}
Sets every element of an array to a given value.
\cvdefC{void cvSet(CvArr* arr, CvScalar value, const CvArr* mask=NULL);}
\cvdefPy{Set(arr,value,mask=NULL)-> None}
\begin{description}
\cvarg{arr}{The destination array}
\cvarg{value}{Fill value}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function copies the scalar \texttt{value} to every selected element of the destination array:
\[
\texttt{arr}(I)=\texttt{value} \quad \text{if} \quad \texttt{mask}(I) \ne 0
\]
If array \texttt{arr} is of \texttt{IplImage} type, then is ROI used, but COI must not be set.
\ifC % {
\cvCPyFunc{Set?D}
Change the particular array element.
\cvdefC{
void cvSet1D(CvArr* arr, int idx0, CvScalar value); \newline
void cvSet2D(CvArr* arr, int idx0, int idx1, CvScalar value); \newline
void cvSet3D(CvArr* arr, int idx0, int idx1, int idx2, CvScalar value); \newline
void cvSetND(CvArr* arr, int* idx, CvScalar value);
}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{The first zero-based component of the element index}
\cvarg{idx1}{The second zero-based component of the element index}
\cvarg{idx2}{The third zero-based component of the element index}
\cvarg{idx}{Array of the element indices}
\cvarg{value}{The assigned value}
\end{description}
The functions assign the new value to a particular array element. In the case of a sparse array the functions create the node if it does not exist yet.
\else % }{
\cvCPyFunc{Set1D}
Set a specific array element.
\cvdefPy{ Set1D(arr, idx, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx}{Zero-based element index}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. Array must have dimension 1.
\cvCPyFunc{Set2D}
Set a specific array element.
\cvdefPy{ Set2D(arr, idx0, idx1, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{Zero-based element row index}
\cvarg{idx1}{Zero-based element column index}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. Array must have dimension 2.
\cvCPyFunc{Set3D}
Set a specific array element.
\cvdefPy{ Set3D(arr, idx0, idx1, idx2, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{Zero-based element index}
\cvarg{idx1}{Zero-based element index}
\cvarg{idx2}{Zero-based element index}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. Array must have dimension 3.
\cvCPyFunc{SetND}
Set a specific array element.
\cvdefPy{ SetND(arr, indices, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{indices}{List of zero-based element indices}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. The length of array indices must be the same as the dimension of the array.
\fi % }
\cvCPyFunc{SetData}
Assigns user data to the array header.
\cvdefC{void cvSetData(CvArr* arr, void* data, int step);}
\cvdefPy{SetData(arr, data, step)-> None}
\begin{description}
\cvarg{arr}{Array header}
\cvarg{data}{User data}
\cvarg{step}{Full row length in bytes}
\end{description}
The function assigns user data to the array header. Header should be initialized before using \texttt{cvCreate*Header}, \texttt{cvInit*Header} or \cvCPyCross{Mat} (in the case of matrix) function.
\cvCPyFunc{SetIdentity}
Initializes a scaled identity matrix.
\cvdefC{void cvSetIdentity(CvArr* mat, CvScalar value=cvRealScalar(1));}
\cvdefPy{SetIdentity(mat,value=1)-> None}
\begin{description}
\cvarg{mat}{The matrix to initialize (not necesserily square)}
\cvarg{value}{The value to assign to the diagonal elements}
\end{description}
The function initializes a scaled identity matrix:
\[
\texttt{arr}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
\]
\cvCPyFunc{SetImageCOI}
Sets the channel of interest in an IplImage.
\cvdefC{void cvSetImageCOI(\par IplImage* image,\par int coi);}
\cvdefPy{SetImageCOI(image, coi)-> None}
\begin{description}
\cvarg{image}{A pointer to the image header}
\cvarg{coi}{The channel of interest. 0 - all channels are selected, 1 - first channel is selected, etc. Note that the channel indices become 1-based.}
\end{description}
If the ROI is set to \texttt{NULL} and the coi is \textit{not} 0,
the ROI is allocated. Most OpenCV functions do \textit{not} support
the COI setting, so to process an individual image/matrix channel one
may copy (via \cvCPyCross{Copy} or \cvCPyCross{Split}) the channel to a separate
image/matrix, process it and then copy the result back (via \cvCPyCross{Copy}
or \cvCPyCross{Merge}) if needed.
\cvCPyFunc{SetImageROI}
Sets an image Region Of Interest (ROI) for a given rectangle.
\cvdefC{void cvSetImageROI(\par IplImage* image,\par CvRect rect);}
\cvdefPy{SetImageROI(image, rect)-> None}
\begin{description}
\cvarg{image}{A pointer to the image header}
\cvarg{rect}{The ROI rectangle}
\end{description}
If the original image ROI was \texttt{NULL} and the \texttt{rect} is not the whole image, the ROI structure is allocated.
Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the ROI, not the original image.
\ifC % {
\cvCPyFunc{SetReal?D}
Change a specific array element.
\cvdefC{
void cvSetReal1D(CvArr* arr, int idx0, double value); \newline
void cvSetReal2D(CvArr* arr, int idx0, int idx1, double value); \newline
void cvSetReal3D(CvArr* arr, int idx0, int idx1, int idx2, double value); \newline
void cvSetRealND(CvArr* arr, int* idx, double value);
}
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{The first zero-based component of the element index}
\cvarg{idx1}{The second zero-based component of the element index}
\cvarg{idx2}{The third zero-based component of the element index}
\cvarg{idx}{Array of the element indices}
\cvarg{value}{The assigned value}
\end{description}
The functions assign a new value to a specific
element of a single-channel array. If the array has multiple channels,
a runtime error is raised. Note that the \cvCPyCross{Set*D} function can be used
safely for both single-channel and multiple-channel arrays, though they
are a bit slower.
In the case of a sparse array the functions create the node if it does not yet exist.
\else % }{
\cvCPyFunc{SetReal1D}
Set a specific array element.
\cvdefPy{ SetReal1D(arr, idx, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx}{Zero-based element index}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. Array must have dimension 1.
\cvCPyFunc{SetReal2D}
Set a specific array element.
\cvdefPy{ SetReal2D(arr, idx0, idx1, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{Zero-based element row index}
\cvarg{idx1}{Zero-based element column index}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. Array must have dimension 2.
\cvCPyFunc{SetReal3D}
Set a specific array element.
\cvdefPy{ SetReal3D(arr, idx0, idx1, idx2, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{idx0}{Zero-based element index}
\cvarg{idx1}{Zero-based element index}
\cvarg{idx2}{Zero-based element index}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. Array must have dimension 3.
\cvCPyFunc{SetRealND}
Set a specific array element.
\cvdefPy{ SetRealND(arr, indices, value) -> None }
\begin{description}
\cvarg{arr}{Input array}
\cvarg{indices}{List of zero-based element indices}
\cvarg{value}{The value to assign to the element}
\end{description}
Sets a specific array element. The length of array indices must be the same as the dimension of the array.
\fi % }
\cvCPyFunc{SetZero}
Clears the array.
\cvdefC{void cvSetZero(CvArr* arr);}
\cvdefPy{SetZero(arr)-> None}
\ifC
\begin{lstlisting}
#define cvZero cvSetZero
\end{lstlisting}
\fi
\begin{description}
\cvarg{arr}{Array to be cleared}
\end{description}
The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0).
In the case of sparse arrays all the elements are removed.
\cvCPyFunc{Solve}
Solves a linear system or least-squares problem.
\cvdefC{int cvSolve(const CvArr* src1, const CvArr* src2, CvArr* dst, int method=CV\_LU);}
\cvdefPy{Solve(A,B,X,method=CV\_LU)-> None}
\begin{description}
\cvarg{A}{The source matrix}
\cvarg{B}{The right-hand part of the linear system}
\cvarg{X}{The output solution}
\cvarg{method}{The solution (matrix inversion) method
\begin{description}
\cvarg{CV\_LU}{Gaussian elimination with optimal pivot element chosen}
\cvarg{CV\_SVD}{Singular value decomposition (SVD) method}
\cvarg{CV\_SVD\_SYM}{SVD method for a symmetric positively-defined matrix.}
\end{description}}
\end{description}
The function solves a linear system or least-squares problem (the latter is possible with SVD methods):
\[
\texttt{dst} = argmin_X||\texttt{src1} \, \texttt{X} - \texttt{src2}||
\]
If \texttt{CV\_LU} method is used, the function returns 1 if \texttt{src1} is non-singular and 0 otherwise; in the latter case \texttt{dst} is not valid.
\cvCPyFunc{SolveCubic}
Finds the real roots of a cubic equation.
\cvdefC{void cvSolveCubic(const CvArr* coeffs, CvArr* roots);}
\cvdefPy{SolveCubic(coeffs,roots)-> None}
\begin{description}
\cvarg{coeffs}{The equation coefficients, an array of 3 or 4 elements}
\cvarg{roots}{The output array of real roots which should have 3 elements}
\end{description}
The function finds the real roots of a cubic equation:
If coeffs is a 4-element vector:
\[
\texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
\]
or if coeffs is 3-element vector:
\[
x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
\]
The function returns the number of real roots found. The roots are
stored to \texttt{root} array, which is padded with zeros if there is
only one root.
\cvCPyFunc{Split}
Divides multi-channel array into several single-channel arrays or extracts a single channel from the array.
\cvdefC{void cvSplit(const CvArr* src, CvArr* dst0, CvArr* dst1,
CvArr* dst2, CvArr* dst3);}
\cvdefPy{Split(src,dst0,dst1,dst2,dst3)-> None}
\begin{description}
\cvarg{src}{Source array}
\cvarg{dst0}{Destination channel 0}
\cvarg{dst1}{Destination channel 1}
\cvarg{dst2}{Destination channel 2}
\cvarg{dst3}{Destination channel 3}
\end{description}
The function divides a multi-channel array into separate
single-channel arrays. Two modes are available for the operation. If the
source array has N channels then if the first N destination channels
are not NULL, they all are extracted from the source array;
if only a single destination channel of the first N is not NULL, this
particular channel is extracted; otherwise an error is raised. The rest
of the destination channels (beyond the first N) must always be NULL. For
IplImage \cvCPyCross{Copy} with COI set can be also used to extract a single
channel from the image.
\cvCPyFunc{Sqrt}
Calculates the square root.
\cvdefC{float cvSqrt(float value);}
\cvdefPy{Sqrt(value)-> float}
\begin{description}
\cvarg{value}{The input floating-point value}
\end{description}
The function calculates the square root of the argument. If the argument is negative, the result is not determined.
\cvCPyFunc{Sub}
Computes the per-element difference between two arrays.
\cvdefC{void cvSub(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{Sub(src1,src2,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function subtracts one array from another one:
\begin{lstlisting}
dst(I)=src1(I)-src2(I) if mask(I)!=0
\end{lstlisting}
All the arrays must have the same type, except the mask, and the same size (or ROI size).
For types that have limited range this operation is saturating.
\cvCPyFunc{SubRS}
Computes the difference between a scalar and an array.
\cvdefC{void cvSubRS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{SubRS(src,value,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{value}{Scalar to subtract from}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function subtracts every element of source array from a scalar:
\begin{lstlisting}
dst(I)=value-src(I) if mask(I)!=0
\end{lstlisting}
All the arrays must have the same type, except the mask, and the same size (or ROI size).
For types that have limited range this operation is saturating.
\cvCPyFunc{SubS}
Computes the difference between an array and a scalar.
\cvdefC{void cvSubS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{SubS(src,value,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{value}{Subtracted scalar}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function subtracts a scalar from every element of the source array:
\begin{lstlisting}
dst(I)=src(I)-value if mask(I)!=0
\end{lstlisting}
All the arrays must have the same type, except the mask, and the same size (or ROI size).
For types that have limited range this operation is saturating.
\cvCPyFunc{Sum}
Adds up array elements.
\cvdefC{CvScalar cvSum(const CvArr* arr);}
\cvdefPy{Sum(arr)-> CvScalar}
\begin{description}
\cvarg{arr}{The array}
\end{description}
The function calculates the sum \texttt{S} of array elements, independently for each channel:
\[ \sum_I \texttt{arr}(I)_c \]
If the array is \texttt{IplImage} and COI is set, the function processes the selected channel only and stores the sum to the first scalar component.
\cvCPyFunc{SVBkSb}
Performs singular value back substitution.
\cvdefC{
void cvSVBkSb(\par const CvArr* W,\par const CvArr* U,\par const CvArr* V,\par const CvArr* B,\par CvArr* X,\par int flags);}
\cvdefPy{SVBkSb(W,U,V,B,X,flags)-> None}
\begin{description}
\cvarg{W}{Matrix or vector of singular values}
\cvarg{U}{Left orthogonal matrix (tranposed, perhaps)}
\cvarg{V}{Right orthogonal matrix (tranposed, perhaps)}
\cvarg{B}{The matrix to multiply the pseudo-inverse of the original matrix \texttt{A} by. This is an optional parameter. If it is omitted then it is assumed to be an identity matrix of an appropriate size (so that \texttt{X} will be the reconstructed pseudo-inverse of \texttt{A}).}
\cvarg{X}{The destination matrix: result of back substitution}
\cvarg{flags}{Operation flags, should match exactly to the \texttt{flags} passed to \cvCPyCross{SVD}}
\end{description}
The function calculates back substitution for decomposed matrix \texttt{A} (see \cvCPyCross{SVD} description) and matrix \texttt{B}:
\[
\texttt{X} = \texttt{V} \texttt{W}^{-1} \texttt{U}^T \texttt{B}
\]
where
\[
W^{-1}_{(i,i)}=
\fork
{1/W_{(i,i)}}{if $W_{(i,i)} > \epsilon \sum_i{W_{(i,i)}}$ }
{0}{otherwise}
\]
and $\epsilon$ is a small number that depends on the matrix data type.
This function together with \cvCPyCross{SVD} is used inside \cvCPyCross{Invert}
and \cvCPyCross{Solve}, and the possible reason to use these (svd and bksb)
"low-level" function, is to avoid allocation of temporary matrices inside
the high-level counterparts (inv and solve).
\cvCPyFunc{SVD}
Performs singular value decomposition of a real floating-point matrix.
\cvdefC{void cvSVD(\par CvArr* A, \par CvArr* W, \par CvArr* U=NULL, \par CvArr* V=NULL, \par int flags=0);}
\cvdefPy{SVD(A,W, U = None, V = None, flags=0)-> None}
\begin{description}
\cvarg{A}{Source $\texttt{M} \times \texttt{N}$ matrix}
\cvarg{W}{Resulting singular value diagonal matrix ($\texttt{M} \times \texttt{N}$ or $\min(\texttt{M}, \texttt{N}) \times \min(\texttt{M}, \texttt{N})$) or $\min(\texttt{M},\texttt{N}) \times 1$ vector of the singular values}
\cvarg{U}{Optional left orthogonal matrix, $\texttt{M} \times \min(\texttt{M}, \texttt{N})$ (when \texttt{CV\_SVD\_U\_T} is not set), or $\min(\texttt{M},\texttt{N}) \times \texttt{M}$ (when \texttt{CV\_SVD\_U\_T} is set), or $\texttt{M} \times \texttt{M}$ (regardless of \texttt{CV\_SVD\_U\_T} flag).}
\cvarg{V}{Optional right orthogonal matrix, $\texttt{N} \times \min(\texttt{M}, \texttt{N})$ (when \texttt{CV\_SVD\_V\_T} is not set), or $\min(\texttt{M},\texttt{N}) \times \texttt{N}$ (when \texttt{CV\_SVD\_V\_T} is set), or $\texttt{N} \times \texttt{N}$ (regardless of \texttt{CV\_SVD\_V\_T} flag).}
\cvarg{flags}{Operation flags; can be 0 or a combination of the following values:
\begin{description}
\cvarg{CV\_SVD\_MODIFY\_A}{enables modification of matrix \texttt{A} during the operation. It speeds up the processing.}
\cvarg{CV\_SVD\_U\_T}{means that the transposed matrix \texttt{U} is returned. Specifying the flag speeds up the processing.}
\cvarg{CV\_SVD\_V\_T}{means that the transposed matrix \texttt{V} is returned. Specifying the flag speeds up the processing.}
\end{description}}
\end{description}
The function decomposes matrix \texttt{A} into the product of a diagonal matrix and two
orthogonal matrices:
\[
A=U \, W \, V^T
\]
where $W$ is a diagonal matrix of singular values that can be coded as a
1D vector of singular values and $U$ and $V$. All the singular values
are non-negative and sorted (together with $U$ and $V$ columns)
in descending order.
An SVD algorithm is numerically robust and its typical applications include:
\begin{itemize}
\item accurate eigenvalue problem solution when matrix \texttt{A}
is a square, symmetric, and positively defined matrix, for example, when
it is a covariance matrix. $W$ in this case will be a vector/matrix
of the eigenvalues, and $U = V$ will be a matrix of the eigenvectors.
\item accurate solution of a poor-conditioned linear system.
\item least-squares solution of an overdetermined linear system. This and the preceeding is done by using the \cvCPyCross{Solve} function with the \texttt{CV\_SVD} method.
\item accurate calculation of different matrix characteristics such as the matrix rank (the number of non-zero singular values), condition number (ratio of the largest singular value to the smallest one), and determinant (absolute value of the determinant is equal to the product of singular values).
\end{itemize}
\cvCPyFunc{Trace}
Returns the trace of a matrix.
\cvdefC{CvScalar cvTrace(const CvArr* mat);}
\cvdefPy{Trace(mat)-> CvScalar}
\begin{description}
\cvarg{mat}{The source matrix}
\end{description}
The function returns the sum of the diagonal elements of the matrix \texttt{src1}.
\[ tr(\texttt{mat}) = \sum_i \texttt{mat}(i,i) \]
\cvCPyFunc{Transform}
Performs matrix transformation of every array element.
\cvdefC{void cvTransform(const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL);}
\cvdefPy{Transform(src,dst,transmat,shiftvec=NULL)-> None}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{dst}{The destination array}
\cvarg{transmat}{Transformation matrix}
\cvarg{shiftvec}{Optional shift vector}
\end{description}
The function performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
\[
dst(I) = transmat \cdot src(I) + shiftvec % or dst(I),,k,,=sum,,j,,(transmat(k,j)*src(I),,j,,) + shiftvec(k)
\]
That is, every element of an \texttt{N}-channel array \texttt{src} is
considered as an \texttt{N}-element vector which is transformed using
a $\texttt{M} \times \texttt{N}$ matrix \texttt{transmat} and shift
vector \texttt{shiftvec} into an element of \texttt{M}-channel array
\texttt{dst}. There is an option to embedd \texttt{shiftvec} into
\texttt{transmat}. In this case \texttt{transmat} should be a $\texttt{M}
\times (N+1)$ matrix and the rightmost column is treated as the shift
vector.
Both source and destination arrays should have the same depth and the
same size or selected ROI size. \texttt{transmat} and \texttt{shiftvec}
should be real floating-point matrices.
The function may be used for geometrical transformation of n dimensional
point set, arbitrary linear color space transformation, shuffling the
channels and so forth.
\cvCPyFunc{Transpose}
Transposes a matrix.
\cvdefC{void cvTranspose(const CvArr* src, CvArr* dst);}
\cvdefPy{Transpose(src,dst)-> None}
\begin{description}
\cvarg{src}{The source matrix}
\cvarg{dst}{The destination matrix}
\end{description}
The function transposes matrix \texttt{src1}:
\[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
Note that no complex conjugation is done in the case of a complex
matrix. Conjugation should be done separately: look at the sample code
in \cvCPyCross{XorS} for an example.
\cvCPyFunc{Xor}
Performs per-element bit-wise "exclusive or" operation on two arrays.
\cvdefC{void cvXor(const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{Xor(src1,src2,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function calculates per-element bit-wise logical conjunction of two arrays:
\begin{lstlisting}
dst(I)=src1(I)^src2(I) if mask(I)!=0
\end{lstlisting}
In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size.
\cvCPyFunc{XorS}
Performs per-element bit-wise "exclusive or" operation on an array and a scalar.
\cvdefC{void cvXorS(const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL);}
\cvdefPy{XorS(src,value,dst,mask=NULL)-> None}
\begin{description}
\cvarg{src}{The source array}
\cvarg{value}{Scalar to use in the operation}
\cvarg{dst}{The destination array}
\cvarg{mask}{Operation mask, 8-bit single channel array; specifies elements of the destination array to be changed}
\end{description}
The function XorS calculates per-element bit-wise conjunction of an array and a scalar:
\begin{lstlisting}
dst(I)=src(I)^value if mask(I)!=0
\end{lstlisting}
Prior to the actual operation, the scalar is converted to the same type as that of the array(s). In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size
\ifC
The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:
\begin{lstlisting}
float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
CvMat A = cvMat(4, 1, CV\_32FC2, &a);
int i, negMask = 0x80000000;
cvXorS(&A, cvScalar(0, *(float*)&negMask, 0, 0 ), &A, 0);
for(i = 0; i < 4; i++ )
printf("(\%.1f, \%.1f) ", a[i*2], a[i*2+1]);
\end{lstlisting}
The code should print:
\begin{lstlisting}
(1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)
\end{lstlisting}
\fi
\cvCPyFunc{mGet}
Returns the particular element of single-channel floating-point matrix.
\cvdefC{double cvmGet(const CvMat* mat, int row, int col);}
\cvdefPy{mGet(mat,row,col)-> double}
\begin{description}
\cvarg{mat}{Input matrix}
\cvarg{row}{The zero-based index of row}
\cvarg{col}{The zero-based index of column}
\end{description}
The function is a fast replacement for \cvCPyCross{GetReal2D}
in the case of single-channel floating-point matrices. It is faster because
it is inline, it does fewer checks for array type and array element type,
and it checks for the row and column ranges only in debug mode.
\cvCPyFunc{mSet}
Returns a specific element of a single-channel floating-point matrix.
\cvdefC{void cvmSet(CvMat* mat, int row, int col, double value);}
\cvdefPy{mSet(mat,row,col,value)-> None}
\begin{description}
\cvarg{mat}{The matrix}
\cvarg{row}{The zero-based index of row}
\cvarg{col}{The zero-based index of column}
\cvarg{value}{The new value of the matrix element}
\end{description}
The function is a fast replacement for \cvCPyCross{SetReal2D}
in the case of single-channel floating-point matrices. It is faster because
it is inline, it does fewer checks for array type and array element type,
and it checks for the row and column ranges only in debug mode.
\fi
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% C++ API %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ifCpp
\cvCppFunc{abs}
Computes absolute value of each matrix element
\cvdefCpp{MatExpr<...> abs(const Mat\& src);\newline
MatExpr<...> abs(const MatExpr<...>\& src);}
\begin{description}
\cvarg{src}{matrix or matrix expression}
\end{description}
\texttt{abs} is a meta-function that is expanded to one of \cvCppCross{absdiff} forms:
\begin{itemize}
\item \texttt{C = abs(A-B)} is equivalent to \texttt{absdiff(A, B, C)} and
\item \texttt{C = abs(A)} is equivalent to \texttt{absdiff(A, Scalar::all(0), C)}.
\item \texttt{C = Mat\_<Vec<uchar,\emph{n}> >(abs(A*$\alpha$ + $\beta$))} is equivalent to \texttt{convertScaleAbs(A, C, alpha, beta)}
\end{itemize}
The output matrix will have the same size and the same type as the input one
(except for the last case, where \texttt{C} will be \texttt{depth=CV\_8U}).
See also: \cross{Matrix Expressions}, \cvCppCross{absdiff}, \hyperref[cppfunc.saturatecast]{saturate\_cast}
\cvCppFunc{absdiff}
Computes per-element absolute difference between 2 arrays or between array and a scalar.
\cvdefCpp{void absdiff(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
void absdiff(const Mat\& src1, const Scalar\& sc, Mat\& dst);\newline
void absdiff(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
void absdiff(const MatND\& src1, const Scalar\& sc, MatND\& dst);}
\begin{description}
\cvarg{src1}{The first input array}
\cvarg{src2}{The second input array; Must be the same size and same type as \texttt{src1}}
\cvarg{sc}{Scalar; the second input parameter}
\cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
\end{description}
The functions \texttt{absdiff} compute:
\begin{itemize}
\item absolute difference between two arrays
\[\texttt{dst}(I) = \texttt{saturate}(|\texttt{src1}(I) - \texttt{src2}(I)|)\]
\item or absolute difference between array and a scalar:
\[\texttt{dst}(I) = \texttt{saturate}(|\texttt{src1}(I) - \texttt{sc}|)\]
\end{itemize}
where \texttt{I} is multi-dimensional index of array elements.
in the case of multi-channel arrays each channel is processed independently.
See also: \cvCppCross{abs}, \hyperref[cppfunc.saturatecast]{saturate\_cast}
\cvCppFunc{add}
Computes the per-element sum of two arrays or an array and a scalar.
\cvdefCpp{void add(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
void add(const Mat\& src1, const Mat\& src2, \par Mat\& dst, const Mat\& mask);\newline
void add(const Mat\& src1, const Scalar\& sc, \par Mat\& dst, const Mat\& mask=Mat());\newline
void add(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
void add(const MatND\& src1, const MatND\& src2, \par MatND\& dst, const MatND\& mask);\newline
void add(const MatND\& src1, const Scalar\& sc, \par MatND\& dst, const MatND\& mask=MatND());}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
\cvarg{sc}{Scalar; the second input parameter}
\cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
\cvarg{mask}{The optional operation mask, 8-bit single channel array;
specifies elements of the destination array to be changed}
\end{description}
The functions \texttt{add} compute:
\begin{itemize}
\item the sum of two arrays:
\[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) + \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
\item or the sum of array and a scalar:
\[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) + \texttt{sc})\quad\texttt{if mask}(I)\ne0\]
\end{itemize}
where \texttt{I} is multi-dimensional index of array elements.
The first function in the above list can be replaced with matrix expressions:
\begin{lstlisting}
dst = src1 + src2;
dst += src1; // equivalent to add(dst, src1, dst);
\end{lstlisting}
in the case of multi-channel arrays each channel is processed independently.
See also: \cvCppCross{subtract}, \cvCppCross{addWeighted}, \cvCppCross{scaleAdd}, \cvCppCross{convertScale},
\cross{Matrix Expressions}, \hyperref[cppfunc.saturatecast]{saturate\_cast}.
\cvCppFunc{addWeighted}
Computes the weighted sum of two arrays.
\cvdefCpp{void addWeighted(const Mat\& src1, double alpha, const Mat\& src2,\par
double beta, double gamma, Mat\& dst);\newline
void addWeighted(const MatND\& src1, double alpha, const MatND\& src2,\par
double beta, double gamma, MatND\& dst);
}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{alpha}{Weight for the first array elements}
\cvarg{src2}{The second source array; must have the same size and same type as \texttt{src1}}
\cvarg{beta}{Weight for the second array elements}
\cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}}
\cvarg{gamma}{Scalar, added to each sum}
\end{description}
The functions \texttt{addWeighted} calculate the weighted sum of two arrays as follows:
\[\texttt{dst}(I)=\texttt{saturate}(\texttt{src1}(I)*\texttt{alpha} + \texttt{src2}(I)*\texttt{beta} + \texttt{gamma})\]
where \texttt{I} is multi-dimensional index of array elements.
The first function can be replaced with a matrix expression:
\begin{lstlisting}
dst = src1*alpha + src2*beta + gamma;
\end{lstlisting}
In the case of multi-channel arrays each channel is processed independently.
See also: \cvCppCross{add}, \cvCppCross{subtract}, \cvCppCross{scaleAdd}, \cvCppCross{convertScale},
\cross{Matrix Expressions}, \hyperref[cppfunc.saturatecast]{saturate\_cast}.
\cvfunc{bitwise\_and}\label{cppfunc.bitwise.and}
Calculates per-element bit-wise conjunction of two arrays and an array and a scalar.
\cvdefCpp{void bitwise\_and(const Mat\& src1, const Mat\& src2,\par Mat\& dst, const Mat\& mask=Mat());\newline
void bitwise\_and(const Mat\& src1, const Scalar\& sc,\par Mat\& dst, const Mat\& mask=Mat());\newline
void bitwise\_and(const MatND\& src1, const MatND\& src2,\par MatND\& dst, const MatND\& mask=MatND());\newline
void bitwise\_and(const MatND\& src1, const Scalar\& sc,\par MatND\& dst, const MatND\& mask=MatND());}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
\cvarg{sc}{Scalar; the second input parameter}
\cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
\cvarg{mask}{The optional operation mask, 8-bit single channel array;
specifies elements of the destination array to be changed}
\end{description}
The functions \texttt{bitwise\_and} compute per-element bit-wise logical conjunction:
\begin{itemize}
\item of two arrays
\[\texttt{dst}(I) = \texttt{src1}(I) \wedge \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
\item or array and a scalar:
\[\texttt{dst}(I) = \texttt{src1}(I) \wedge \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
\end{itemize}
In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation, and in the case of multi-channel arrays each channel is processed independently.
See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.not]{bitwise\_not}, \hyperref[cppfunc.bitwise.xor]{bitwise\_xor}
\cvfunc{bitwise\_not}\label{cppfunc.bitwise.not}
Inverts every bit of array
\cvdefCpp{void bitwise\_not(const Mat\& src, Mat\& dst);\newline
void bitwise\_not(const MatND\& src, MatND\& dst);}
\begin{description}
\cvarg{src1}{The source array}
\cvarg{dst}{The destination array; it is reallocated to be of the same size and
the same type as \texttt{src}; see \texttt{Mat::create}}
\cvarg{mask}{The optional operation mask, 8-bit single channel array;
specifies elements of the destination array to be changed}
\end{description}
The functions \texttt{bitwise\_not} compute per-element bit-wise inversion of the source array:
\[\texttt{dst}(I) = \neg\texttt{src}(I)\]
In the case of floating-point source array its machine-specific bit representation (usually IEEE754-compliant) is used for the operation. in the case of multi-channel arrays each channel is processed independently.
See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.or]{bitwise\_or}, \hyperref[cppfunc.bitwise.xor]{bitwise\_xor}
\cvfunc{bitwise\_or}\label{cppfunc.bitwise.or}
Calculates per-element bit-wise disjunction of two arrays and an array and a scalar.
\cvdefCpp{void bitwise\_or(const Mat\& src1, const Mat\& src2,\par Mat\& dst, const Mat\& mask=Mat());\newline
void bitwise\_or(const Mat\& src1, const Scalar\& sc,\par Mat\& dst, const Mat\& mask=Mat());\newline
void bitwise\_or(const MatND\& src1, const MatND\& src2,\par MatND\& dst, const MatND\& mask=MatND());\newline
void bitwise\_or(const MatND\& src1, const Scalar\& sc,\par MatND\& dst, const MatND\& mask=MatND());}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
\cvarg{sc}{Scalar; the second input parameter}
\cvarg{dst}{The destination array; it is reallocated to be of the same size and
the same type as \texttt{src1}; see \texttt{Mat::create}}
\cvarg{mask}{The optional operation mask, 8-bit single channel array;
specifies elements of the destination array to be changed}
\end{description}
The functions \texttt{bitwise\_or} compute per-element bit-wise logical disjunction
\begin{itemize}
\item of two arrays
\[\texttt{dst}(I) = \texttt{src1}(I) \vee \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
\item or array and a scalar:
\[\texttt{dst}(I) = \texttt{src1}(I) \vee \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
\end{itemize}
In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. in the case of multi-channel arrays each channel is processed independently.
See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.not]{bitwise\_not}, \hyperref[cppfunc.bitwise.or]{bitwise\_or}
\cvfunc{bitwise\_xor}\label{cppfunc.bitwise.xor}
Calculates per-element bit-wise "exclusive or" operation on two arrays and an array and a scalar.
\cvdefCpp{void bitwise\_xor(const Mat\& src1, const Mat\& src2,\par Mat\& dst, const Mat\& mask=Mat());\newline
void bitwise\_xor(const Mat\& src1, const Scalar\& sc,\par Mat\& dst, const Mat\& mask=Mat());\newline
void bitwise\_xor(const MatND\& src1, const MatND\& src2,\par MatND\& dst, const MatND\& mask=MatND());\newline
void bitwise\_xor(const MatND\& src1, const Scalar\& sc,\par MatND\& dst, const MatND\& mask=MatND());}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
\cvarg{sc}{Scalar; the second input parameter}
\cvarg{dst}{The destination array; it is reallocated to be of the same size and
the same type as \texttt{src1}; see \texttt{Mat::create}}
\cvarg{mask}{The optional operation mask, 8-bit single channel array;
specifies elements of the destination array to be changed}
\end{description}
The functions \texttt{bitwise\_xor} compute per-element bit-wise logical "exclusive or" operation
\begin{itemize}
\item on two arrays
\[\texttt{dst}(I) = \texttt{src1}(I) \oplus \texttt{src2}(I)\quad\texttt{if mask}(I)\ne0\]
\item or array and a scalar:
\[\texttt{dst}(I) = \texttt{src1}(I) \oplus \texttt{sc}\quad\texttt{if mask}(I)\ne0\]
\end{itemize}
In the case of floating-point arrays their machine-specific bit representations (usually IEEE754-compliant) are used for the operation. in the case of multi-channel arrays each channel is processed independently.
See also: \hyperref[cppfunc.bitwise.and]{bitwise\_and}, \hyperref[cppfunc.bitwise.not]{bitwise\_not}, \hyperref[cppfunc.bitwise.or]{bitwise\_or}
\cvCppFunc{calcCovarMatrix}
Calculates covariation matrix of a set of vectors
\cvdefCpp{void calcCovarMatrix( const Mat* samples, int nsamples,\par
Mat\& covar, Mat\& mean,\par
int flags, int ctype=CV\_64F);\newline
void calcCovarMatrix( const Mat\& samples, Mat\& covar, Mat\& mean,\par
int flags, int ctype=CV\_64F);}
\begin{description}
\cvarg{samples}{The samples, stored as separate matrices, or as rows or columns of a single matrix}
\cvarg{nsamples}{The number of samples when they are stored separately}
\cvarg{covar}{The output covariance matrix; it will have type=\texttt{ctype} and square size}
\cvarg{mean}{The input or output (depending on the flags) array - the mean (average) vector of the input vectors}
\cvarg{flags}{The operation flags, a combination of the following values
\begin{description}
\cvarg{CV\_COVAR\_SCRAMBLED}{The output covariance matrix is calculated as:
\[
\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} ,\texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [\texttt{vects} [0]-\texttt{mean} ,\texttt{vects} [1]-\texttt{mean} ,...]
\],
that is, the covariance matrix will be $\texttt{nsamples} \times \texttt{nsamples}$.
Such an unusual covariance matrix is used for fast PCA
of a set of very large vectors (see, for example, the EigenFaces technique
for face recognition). Eigenvalues of this "scrambled" matrix will
match the eigenvalues of the true covariance matrix and the "true"
eigenvectors can be easily calculated from the eigenvectors of the
"scrambled" covariance matrix.}
\cvarg{CV\_COVAR\_NORMAL}{The output covariance matrix is calculated as:
\[
\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} ,\texttt{vects} [1]- \texttt{mean} ,...] \cdot [\texttt{vects} [0]-\texttt{mean} ,\texttt{vects} [1]-\texttt{mean} ,...]^T
\],
that is, \texttt{covar} will be a square matrix
of the same size as the total number of elements in each
input vector. One and only one of \texttt{CV\_COVAR\_SCRAMBLED} and
\texttt{CV\_COVAR\_NORMAL} must be specified}
\cvarg{CV\_COVAR\_USE\_AVG}{If the flag is specified, the function does not calculate \texttt{mean} from the input vectors, but, instead, uses the passed \texttt{mean} vector. This is useful if \texttt{mean} has been pre-computed or known a-priori, or if the covariance matrix is calculated by parts - in this case, \texttt{mean} is not a mean vector of the input sub-set of vectors, but rather the mean vector of the whole set.}
\cvarg{CV\_COVAR\_SCALE}{If the flag is specified, the covariance matrix is scaled. In the "normal" mode \texttt{scale} is \texttt{1./nsamples}; in the "scrambled" mode \texttt{scale} is the reciprocal of the total number of elements in each input vector. By default (if the flag is not specified) the covariance matrix is not scaled (i.e. \texttt{scale=1}).}
\cvarg{CV\_COVAR\_ROWS}{[Only useful in the second variant of the function] The flag means that all the input vectors are stored as rows of the \texttt{samples} matrix. \texttt{mean} should be a single-row vector in this case.}
\cvarg{CV\_COVAR\_COLS}{[Only useful in the second variant of the function] The flag means that all the input vectors are stored as columns of the \texttt{samples} matrix. \texttt{mean} should be a single-column vector in this case.}
\end{description}}
\end{description}
The functions \texttt{calcCovarMatrix} calculate the covariance matrix
and, optionally, the mean vector of the set of input vectors.
See also: \cvCppCross{PCA}, \cvCppCross{mulTransposed}, \cvCppCross{Mahalanobis}
\cvCppFunc{cartToPolar}
Calculates the magnitude and angle of 2d vectors.
\cvdefCpp{void cartToPolar(const Mat\& x, const Mat\& y,\par
Mat\& magnitude, Mat\& angle,\par
bool angleInDegrees=false);}
\begin{description}
\cvarg{x}{The array of x-coordinates; must be single-precision or double-precision floating-point array}
\cvarg{y}{The array of y-coordinates; it must have the same size and same type as \texttt{x}}
\cvarg{magnitude}{The destination array of magnitudes of the same size and same type as \texttt{x}}
\cvarg{angle}{The destination array of angles of the same size and same type as \texttt{x}.
The angles are measured in radians $(0$ to $2 \pi )$ or in degrees (0 to 360 degrees).}
\cvarg{angleInDegrees}{The flag indicating whether the angles are measured in radians, which is default mode, or in degrees}
\end{description}
The function \texttt{cartToPolar} calculates either the magnitude, angle, or both of every 2d vector (x(I),y(I)):
\[
\begin{array}{l}
\texttt{magnitude}(I)=\sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2},\\
\texttt{angle}(I)=\texttt{atan2}(\texttt{y}(I), \texttt{x}(I))[\cdot180/\pi]
\end{array}
\]
The angles are calculated with $\sim\,0.3^\circ$ accuracy. For the (0,0) point, the angle is set to 0.
\cvCppFunc{checkRange}
Checks every element of an input array for invalid values.
\cvdefCpp{bool checkRange(const Mat\& src, bool quiet=true, Point* pos=0,\par
double minVal=-DBL\_MAX, double maxVal=DBL\_MAX);\newline
bool checkRange(const MatND\& src, bool quiet=true, int* pos=0,\par
double minVal=-DBL\_MAX, double maxVal=DBL\_MAX);}
\begin{description}
\cvarg{src}{The array to check}
\cvarg{quiet}{The flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.}
\cvarg{pos}{The optional output parameter, where the position of the first outlier is stored. In the second function \texttt{pos}, when not NULL, must be a pointer to array of \texttt{src.dims} elements}
\cvarg{minVal}{The inclusive lower boundary of valid values range}
\cvarg{maxVal}{The exclusive upper boundary of valid values range}
\end{description}
The functions \texttt{checkRange} check that every array element is
neither NaN nor $\pm \infty $. When \texttt{minVal < -DBL\_MAX} and \texttt{maxVal < DBL\_MAX}, then the functions also check that
each value is between \texttt{minVal} and \texttt{maxVal}. in the case of multi-channel arrays each channel is processed independently.
If some values are out of range, position of the first outlier is stored in \texttt{pos} (when $\texttt{pos}\ne0$), and then the functions either return false (when \texttt{quiet=true}) or throw an exception.
\cvCppFunc{compare}
Performs per-element comparison of two arrays or an array and scalar value.
\cvdefCpp{void compare(const Mat\& src1, const Mat\& src2, Mat\& dst, int cmpop);\newline
void compare(const Mat\& src1, double value, \par Mat\& dst, int cmpop);\newline
void compare(const MatND\& src1, const MatND\& src2, \par MatND\& dst, int cmpop);\newline
void compare(const MatND\& src1, double value, \par MatND\& dst, int cmpop);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array; must have the same size and same type as \texttt{src1}}
\cvarg{value}{The scalar value to compare each array element with}
\cvarg{dst}{The destination array; will have the same size as \texttt{src1} and type=\texttt{CV\_8UC1}}
\cvarg{cmpop}{The flag specifying the relation between the elements to be checked
\begin{description}
\cvarg{CMP\_EQ}{$\texttt{src1}(I) = \texttt{src2}(I)$ or $\texttt{src1}(I) = \texttt{value}$}
\cvarg{CMP\_GT}{$\texttt{src1}(I) > \texttt{src2}(I)$ or $\texttt{src1}(I) > \texttt{value}$}
\cvarg{CMP\_GE}{$\texttt{src1}(I) \geq \texttt{src2}(I)$ or $\texttt{src1}(I) \geq \texttt{value}$}
\cvarg{CMP\_LT}{$\texttt{src1}(I) < \texttt{src2}(I)$ or $\texttt{src1}(I) < \texttt{value}$}
\cvarg{CMP\_LE}{$\texttt{src1}(I) \leq \texttt{src2}(I)$ or $\texttt{src1}(I) \leq \texttt{value}$}
\cvarg{CMP\_NE}{$\texttt{src1}(I) \ne \texttt{src2}(I)$ or $\texttt{src1}(I) \ne \texttt{value}$}
\end{description}}
\end{description}
The functions \texttt{compare} compare each element of \texttt{src1} with the corresponding element of \texttt{src2}
or with real scalar \texttt{value}. When the comparison result is true, the corresponding element of destination array is set to 255, otherwise it is set to 0:
\begin{itemize}
\item \texttt{dst(I) = src1(I) cmpop src2(I) ? 255 : 0}
\item \texttt{dst(I) = src1(I) cmpop value ? 255 : 0}
\end{itemize}
The comparison operations can be replaced with the equivalent matrix expressions:
\begin{lstlisting}
Mat dst1 = src1 >= src2;
Mat dst2 = src1 < 8;
...
\end{lstlisting}
See also: \cvCppCross{checkRange}, \cvCppCross{min}, \cvCppCross{max}, \cvCppCross{threshold}, \cross{Matrix Expressions}
\cvCppFunc{completeSymm}
Copies the lower or the upper half of a square matrix to another half.
\cvdefCpp{void completeSymm(Mat\& mtx, bool lowerToUpper=false);}
\begin{description}
\cvarg{mtx}{Input-output floating-point square matrix}
\cvarg{lowerToUpper}{If true, the lower half is copied to the upper half, otherwise the upper half is copied to the lower half}
\end{description}
The function \texttt{completeSymm} copies the lower half of a square matrix to its another half; the matrix diagonal remains unchanged:
\begin{itemize}
\item $\texttt{mtx}_{ij}=\texttt{mtx}_{ji}$ for $i > j$ if \texttt{lowerToUpper=false}
\item $\texttt{mtx}_{ij}=\texttt{mtx}_{ji}$ for $i < j$ if \texttt{lowerToUpper=true}
\end{itemize}
See also: \cvCppCross{flip}, \cvCppCross{transpose}
\cvCppFunc{convertScaleAbs}
Scales, computes absolute values and converts the result to 8-bit.
\cvdefCpp{void convertScaleAbs(const Mat\& src, Mat\& dst, double alpha=1, double beta=0);}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array}
\cvarg{alpha}{The optional scale factor}
\cvarg{beta}{The optional delta added to the scaled values}
\end{description}
On each element of the input array the function \texttt{convertScaleAbs} performs 3 operations sequentially: scaling, taking absolute value, conversion to unsigned 8-bit type:
\[\texttt{dst}(I)=\texttt{saturate\_cast<uchar>}(|\texttt{src}(I)*\texttt{alpha} + \texttt{beta}|)\]
in the case of multi-channel arrays the function processes each channel independently. When the output is not 8-bit, the operation can be emulated by calling \texttt{Mat::convertTo} method (or by using matrix expressions) and then by computing absolute value of the result, for example:
\begin{lstlisting}
Mat_<float> A(30,30);
randu(A, Scalar(-100), Scalar(100));
Mat_<float> B = A*5 + 3;
B = abs(B);
// Mat_<float> B = abs(A*5+3) will also do the job,
// but it will allocate a temporary matrix
\end{lstlisting}
See also: \cvCppCross{Mat::convertTo}, \cvCppCross{abs}
\cvCppFunc{countNonZero}
Counts non-zero array elements.
\cvdefCpp{int countNonZero( const Mat\& mtx );\newline
int countNonZero( const MatND\& mtx );}
\begin{description}
\cvarg{mtx}{Single-channel array}
\end{description}
The function \texttt{cvCountNonZero} returns the number of non-zero elements in mtx:
\[ \sum_{I:\;\texttt{mtx}(I)\ne0} 1 \]
See also: \cvCppCross{mean}, \cvCppCross{meanStdDev}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}, \cvCppCross{calcCovarMatrix}
\cvCppFunc{cubeRoot}
Computes cube root of the argument
\cvdefCpp{float cubeRoot(float val);}
\begin{description}
\cvarg{val}{The function argument}
\end{description}
The function \texttt{cubeRoot} computes $\sqrt[3]{\texttt{val}}$.
Negative arguments are handled correctly, \emph{NaN} and $\pm\infty$ are not handled.
The accuracy approaches the maximum possible accuracy for single-precision data.
\cvCppFunc{cvarrToMat}
Converts CvMat, IplImage or CvMatND to cv::Mat.
\cvdefCpp{Mat cvarrToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0);}
\begin{description}
\cvarg{src}{The source \texttt{CvMat}, \texttt{IplImage} or \texttt{CvMatND}}
\cvarg{copyData}{When it is false (default value), no data is copied, only the new header is created.
In this case the original array should not be deallocated while the new matrix header is used. The the parameter is true, all the data is copied, then user may deallocate the original array right after the conversion}
\cvarg{allowND}{When it is true (default value), then \texttt{CvMatND} is converted to \texttt{Mat} if it's possible
(e.g. then the data is contiguous). If it's not possible, or when the parameter is false, the function will report an error}
\cvarg{coiMode}{The parameter specifies how the IplImage COI (when set) is handled.
\begin{itemize}
\item If \texttt{coiMode=0}, the function will report an error if COI is set.
\item If \texttt{coiMode=1}, the function will never report an error; instead it returns the header to the whole original image and user will have to check and process COI manually, see \cvCppCross{extractImageCOI}.
% \item If \texttt{coiMode=2}, the function will extract the COI into the separate matrix. \emph{This is also done when the COI is set and }\texttt{copyData=true}}
\end{itemize}}
\end{description}
The function \texttt{cvarrToMat} converts \cross{CvMat}, \cross{IplImage} or \cross{CvMatND} header to \cvCppCross{Mat} header, and optionally duplicates the underlying data. The constructed header is returned by the function.
When \texttt{copyData=false}, the conversion is done really fast (in O(1) time) and the newly created matrix header will have \texttt{refcount=0}, which means that no reference counting is done for the matrix data, and user has to preserve the data until the new header is destructed. Otherwise, when \texttt{copyData=true}, the new buffer will be allocated and managed as if you created a new matrix from scratch and copy the data there. That is,
\texttt{cvarrToMat(src, true) $\sim$ cvarrToMat(src, false).clone()} (assuming that COI is not set). The function provides uniform way of supporting \cross{CvArr} paradigm in the code that is migrated to use new-style data structures internally. The reverse transformation, from \cvCppCross{Mat} to \cross{CvMat} or \cross{IplImage} can be done by simple assignment:
\begin{lstlisting}
CvMat* A = cvCreateMat(10, 10, CV_32F);
cvSetIdentity(A);
IplImage A1; cvGetImage(A, &A1);
Mat B = cvarrToMat(A);
Mat B1 = cvarrToMat(&A1);
IplImage C = B;
CvMat C1 = B1;
// now A, A1, B, B1, C and C1 are different headers
// for the same 10x10 floating-point array.
// note, that you will need to use "&"
// to pass C & C1 to OpenCV functions, e.g:
printf("%g", cvDet(&C1));
\end{lstlisting}
Normally, the function is used to convert an old-style 2D array (\cross{CvMat} or \cross{IplImage}) to \texttt{Mat}, however, the function can also take \cross{CvMatND} on input and create \cvCppCross{Mat} for it, if it's possible. And for \texttt{CvMatND A} it is possible if and only if \texttt{A.dim[i].size*A.dim.step[i] == A.dim.step[i-1]} for all or for all but one \texttt{i, 0 < i < A.dims}. That is, the matrix data should be continuous or it should be representable as a sequence of continuous matrices. By using this function in this way, you can process \cross{CvMatND} using arbitrary element-wise function. But for more complex operations, such as filtering functions, it will not work, and you need to convert \cross{CvMatND} to \cvCppCross{MatND} using the corresponding constructor of the latter.
The last parameter, \texttt{coiMode}, specifies how to react on an image with COI set: by default it's 0, and then the function reports an error when an image with COI comes in. And \texttt{coiMode=1} means that no error is signaled - user has to check COI presence and handle it manually. The modern structures, such as \cvCppCross{Mat} and \cvCppCross{MatND} do not support COI natively. To process individual channel of an new-style array, you will need either to organize loop over the array (e.g. using matrix iterators) where the channel of interest will be processed, or extract the COI using \cvCppCross{mixChannels} (for new-style arrays) or \cvCppCross{extractImageCOI} (for old-style arrays), process this individual channel and insert it back to the destination array if need (using \cvCppCross{mixChannel} or \cvCppCross{insertImageCOI}, respectively).
See also: \cvCppCross{cvGetImage}, \cvCppCross{cvGetMat}, \cvCppCross{cvGetMatND}, \cvCppCross{extractImageCOI}, \cvCppCross{insertImageCOI}, \cvCppCross{mixChannels}
\cvCppFunc{dct}
Performs a forward or inverse discrete cosine transform of 1D or 2D array
\cvdefCpp{void dct(const Mat\& src, Mat\& dst, int flags=0);}
\begin{description}
\cvarg{src}{The source floating-point array}
\cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
\cvarg{flags}{Transformation flags, a combination of the following values
\begin{description}
\cvarg{DCT\_INVERSE}{do an inverse 1D or 2D transform instead of the default forward transform.}
\cvarg{DCT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
\end{description}}
\end{description}
The function \texttt{dct} performs a forward or inverse discrete cosine transform (DCT) of a 1D or 2D floating-point array:
Forward Cosine transform of 1D vector of $N$ elements:
\[Y = C^{(N)} \cdot X\]
where
\[C^{(N)}_{jk}=\sqrt{\alpha_j/N}\cos\left(\frac{\pi(2k+1)j}{2N}\right)\]
and $\alpha_0=1$, $\alpha_j=2$ for $j > 0$.
Inverse Cosine transform of 1D vector of N elements:
\[X = \left(C^{(N)}\right)^{-1} \cdot Y = \left(C^{(N)}\right)^T \cdot Y\]
(since $C^{(N)}$ is orthogonal matrix, $C^{(N)} \cdot \left(C^{(N)}\right)^T = I$)
Forward Cosine transform of 2D $M \times N$ matrix:
\[Y = C^{(N)} \cdot X \cdot \left(C^{(N)}\right)^T\]
Inverse Cosine transform of 2D vector of $M \times N$ elements:
\[X = \left(C^{(N)}\right)^T \cdot X \cdot C^{(N)}\]
The function chooses the mode of operation by looking at the flags and size of the input array:
\begin{itemize}
\item if \texttt{(flags \& DCT\_INVERSE) == 0}, the function does forward 1D or 2D transform, otherwise it is inverse 1D or 2D transform.
\item if \texttt{(flags \& DCT\_ROWS) $\ne$ 0}, the function performs 1D transform of each row.
\item otherwise, if the array is a single column or a single row, the function performs 1D transform
\item otherwise it performs 2D transform.
\end{itemize}
\textbf{Important note}: currently cv::dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation you can pad the array when necessary.
Also, the function's performance depends very much, and not monotonically, on the array size, see \cvCppCross{getOptimalDFTSize}. In the current implementation DCT of a vector of size \texttt{N} is computed via DFT of a vector of size \texttt{N/2}, thus the optimal DCT size $\texttt{N}^*\geq\texttt{N}$ can be computed as:
\begin{lstlisting}
size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
\end{lstlisting}
See also: \cvCppCross{dft}, \cvCppCross{getOptimalDFTSize}, \cvCppCross{idct}
\cvCppFunc{dft}
Performs a forward or inverse Discrete Fourier transform of 1D or 2D floating-point array.
\cvdefCpp{void dft(const Mat\& src, Mat\& dst, int flags=0, int nonzeroRows=0);}
\begin{description}
\cvarg{src}{The source array, real or complex}
\cvarg{dst}{The destination array, which size and type depends on the \texttt{flags}}
\cvarg{flags}{Transformation flags, a combination of the following values
\begin{description}
\cvarg{DFT\_INVERSE}{do an inverse 1D or 2D transform instead of the default forward transform.}
\cvarg{DFT\_SCALE}{scale the result: divide it by the number of array elements. Normally, it is combined with \texttt{DFT\_INVERSE}}.
\cvarg{DFT\_ROWS}{do a forward or inverse transform of every individual row of the input matrix. This flag allows the user to transform multiple vectors simultaneously and can be used to decrease the overhead (which is sometimes several times larger than the processing itself), to do 3D and higher-dimensional transforms and so forth.}
\cvarg{DFT\_COMPLEX\_OUTPUT}{then the function performs forward transformation of 1D or 2D real array, the result, though being a complex array, has complex-conjugate symmetry (\emph{CCS}), see the description below. Such an array can be packed into real array of the same size as input, which is the fastest option and which is what the function does by default. However, you may wish to get the full complex array (for simpler spectrum analysis etc.). Pass the flag to tell the function to produce full-size complex output array.}
\cvarg{DFT\_REAL\_OUTPUT}{then the function performs inverse transformation of 1D or 2D complex array, the result is normally a complex array of the same size. However, if the source array has conjugate-complex symmetry (for example, it is a result of forward transformation with \texttt{DFT\_COMPLEX\_OUTPUT} flag), then the output is real array. While the function itself does not check whether the input is symmetrical or not, you can pass the flag and then the function will assume the symmetry and produce the real output array. Note that when the input is packed real array and inverse transformation is executed, the function treats the input as packed complex-conjugate symmetrical array, so the output will also be real array}
\end{description}}
\cvarg{nonzeroRows}{When the parameter $\ne 0$, the function assumes that only the first \texttt{nonzeroRows} rows of the input array (\texttt{DFT\_INVERSE} is not set) or only the first \texttt{nonzeroRows} of the output array (\texttt{DFT\_INVERSE} is set) contain non-zeros, thus the function can handle the rest of the rows more efficiently and thus save some time. This technique is very useful for computing array cross-correlation or convolution using DFT}
\end{description}
Forward Fourier transform of 1D vector of N elements:
\[Y = F^{(N)} \cdot X,\]
where $F^{(N)}_{jk}=\exp(-2\pi i j k/N)$ and $i=\sqrt{-1}$
Inverse Fourier transform of 1D vector of N elements:
\[
\begin{array}{l}
X'= \left(F^{(N)}\right)^{-1} \cdot Y = \left(F^{(N)}\right)^* \cdot y \\
X = (1/N) \cdot X,
\end{array}
\]
where $F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T$
Forward Fourier transform of 2D vector of $M \times N$ elements:
\[Y = F^{(M)} \cdot X \cdot F^{(N)}\]
Inverse Fourier transform of 2D vector of $M \times N$ elements:
\[
\begin{array}{l}
X'= \left(F^{(M)}\right)^* \cdot Y \cdot \left(F^{(N)}\right)^*\\
X = \frac{1}{M \cdot N} \cdot X'
\end{array}
\]
In the case of real (single-channel) data, the packed format called \emph{CCS} (complex-conjugate-symmetrical) that was borrowed from IPL and used to represent the result of a forward Fourier transform or input for an inverse Fourier transform:
\[\begin{bmatrix}
Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\
Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\
Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\
\hdotsfor{9} \\
Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\
Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\
Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2}
\end{bmatrix}
\]
in the case of 1D transform of real vector, the output will look as the first row of the above matrix.
So, the function chooses the operation mode depending on the flags and size of the input array:
\begin{itemize}
\item if \texttt{DFT\_ROWS} is set or the input array has single row or single column then the function performs 1D forward or inverse transform (of each row of a matrix when \texttt{DFT\_ROWS} is set, otherwise it will be 2D transform.
\item if input array is real and \texttt{DFT\_INVERSE} is not set, the function does forward 1D or 2D transform:
\begin{itemize}
\item when \texttt{DFT\_COMPLEX\_OUTPUT} is set then the output will be complex matrix of the same size as input.
\item otherwise the output will be a real matrix of the same size as input. in the case of 2D transform it will use the packed format as shown above; in the case of single 1D transform it will look as the first row of the above matrix; in the case of multiple 1D transforms (when using \texttt{DCT\_ROWS} flag) each row of the output matrix will look like the first row of the above matrix.
\end{itemize}
\item otherwise, if the input array is complex and either \texttt{DFT\_INVERSE} or \texttt{DFT\_REAL\_OUTPUT} are not set then the output will be a complex array of the same size as input and the function will perform the forward or inverse 1D or 2D transform of the whole input array or each row of the input array independently, depending on the flags \texttt{DFT\_INVERSE} and \texttt{DFT\_ROWS}.
\item otherwise, i.e. when \texttt{DFT\_INVERSE} is set, the input array is real, or it is complex but \texttt{DFT\_REAL\_OUTPUT} is set, the output will be a real array of the same size as input, and the function will perform 1D or 2D inverse transformation of the whole input array or each individual row, depending on the flags \texttt{DFT\_INVERSE} and \texttt{DFT\_ROWS}.
\end{itemize}
The scaling is done after the transformation if \texttt{DFT\_SCALE} is set.
Unlike \cvCppCross{dct}, the function supports arrays of arbitrary size, but only those arrays are processed efficiently, which sizes can be factorized in a product of small prime numbers (2, 3 and 5 in the current implementation). Such an efficient DFT size can be computed using \cvCppCross{getOptimalDFTSize} method.
Here is the sample on how to compute DFT-based convolution of two 2D real arrays:
\begin{lstlisting}
void convolveDFT(const Mat& A, const Mat& B, Mat& C)
{
// reallocate the output array if needed
C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
Size dftSize;
// compute the size of DFT transform
dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
// allocate temporary buffers and initialize them with 0's
Mat tempA(dftSize, A.type(), Scalar::all(0));
Mat tempB(dftSize, B.type(), Scalar::all(0));
// copy A and B to the top-left corners of tempA and tempB, respectively
Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
A.copyTo(roiA);
Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
B.copyTo(roiB);
// now transform the padded A & B in-place;
// use "nonzeroRows" hint for faster processing
dft(tempA, tempA, 0, A.rows);
dft(tempB, tempB, 0, B.rows);
// multiply the spectrums;
// the function handles packed spectrum representations well
mulSpectrums(tempA, tempB, tempA);
// transform the product back from the frequency domain.
// Even though all the result rows will be non-zero,
// we need only the first C.rows of them, and thus we
// pass nonzeroRows == C.rows
dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
// now copy the result back to C.
tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
// all the temporary buffers will be deallocated automatically
}
\end{lstlisting}
What can be optimized in the above sample?
\begin{itemize}
\item since we passed $\texttt{nonzeroRows} \ne 0$ to the forward transform calls and
since we copied \texttt{A}/\texttt{B} to the top-left corners of \texttt{tempA}/\texttt{tempB}, respectively,
it's not necessary to clear the whole \texttt{tempA} and \texttt{tempB};
it is only necessary to clear the \texttt{tempA.cols - A.cols} (\texttt{tempB.cols - B.cols})
rightmost columns of the matrices.
\item this DFT-based convolution does not have to be applied to the whole big arrays,
especially if \texttt{B} is significantly smaller than \texttt{A} or vice versa.
Instead, we can compute convolution by parts. For that we need to split the destination array
\texttt{C} into multiple tiles and for each tile estimate, which parts of \texttt{A} and \texttt{B}
are required to compute convolution in this tile. If the tiles in \texttt{C} are too small,
the speed will decrease a lot, because of repeated work - in the ultimate case, when each tile in \texttt{C} is a single pixel,
the algorithm becomes equivalent to the naive convolution algorithm.
If the tiles are too big, the temporary arrays \texttt{tempA} and \texttt{tempB} become too big
and there is also slowdown because of bad cache locality. So there is optimal tile size somewhere in the middle.
\item if the convolution is done by parts, since different tiles in \texttt{C} can be computed in parallel, the loop can be threaded.
\end{itemize}
All of the above improvements have been implemented in \cvCppCross{matchTemplate} and \cvCppCross{filter2D}, therefore, by using them, you can get even better performance than with the above theoretically optimal implementation (though, those two functions actually compute cross-correlation, not convolution, so you will need to "flip" the kernel or the image around the center using \cvCppCross{flip}).
See also: \cvCppCross{dct}, \cvCppCross{getOptimalDFTSize}, \cvCppCross{mulSpectrums}, \cvCppCross{filter2D}, \cvCppCross{matchTemplate}, \cvCppCross{flip}, \cvCppCross{cartToPolar}, \cvCppCross{magnitude}, \cvCppCross{phase}
\cvCppFunc{divide}
Performs per-element division of two arrays or a scalar by an array.
\cvdefCpp{void divide(const Mat\& src1, const Mat\& src2, \par Mat\& dst, double scale=1);\newline
void divide(double scale, const Mat\& src2, Mat\& dst);\newline
void divide(const MatND\& src1, const MatND\& src2, \par MatND\& dst, double scale=1);\newline
void divide(double scale, const MatND\& src2, MatND\& dst);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array; should have the same size and same type as \texttt{src1}}
\cvarg{scale}{Scale factor}
\cvarg{dst}{The destination array; will have the same size and same type as \texttt{src2}}
\end{description}
The functions \texttt{divide} divide one array by another:
\[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))} \]
or a scalar by array, when there is no \texttt{src1}:
\[\texttt{dst(I) = saturate(scale/src2(I))} \]
The result will have the same type as \texttt{src1}. When \texttt{src2(I)=0}, \texttt{dst(I)=0} too.
See also: \cvCppCross{multiply}, \cvCppCross{add}, \cvCppCross{subtract}, \cross{Matrix Expressions}
\cvCppFunc{determinant}
Returns determinant of a square floating-point matrix.
\cvdefCpp{double determinant(const Mat\& mtx);}
\begin{description}
\cvarg{mtx}{The input matrix; must have \texttt{CV\_32FC1} or \texttt{CV\_64FC1} type and square size}
\end{description}
The function \texttt{determinant} computes and returns determinant of the specified matrix. For small matrices (\texttt{mtx.cols=mtx.rows<=3})
the direct method is used; for larger matrices the function uses LU factorization.
For symmetric positive-determined matrices, it is also possible to compute \cvCppCross{SVD}: $\texttt{mtx}=U \cdot W \cdot V^T$ and then calculate the determinant as a product of the diagonal elements of $W$.
See also: \cvCppCross{SVD}, \cvCppCross{trace}, \cvCppCross{invert}, \cvCppCross{solve}, \cross{Matrix Expressions}
\cvCppFunc{eigen}
Computes eigenvalues and eigenvectors of a symmetric matrix.
\cvdefCpp{bool eigen(const Mat\& src, Mat\& eigenvalues, \par int lowindex=-1, int highindex=-1);\newline
bool eigen(const Mat\& src, Mat\& eigenvalues, \par Mat\& eigenvectors, int lowindex=-1,\par
int highindex=-1);}
\begin{description}
\cvarg{src}{The input matrix; must have \texttt{CV\_32FC1} or \texttt{CV\_64FC1} type, square size and be symmetric: $\texttt{src}^T=\texttt{src}$}
\cvarg{eigenvalues}{The output vector of eigenvalues of the same type as \texttt{src}; The eigenvalues are stored in the descending order.}
\cvarg{eigenvectors}{The output matrix of eigenvectors; It will have the same size and the same type as \texttt{src}; The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues}
\cvarg{lowindex}{Optional index of largest eigenvalue/-vector to calculate.
(See below.)}
\cvarg{highindex}{Optional index of smallest eigenvalue/-vector to calculate.
(See below.)}
\end{description}
The functions \texttt{eigen} compute just eigenvalues, or eigenvalues and eigenvectors of symmetric matrix \texttt{src}:
\begin{lstlisting}
src*eigenvectors(i,:)' = eigenvalues(i)*eigenvectors(i,:)' (in MATLAB notation)
\end{lstlisting}
If either low- or highindex is supplied the other is required, too.
Indexing is 0-based. Example: To calculate the largest eigenvector/-value set
lowindex = highindex = 0.
For legacy reasons this function always returns a square matrix the same size
as the source matrix with eigenvectors and a vector the length of the source
matrix with eigenvalues. The selected eigenvectors/-values are always in the
first highindex - lowindex + 1 rows.
See also: \cvCppCross{SVD}, \cvCppCross{completeSymm}, \cvCppCross{PCA}
\cvCppFunc{exp}
Calculates the exponent of every array element.
\cvdefCpp{void exp(const Mat\& src, Mat\& dst);\newline
void exp(const MatND\& src, MatND\& dst);}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
\end{description}
The function \texttt{exp} calculates the exponent of every element of the input array:
\[
\texttt{dst} [I] = e^{\texttt{src}}(I)
\]
The maximum relative error is about $7 \times 10^{-6}$ for single-precision and less than $10^{-10}$ for double-precision. Currently, the function converts denormalized values to zeros on output. Special values (NaN, $\pm \infty$) are not handled.
See also: \cvCppCross{log}, \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}, \cvCppCross{phase}, \cvCppCross{pow}, \cvCppCross{sqrt}, \cvCppCross{magnitude}
\cvCppFunc{extractImageCOI}
Extract the selected image channel
\cvdefCpp{void extractImageCOI(const CvArr* src, Mat\& dst, int coi=-1);}
\begin{description}
\cvarg{src}{The source array. It should be a pointer to \cross{CvMat} or \cross{IplImage}}
\cvarg{dst}{The destination array; will have single-channel, and the same size and the same depth as \texttt{src}}
\cvarg{coi}{If the parameter is \texttt{>=0}, it specifies the channel to extract;
If it is \texttt{<0}, \texttt{src} must be a pointer to \texttt{IplImage} with valid COI set - then the selected COI is extracted.}
\end{description}
The function \texttt{extractImageCOI} is used to extract image COI from an old-style array and put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated using \texttt{Mat::create} if needed.
To extract a channel from a new-style matrix, use \cvCppCross{mixChannels} or \cvCppCross{split}
See also: \cvCppCross{mixChannels}, \cvCppCross{split}, \cvCppCross{merge}, \cvCppCross{cvarrToMat}, \cvCppCross{cvSetImageCOI}, \cvCppCross{cvGetImageCOI}
\cvCppFunc{fastAtan2}
Calculates the angle of a 2D vector in degrees
\cvdefCpp{float fastAtan2(float y, float x);}
\begin{description}
\cvarg{x}{x-coordinate of the vector}
\cvarg{y}{y-coordinate of the vector}
\end{description}
The function \texttt{fastAtan2} calculates the full-range angle of an input 2D vector. The angle is
measured in degrees and varies from $0^\circ$ to $360^\circ$. The accuracy is about $0.3^\circ$.
\cvCppFunc{flip}
Flips a 2D array around vertical, horizontal or both axes.
\cvdefCpp{void flip(const Mat\& src, Mat\& dst, int flipCode);}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
\cvarg{flipCode}{Specifies how to flip the array:
0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas.}
\end{description}
The function \texttt{flip} flips the array in one of three different ways (row and column indices are 0-based):
\[
\texttt{dst}_{ij} = \forkthree
{\texttt{src}_{\texttt{src.rows}-i-1,j}}{if \texttt{flipCode} = 0}
{\texttt{src}_{i,\texttt{src.cols}-j-1}}{if \texttt{flipCode} > 0}
{\texttt{src}_{\texttt{src.rows}-i-1,\texttt{src.cols}-j-1}}{if \texttt{flipCode} < 0}
\]
The example scenarios of function use are:
\begin{itemize}
\item vertical flipping of the image ($\texttt{flipCode} = 0$) to switch between top-left and bottom-left image origin, which is a typical operation in video processing in Windows.
\item horizontal flipping of the image with subsequent horizontal shift and absolute difference calculation to check for a vertical-axis symmetry ($\texttt{flipCode} > 0$)
\item simultaneous horizontal and vertical flipping of the image with subsequent shift and absolute difference calculation to check for a central symmetry ($\texttt{flipCode} < 0$)
\item reversing the order of 1d point arrays ($\texttt{flipCode} > 0$ or $\texttt{flipCode} = 0$)
\end{itemize}
See also: \cvCppCross{transpose}, \cvCppCross{repeat}, \cvCppCross{completeSymm}
\cvCppFunc{gemm}
Performs generalized matrix multiplication.
\cvdefCpp{void gemm(const Mat\& src1, const Mat\& src2, double alpha,\par
const Mat\& src3, double beta, Mat\& dst, int flags=0);}
\begin{description}
\cvarg{src1}{The first multiplied input matrix; should have \texttt{CV\_32FC1}, \texttt{CV\_64FC1}, \texttt{CV\_32FC2} or \texttt{CV\_64FC2} type}
\cvarg{src2}{The second multiplied input matrix; should have the same type as \texttt{src1}}
\cvarg{alpha}{The weight of the matrix product}
\cvarg{src3}{The third optional delta matrix added to the matrix product; should have the same type as \texttt{src1} and \texttt{src2}}
\cvarg{beta}{The weight of \texttt{src3}}
\cvarg{dst}{The destination matrix; It will have the proper size and the same type as input matrices}
\cvarg{flags}{Operation flags:
\begin{description}
\cvarg{GEMM\_1\_T}{transpose \texttt{src1}}
\cvarg{GEMM\_2\_T}{transpose \texttt{src2}}
\cvarg{GEMM\_3\_T}{transpose \texttt{src3}}
\end{description}}
\end{description}
The function performs generalized matrix multiplication and similar to the corresponding functions \texttt{*gemm} in BLAS level 3.
For example, \texttt{gemm(src1, src2, alpha, src3, beta, dst, GEMM\_1\_T + GEMM\_3\_T)} corresponds to
\[
\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T
\]
The function can be replaced with a matrix expression, e.g. the above call can be replaced with:
\begin{lstlisting}
dst = alpha*src1.t()*src2 + beta*src3.t();
\end{lstlisting}
See also: \cvCppCross{mulTransposed}, \cvCppCross{transform}, \cross{Matrix Expressions}
\cvCppFunc{getConvertElem}
Returns conversion function for a single pixel
\cvdefCpp{ConvertData getConvertElem(int fromType, int toType);\newline
ConvertScaleData getConvertScaleElem(int fromType, int toType);\newline
typedef void (*ConvertData)(const void* from, void* to, int cn);\newline
typedef void (*ConvertScaleData)(const void* from, void* to,\par
int cn, double alpha, double beta);}
\begin{description}
\cvarg{fromType}{The source pixel type}
\cvarg{toType}{The destination pixel type}
\cvarg{from}{Callback parameter: pointer to the input pixel}
\cvarg{to}{Callback parameter: pointer to the output pixel}
\cvarg{cn}{Callback parameter: the number of channels; can be arbitrary, 1, 100, 100000, ...}
\cvarg{alpha}{ConvertScaleData callback optional parameter: the scale factor}
\cvarg{beta}{ConvertScaleData callback optional parameter: the delta or offset}
\end{description}
The functions \texttt{getConvertElem} and \texttt{getConvertScaleElem} return pointers to the functions for converting individual pixels from one type to another. While the main function purpose is to convert single pixels (actually, for converting sparse matrices from one type to another), you can use them to convert the whole row of a dense matrix or the whole matrix at once, by setting \texttt{cn = matrix.cols*matrix.rows*matrix.channels()} if the matrix data is continuous.
See also: \cvCppCross{Mat::convertTo}, \cvCppCross{MatND::convertTo}, \cvCppCross{SparseMat::convertTo}
\cvCppFunc{getOptimalDFTSize}
Returns optimal DFT size for a given vector size.
\cvdefCpp{int getOptimalDFTSize(int vecsize);}
\begin{description}
\cvarg{vecsize}{Vector size}
\end{description}
DFT performance is not a monotonic function of a vector size, therefore, when you compute convolution of two arrays or do a spectral analysis of array, it usually makes sense to pad the input data with zeros to get a bit larger array that can be transformed much faster than the original one.
Arrays, which size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process, though, the arrays, which size is a product of 2's, 3's and 5's (e.g. 300 = 5*5*3*2*2), are also processed quite efficiently.
The function \texttt{getOptimalDFTSize} returns the minimum number \texttt{N} that is greater than or equal to \texttt{vecsize}, such that the DFT
of a vector of size \texttt{N} can be computed efficiently. In the current implementation $N=2^p \times 3^q \times 5^r$, for some $p$, $q$, $r$.
The function returns a negative number if \texttt{vecsize} is too large (very close to \texttt{INT\_MAX}).
While the function cannot be used directly to estimate the optimal vector size for DCT transform (since the current DCT implementation supports only even-size vectors), it can be easily computed as \texttt{getOptimalDFTSize((vecsize+1)/2)*2}.
See also: \cvCppCross{dft}, \cvCppCross{dct}, \cvCppCross{idft}, \cvCppCross{idct}, \cvCppCross{mulSpectrums}
\cvCppFunc{idct}
Computes inverse Discrete Cosine Transform of a 1D or 2D array
\cvdefCpp{void idct(const Mat\& src, Mat\& dst, int flags=0);}
\begin{description}
\cvarg{src}{The source floating-point single-channel array}
\cvarg{dst}{The destination array. Will have the same size and same type as \texttt{src}}
\cvarg{flags}{The operation flags.}
\end{description}
\texttt{idct(src, dst, flags)} is equivalent to \texttt{dct(src, dst, flags | DCT\_INVERSE)}.
See \cvCppCross{dct} for details.
See also: \cvCppCross{dct}, \cvCppCross{dft}, \cvCppCross{idft}, \cvCppCross{getOptimalDFTSize}
\cvCppFunc{idft}
Computes inverse Discrete Fourier Transform of a 1D or 2D array
\cvdefCpp{void idft(const Mat\& src, Mat\& dst, int flags=0, int outputRows=0);}
\begin{description}
\cvarg{src}{The source floating-point real or complex array}
\cvarg{dst}{The destination array, which size and type depends on the \texttt{flags}}
\cvarg{flags}{The operation flags. See \cvCppCross{dft}}
\cvarg{nonzeroRows}{The number of \texttt{dst} rows to compute.
The rest of the rows will have undefined content.
See the convolution sample in \cvCppCross{dft} description}
\end{description}
\texttt{idft(src, dst, flags)} is equivalent to \texttt{dct(src, dst, flags | DFT\_INVERSE)}.
See \cvCppCross{dft} for details.
Note, that none of \texttt{dft} and \texttt{idft} scale the result by default.
Thus, you should pass \texttt{DFT\_SCALE} to one of \texttt{dft} or \texttt{idft}
explicitly to make these transforms mutually inverse.
See also: \cvCppCross{dft}, \cvCppCross{dct}, \cvCppCross{idct}, \cvCppCross{mulSpectrums}, \cvCppCross{getOptimalDFTSize}
\cvCppFunc{inRange}
Checks if array elements lie between the elements of two other arrays.
\cvdefCpp{void inRange(const Mat\& src, const Mat\& lowerb,\par
const Mat\& upperb, Mat\& dst);\newline
void inRange(const Mat\& src, const Scalar\& lowerb,\par
const Scalar\& upperb, Mat\& dst);\newline
void inRange(const MatND\& src, const MatND\& lowerb,\par
const MatND\& upperb, MatND\& dst);\newline
void inRange(const MatND\& src, const Scalar\& lowerb,\par
const Scalar\& upperb, MatND\& dst);}
\begin{description}
\cvarg{src}{The first source array}
\cvarg{lowerb}{The inclusive lower boundary array of the same size and type as \texttt{src}}
\cvarg{upperb}{The exclusive upper boundary array of the same size and type as \texttt{src}}
\cvarg{dst}{The destination array, will have the same size as \texttt{src} and \texttt{CV\_8U} type}
\end{description}
The functions \texttt{inRange} do the range check for every element of the input array:
\[
\texttt{dst}(I)=\texttt{lowerb}(I)_0 \leq \texttt{src}(I)_0 < \texttt{upperb}(I)_0
\]
for single-channel arrays,
\[
\texttt{dst}(I)=
\texttt{lowerb}(I)_0 \leq \texttt{src}(I)_0 < \texttt{upperb}(I)_0 \land
\texttt{lowerb}(I)_1 \leq \texttt{src}(I)_1 < \texttt{upperb}(I)_1
\]
for two-channel arrays and so forth.
\texttt{dst}(I) is set to 255 (all \texttt{1}-bits) if \texttt{src}(I) is within the specified range and 0 otherwise.
\cvCppFunc{invert}
Finds the inverse or pseudo-inverse of a matrix
\cvdefCpp{double invert(const Mat\& src, Mat\& dst, int method=DECOMP\_LU);}
\begin{description}
\cvarg{src}{The source floating-point $M \times N$ matrix}
\cvarg{dst}{The destination matrix; will have $N \times M$ size and the same type as \texttt{src}}
\cvarg{flags}{The inversion method :
\begin{description}
\cvarg{DECOMP\_LU}{Gaussian elimination with optimal pivot element chosen}
\cvarg{DECOMP\_SVD}{Singular value decomposition (SVD) method}
\cvarg{DECOMP\_CHOLESKY}{Cholesky decomposion. The matrix must be symmetrical and positively defined}
\end{description}}
\end{description}
The function \texttt{invert} inverts matrix \texttt{src} and stores the result in \texttt{dst}.
When the matrix \texttt{src} is singular or non-square, the function computes the pseudo-inverse matrix, i.e. the matrix \texttt{dst}, such that $\|\texttt{src} \cdot \texttt{dst} - I\|$ is minimal.
In the case of \texttt{DECOMP\_LU} method, the function returns the \texttt{src} determinant (\texttt{src} must be square). If it is 0, the matrix is not inverted and \texttt{dst} is filled with zeros.
In the case of \texttt{DECOMP\_SVD} method, the function returns the inversed condition number of \texttt{src} (the ratio of the smallest singular value to the largest singular value) and 0 if \texttt{src} is singular. The SVD method calculates a pseudo-inverse matrix if \texttt{src} is singular.
Similarly to \texttt{DECOMP\_LU}, the method \texttt{DECOMP\_CHOLESKY} works only with non-singular square matrices. In this case the function stores the inverted matrix in \texttt{dst} and returns non-zero, otherwise it returns 0.
See also: \cvCppCross{solve}, \cvCppCross{SVD}
\cvCppFunc{log}
Calculates the natural logarithm of every array element.
\cvdefCpp{void log(const Mat\& src, Mat\& dst);\newline
void log(const MatND\& src, MatND\& dst);}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array; will have the same size and same type as \texttt{src}}
\end{description}
The function \texttt{log} calculates the natural logarithm of the absolute value of every element of the input array:
\[
\texttt{dst}(I) = \fork
{\log |\texttt{src}(I)|}{if $\texttt{src}(I) \ne 0$ }
{\texttt{C}}{otherwise}
\]
Where \texttt{C} is a large negative number (about -700 in the current implementation).
The maximum relative error is about $7 \times 10^{-6}$ for single-precision input and less than $10^{-10}$ for double-precision input. Special values (NaN, $\pm \infty$) are not handled.
See also: \cvCppCross{exp}, \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}, \cvCppCross{phase}, \cvCppCross{pow}, \cvCppCross{sqrt}, \cvCppCross{magnitude}
\cvCppFunc{LUT}
Performs a look-up table transform of an array.
\cvdefCpp{void LUT(const Mat\& src, const Mat\& lut, Mat\& dst);}
\begin{description}
\cvarg{src}{Source array of 8-bit elements}
\cvarg{lut}{Look-up table of 256 elements. In the case of multi-channel source array, the table should either have a single channel (in this case the same table is used for all channels) or the same number of channels as in the source array}
\cvarg{dst}{Destination array; will have the same size and the same number of channels as \texttt{src}, and the same depth as \texttt{lut}}
\end{description}
The function \texttt{LUT} fills the destination array with values from the look-up table. Indices of the entries are taken from the source array. That is, the function processes each element of \texttt{src} as follows:
\[
\texttt{dst}(I) \leftarrow \texttt{lut(src(I) + d)}
\]
where
\[
d = \fork
{0}{if \texttt{src} has depth \texttt{CV\_8U}}
{128}{if \texttt{src} has depth \texttt{CV\_8S}}
\]
See also: \cvCppCross{convertScaleAbs}, \texttt{Mat::convertTo}
\cvCppFunc{magnitude}
Calculates magnitude of 2D vectors.
\cvdefCpp{void magnitude(const Mat\& x, const Mat\& y, Mat\& magnitude);}
\begin{description}
\cvarg{x}{The floating-point array of x-coordinates of the vectors}
\cvarg{y}{The floating-point array of y-coordinates of the vectors; must have the same size as \texttt{x}}
\cvarg{dst}{The destination array; will have the same size and same type as \texttt{x}}
\end{description}
The function \texttt{magnitude} calculates magnitude of 2D vectors formed from the corresponding elements of \texttt{x} and \texttt{y} arrays:
\[
\texttt{dst}(I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}
\]
See also: \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}, \cvCppCross{phase}, \cvCppCross{sqrt}
\cvCppFunc{Mahalanobis}
Calculates the Mahalanobis distance between two vectors.
\cvdefCpp{double Mahalanobis(const Mat\& vec1, const Mat\& vec2, \par const Mat\& icovar);}
\begin{description}
\cvarg{vec1}{The first 1D source vector}
\cvarg{vec2}{The second 1D source vector}
\cvarg{icovar}{The inverse covariance matrix}
\end{description}
The function \texttt{cvMahalonobis} calculates and returns the weighted distance between two vectors:
\[
d(\texttt{vec1},\texttt{vec2})=\sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})}}
\]
The covariance matrix may be calculated using the \cvCppCross{calcCovarMatrix} function and then inverted using the \cvCppCross{invert} function (preferably using DECOMP\_SVD method, as the most accurate).
\cvCppFunc{max}
Calculates per-element maximum of two arrays or array and a scalar
\cvdefCpp{Mat\_Expr<...> max(const Mat\& src1, const Mat\& src2);\newline
Mat\_Expr<...> max(const Mat\& src1, double value);\newline
Mat\_Expr<...> max(double value, const Mat\& src1);\newline
void max(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
void max(const Mat\& src1, double value, Mat\& dst);\newline
void max(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
void max(const MatND\& src1, double value, MatND\& dst);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array of the same size and type as \texttt{src1}}
\cvarg{value}{The real scalar value}
\cvarg{dst}{The destination array; will have the same size and type as \texttt{src1}}
\end{description}
The functions \texttt{max} compute per-element maximum of two arrays:
\[\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{src2}(I))\]
or array and a scalar:
\[\texttt{dst}(I)=\max(\texttt{src1}(I), \texttt{value})\]
In the second variant, when the source array is multi-channel, each channel is compared with \texttt{value} independently.
The first 3 variants of the function listed above are actually a part of \cross{Matrix Expressions}, they return the expression object that can be further transformed, or assigned to a matrix, or passed to a function etc.
See also: \cvCppCross{min}, \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{minMaxLoc}, \cross{Matrix Expressions}
\cvCppFunc{mean}
Calculates average (mean) of array elements
\cvdefCpp{Scalar mean(const Mat\& mtx);\newline
Scalar mean(const Mat\& mtx, const Mat\& mask);\newline
Scalar mean(const MatND\& mtx);\newline
Scalar mean(const MatND\& mtx, const MatND\& mask);}
\begin{description}
\cvarg{mtx}{The source array; it should have 1 to 4 channels (so that the result can be stored in \cvCppCross{Scalar})}
\cvarg{mask}{The optional operation mask}
\end{description}
The functions \texttt{mean} compute mean value \texttt{M} of array elements, independently for each channel, and return it:
\[
\begin{array}{l}
N = \sum_{I:\;\texttt{mask}(I)\ne 0} 1\\
M_c = \left(\sum_{I:\;\texttt{mask}(I)\ne 0}{\texttt{mtx}(I)_c}\right)/N
\end{array}
\]
When all the mask elements are 0's, the functions return \texttt{Scalar::all(0)}.
See also: \cvCppCross{countNonZero}, \cvCppCross{meanStdDev}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}
\cvCppFunc{meanStdDev}
Calculates mean and standard deviation of array elements
\cvdefCpp{void meanStdDev(const Mat\& mtx, Scalar\& mean, \par Scalar\& stddev, const Mat\& mask=Mat());\newline
void meanStdDev(const MatND\& mtx, Scalar\& mean, \par Scalar\& stddev, const MatND\& mask=MatND());}
\begin{description}
\cvarg{mtx}{The source array; it should have 1 to 4 channels (so that the results can be stored in \cvCppCross{Scalar}'s)}
\cvarg{mean}{The output parameter: computed mean value}
\cvarg{stddev}{The output parameter: computed standard deviation}
\cvarg{mask}{The optional operation mask}
\end{description}
The functions \texttt{meanStdDev} compute the mean and the standard deviation \texttt{M} of array elements, independently for each channel, and return it via the output parameters:
\[
\begin{array}{l}
N = \sum_{I, \texttt{mask}(I) \ne 0} 1\\
\texttt{mean}_c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src}(I)_c}{N}\\
\texttt{stddev}_c = \sqrt{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left(\texttt{src}(I)_c - \texttt{mean}_c\right)^2}
\end{array}
\]
When all the mask elements are 0's, the functions return \texttt{mean=stddev=Scalar::all(0)}.
Note that the computed standard deviation is only the diagonal of the complete normalized covariance matrix. If the full matrix is needed, you can reshape the multi-channel array $M \times N$ to the single-channel array $M*N \times \texttt{mtx.channels}()$ (only possible when the matrix is continuous) and then pass the matrix to \cvCppCross{calcCovarMatrix}.
See also: \cvCppCross{countNonZero}, \cvCppCross{mean}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}, \cvCppCross{calcCovarMatrix}
\cvCppFunc{merge}
Composes a multi-channel array from several single-channel arrays.
\cvdefCpp{void merge(const Mat* mv, size\_t count, Mat\& dst);\newline
void merge(const vector<Mat>\& mv, Mat\& dst);\newline
void merge(const MatND* mv, size\_t count, MatND\& dst);\newline
void merge(const vector<MatND>\& mv, MatND\& dst);}
\begin{description}
\cvarg{mv}{The source array or vector of the single-channel matrices to be merged. All the matrices in \texttt{mv} must have the same size and the same type}
\cvarg{count}{The number of source matrices when \texttt{mv} is a plain C array; must be greater than zero}
\cvarg{dst}{The destination array; will have the same size and the same depth as \texttt{mv[0]}, the number of channels will match the number of source matrices}
\end{description}
The functions \texttt{merge} merge several single-channel arrays (or rather interleave their elements) to make a single multi-channel array.
\[\texttt{dst}(I)_c = \texttt{mv}[c](I)\]
The function \cvCppCross{split} does the reverse operation and if you need to merge several multi-channel images or shuffle channels in some other advanced way, use \cvCppCross{mixChannels}
See also: \cvCppCross{mixChannels}, \cvCppCross{split}, \cvCppCross{reshape}
\cvCppFunc{min}
Calculates per-element minimum of two arrays or array and a scalar
\cvdefCpp{Mat\_Expr<...> min(const Mat\& src1, const Mat\& src2);\newline
Mat\_Expr<...> min(const Mat\& src1, double value);\newline
Mat\_Expr<...> min(double value, const Mat\& src1);\newline
void min(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
void min(const Mat\& src1, double value, Mat\& dst);\newline
void min(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
void min(const MatND\& src1, double value, MatND\& dst);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array of the same size and type as \texttt{src1}}
\cvarg{value}{The real scalar value}
\cvarg{dst}{The destination array; will have the same size and type as \texttt{src1}}
\end{description}
The functions \texttt{min} compute per-element minimum of two arrays:
\[\texttt{dst}(I)=\min(\texttt{src1}(I), \texttt{src2}(I))\]
or array and a scalar:
\[\texttt{dst}(I)=\min(\texttt{src1}(I), \texttt{value})\]
In the second variant, when the source array is multi-channel, each channel is compared with \texttt{value} independently.
The first 3 variants of the function listed above are actually a part of \cross{Matrix Expressions}, they return the expression object that can be further transformed, or assigned to a matrix, or passed to a function etc.
See also: \cvCppCross{max}, \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{minMaxLoc}, \cross{Matrix Expressions}
\cvCppFunc{minMaxLoc}
Finds global minimum and maximum in a whole array or sub-array
\cvdefCpp{void minMaxLoc(const Mat\& src, double* minVal,\par
double* maxVal=0, Point* minLoc=0,\par
Point* maxLoc=0, const Mat\& mask=Mat());\newline
void minMaxLoc(const MatND\& src, double* minVal,\par
double* maxVal, int* minIdx=0, int* maxIdx=0,\par
const MatND\& mask=MatND());\newline
void minMaxLoc(const SparseMat\& src, double* minVal,\par
double* maxVal, int* minIdx=0, int* maxIdx=0);}
\begin{description}
\cvarg{src}{The source single-channel array}
\cvarg{minVal}{Pointer to returned minimum value; \texttt{NULL} if not required}
\cvarg{maxVal}{Pointer to returned maximum value; \texttt{NULL} if not required}
\cvarg{minLoc}{Pointer to returned minimum location (in 2D case); \texttt{NULL} if not required}
\cvarg{maxLoc}{Pointer to returned maximum location (in 2D case); \texttt{NULL} if not required}
\cvarg{minIdx}{Pointer to returned minimum location (in nD case);
\texttt{NULL} if not required, otherwise must point to an array of \texttt{src.dims} elements and the coordinates of minimum element in each dimensions will be stored sequentially there.}
\cvarg{maxIdx}{Pointer to returned maximum location (in nD case); \texttt{NULL} if not required}
\cvarg{mask}{The optional mask used to select a sub-array}
\end{description}
The functions \texttt{ninMaxLoc} find minimum and maximum element values
and their positions. The extremums are searched across the whole array, or,
if \texttt{mask} is not an empty array, in the specified array region.
The functions do not work with multi-channel arrays. If you need to find minimum or maximum elements across all the channels, use \cvCppCross{reshape} first to reinterpret the array as single-channel. Or you may extract the particular channel using \cvCppCross{extractImageCOI} or \cvCppCross{mixChannels} or \cvCppCross{split}.
in the case of a sparse matrix the minimum is found among non-zero elements only.
See also: \cvCppCross{max}, \cvCppCross{min}, \cvCppCross{compare}, \cvCppCross{inRange}, \cvCppCross{extractImageCOI}, \cvCppCross{mixChannels}, \cvCppCross{split}, \cvCppCross{reshape}.
\cvCppFunc{mixChannels}
Copies specified channels from input arrays to the specified channels of output arrays
\cvdefCpp{void mixChannels(const Mat* srcv, int nsrc, Mat* dstv, int ndst,\par
const int* fromTo, size\_t npairs);\newline
void mixChannels(const MatND* srcv, int nsrc, MatND* dstv, int ndst,\par
const int* fromTo, size\_t npairs);\newline
void mixChannels(const vector<Mat>\& srcv, vector<Mat>\& dstv,\par
const int* fromTo, int npairs);\newline
void mixChannels(const vector<MatND>\& srcv, vector<MatND>\& dstv,\par
const int* fromTo, int npairs);}
\begin{description}
\cvarg{srcv}{The input array or vector of matrices.
All the matrices must have the same size and the same depth}
\cvarg{nsrc}{The number of elements in \texttt{srcv}}
\cvarg{dstv}{The output array or vector of matrices.
All the matrices \emph{must be allocated}, their size and depth must be the same as in \texttt{srcv[0]}}
\cvarg{ndst}{The number of elements in \texttt{dstv}}
\cvarg{fromTo}{The array of index pairs, specifying which channels are copied and where.
\texttt{fromTo[k*2]} is the 0-based index of the input channel in \texttt{srcv} and
\texttt{fromTo[k*2+1]} is the index of the output channel in \texttt{dstv}. Here the continuous channel numbering is used, that is,
the first input image channels are indexed from \texttt{0} to \texttt{srcv[0].channels()-1},
the second input image channels are indexed from \texttt{srcv[0].channels()} to
\texttt{srcv[0].channels() + srcv[1].channels()-1} etc., and the same scheme is used for the output image channels.
As a special case, when \texttt{fromTo[k*2]} is negative, the corresponding output channel is filled with zero.
}
\texttt{npairs}{The number of pairs. In the latter case the parameter is not passed explicitly, but computed as \texttt{srcv.size()} (=\texttt{dstv.size()})}
\end{description}
The functions \texttt{mixChannels} provide an advanced mechanism for shuffling image channels. \cvCppCross{split} and \cvCppCross{merge} and some forms of \cvCppCross{cvtColor} are partial cases of \texttt{mixChannels}.
As an example, this code splits a 4-channel RGBA image into a 3-channel
BGR (i.e. with R and B channels swapped) and separate alpha channel image:
\begin{lstlisting}
Mat rgba( 100, 100, CV_8UC4, Scalar(1,2,3,4) );
Mat bgr( rgba.rows, rgba.cols, CV_8UC3 );
Mat alpha( rgba.rows, rgba.cols, CV_8UC1 );
// forming array of matrices is quite efficient operations,
// because the matrix data is not copied, only the headers
Mat out[] = { bgr, alpha };
// rgba[0] -> bgr[2], rgba[1] -> bgr[1],
// rgba[2] -> bgr[0], rgba[3] -> alpha[0]
int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
mixChannels( &rgba, 1, out, 2, from_to, 4 );
\end{lstlisting}
Note that, unlike many other new-style C++ functions in OpenCV (see the introduction section and \cvCppCross{Mat::create}),
\texttt{mixChannels} requires the destination arrays be pre-allocated before calling the function.
See also: \cvCppCross{split}, \cvCppCross{merge}, \cvCppCross{cvtColor}
\cvCppFunc{mulSpectrums}
Performs per-element multiplication of two Fourier spectrums.
\cvdefCpp{void mulSpectrums(const Mat\& src1, const Mat\& src2, Mat\& dst,\par
int flags, bool conj=false);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array; must have the same size and the same type as \texttt{src1}}
\cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
\cvarg{flags}{The same flags as passed to \cvCppCross{dft}; only the flag \texttt{DFT\_ROWS} is checked for}
\cvarg{conj}{The optional flag that conjugate the second source array before the multiplication (true) or not (false)}
\end{description}
The function \texttt{mulSpectrums} performs per-element multiplication of the two CCS-packed or complex matrices that are results of a real or complex Fourier transform.
The function, together with \cvCppCross{dft} and \cvCppCross{idft}, may be used to calculate convolution (pass \texttt{conj=false}) or correlation (pass \texttt{conj=false}) of two arrays rapidly. When the arrays are complex, they are simply multiplied (per-element) with optional conjugation of the second array elements. When the arrays are real, they assumed to be CCS-packed (see \cvCppCross{dft} for details).
\cvCppFunc{multiply}
Calculates the per-element scaled product of two arrays
\cvdefCpp{void multiply(const Mat\& src1, const Mat\& src2, \par Mat\& dst, double scale=1);\newline
void multiply(const MatND\& src1, const MatND\& src2, \par MatND\& dst, double scale=1);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array of the same size and the same type as \texttt{src1}}
\cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
\cvarg{scale}{The optional scale factor}
\end{description}
The function \texttt{multiply} calculates the per-element product of two arrays:
\[
\texttt{dst}(I)=\texttt{saturate}(\texttt{scale} \cdot \texttt{src1}(I) \cdot \texttt{src2}(I))
\]
There is also \cross{Matrix Expressions}-friendly variant of the first function, see \cvCppCross{Mat::mul}.
If you are looking for a matrix product, not per-element product, see \cvCppCross{gemm}.
See also: \cvCppCross{add}, \cvCppCross{substract}, \cvCppCross{divide}, \cross{Matrix Expressions}, \cvCppCross{scaleAdd}, \cvCppCross{addWeighted}, \cvCppCross{accumulate}, \cvCppCross{accumulateProduct}, \cvCppCross{accumulateSquare}, \cvCppCross{Mat::convertTo}
\cvCppFunc{mulTransposed}
Calculates the product of a matrix and its transposition.
\cvdefCpp{void mulTransposed( const Mat\& src, Mat\& dst, bool aTa,\par
const Mat\& delta=Mat(),\par
double scale=1, int rtype=-1 );}
\begin{description}
\cvarg{src}{The source matrix}
\cvarg{dst}{The destination square matrix}
\cvarg{aTa}{Specifies the multiplication ordering; see the description below}
\cvarg{delta}{The optional delta matrix, subtracted from \texttt{src} before the multiplication. When the matrix is empty (\texttt{delta=Mat()}), it's assumed to be zero, i.e. nothing is subtracted, otherwise if it has the same size as \texttt{src}, then it's simply subtracted, otherwise it is "repeated" (see \cvCppCross{repeat}) to cover the full \texttt{src} and then subtracted. Type of the delta matrix, when it's not empty, must be the same as the type of created destination matrix, see the \texttt{rtype} description}
\cvarg{scale}{The optional scale factor for the matrix product}
\cvarg{rtype}{When it's negative, the destination matrix will have the same type as \texttt{src}. Otherwise, it will have \texttt{type=CV\_MAT\_DEPTH(rtype)}, which should be either \texttt{CV\_32F} or \texttt{CV\_64F}}
\end{description}
The function \texttt{mulTransposed} calculates the product of \texttt{src} and its transposition:
\[
\texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta})^T (\texttt{src}-\texttt{delta})
\]
if \texttt{aTa=true}, and
\[
\texttt{dst}=\texttt{scale} (\texttt{src}-\texttt{delta}) (\texttt{src}-\texttt{delta})^T
\]
otherwise. The function is used to compute covariance matrix and with zero delta can be used as a faster substitute for general matrix product $A*B$ when $B=A^T$.
See also: \cvCppCross{calcCovarMatrix}, \cvCppCross{gemm}, \cvCppCross{repeat}, \cvCppCross{reduce}
\cvCppFunc{norm}
Calculates absolute array norm, absolute difference norm, or relative difference norm.
\cvdefCpp{double norm(const Mat\& src1, int normType=NORM\_L2);\newline
double norm(const Mat\& src1, const Mat\& src2, int normType=NORM\_L2);\newline
double norm(const Mat\& src1, int normType, const Mat\& mask);\newline
double norm(const Mat\& src1, const Mat\& src2, \par int normType, const Mat\& mask);\newline
double norm(const MatND\& src1, int normType=NORM\_L2, \par const MatND\& mask=MatND());\newline
double norm(const MatND\& src1, const MatND\& src2,\par
int normType=NORM\_L2, const MatND\& mask=MatND());\newline
double norm( const SparseMat\& src, int normType );}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array of the same size and the same type as \texttt{src1}}
\cvarg{normType}{Type of the norm; see the discussion below}
\cvarg{mask}{The optional operation mask}
\end{description}
The functions \texttt{norm} calculate the absolute norm of \texttt{src1} (when there is no \texttt{src2}):
\[
norm = \forkthree
{\|\texttt{src1}\|_{L_{\infty}} = \max_I |\texttt{src1}(I)|}{if $\texttt{normType} = \texttt{NORM\_INF}$}
{\|\texttt{src1}\|_{L_1} = \sum_I |\texttt{src1}(I)|}{if $\texttt{normType} = \texttt{NORM\_L1}$}
{\|\texttt{src1}\|_{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2}}{if $\texttt{normType} = \texttt{NORM\_L2}$}
\]
or an absolute or relative difference norm if \texttt{src2} is there:
\[
norm = \forkthree
{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max_I |\texttt{src1}(I) - \texttt{src2}(I)|}{if $\texttt{normType} = \texttt{NORM\_INF}$}
{\|\texttt{src1}-\texttt{src2}\|_{L_1} = \sum_I |\texttt{src1}(I) - \texttt{src2}(I)|}{if $\texttt{normType} = \texttt{NORM\_L1}$}
{\|\texttt{src1}-\texttt{src2}\|_{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2}}{if $\texttt{normType} = \texttt{NORM\_L2}$}
\]
or
\[
norm = \forkthree
{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_INF}$}
{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}}}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_L1}$}
{\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}}{if $\texttt{normType} = \texttt{NORM\_RELATIVE\_L2}$}
\]
The functions \texttt{norm} return the calculated norm.
When there is \texttt{mask} parameter, and it is not empty (then it should have type \texttt{CV\_8U} and the same size as \texttt{src1}), the norm is computed only over the specified by the mask region.
A multiple-channel source arrays are treated as a single-channel, that is, the results for all channels are combined.
\cvCppFunc{normalize}
Normalizes array's norm or the range
\cvdefCpp{void normalize( const Mat\& src, Mat\& dst, \par double alpha=1, double beta=0,\par
int normType=NORM\_L2, int rtype=-1, \par const Mat\& mask=Mat());\newline
void normalize( const MatND\& src, MatND\& dst, \par double alpha=1, double beta=0,\par
int normType=NORM\_L2, int rtype=-1, \par const MatND\& mask=MatND());\newline
void normalize( const SparseMat\& src, SparseMat\& dst, \par double alpha, int normType );}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array; will have the same size as \texttt{src}}
\cvarg{alpha}{The norm value to normalize to or the lower range boundary in the case of range normalization}
\cvarg{beta}{The upper range boundary in the case of range normalization; not used for norm normalization}
\cvarg{normType}{The normalization type, see the discussion}
\cvarg{rtype}{When the parameter is negative, the destination array will have the same type as \texttt{src}, otherwise it will have the same number of channels as \texttt{src} and the depth\texttt{=CV\_MAT\_DEPTH(rtype)}}
\cvarg{mask}{The optional operation mask}
\end{description}
The functions \texttt{normalize} scale and shift the source array elements, so that
\[\|\texttt{dst}\|_{L_p}=\texttt{alpha}\]
(where $p=\infty$, 1 or 2) when \texttt{normType=NORM\_INF}, \texttt{NORM\_L1} or \texttt{NORM\_L2},
or so that
\[\min_I \texttt{dst}(I)=\texttt{alpha},\,\,\max_I \texttt{dst}(I)=\texttt{beta}\]
when \texttt{normType=NORM\_MINMAX} (for dense arrays only).
The optional mask specifies the sub-array to be normalize, that is, the norm or min-n-max are computed over the sub-array and then this sub-array is modified to be normalized. If you want to only use the mask to compute the norm or min-max, but modify the whole array, you can use \cvCppCross{norm} and \cvCppCross{Mat::convertScale}/\cvCppCross{MatND::convertScale}/cross{SparseMat::convertScale} separately.
in the case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, the range transformation for sparse matrices is not allowed, since it can shift the zero level.
See also: \cvCppCross{norm}, \cvCppCross{Mat::convertScale}, \cvCppCross{MatND::convertScale}, \cvCppCross{SparseMat::convertScale}
\cvclass{PCA}
Class for Principal Component Analysis
\begin{lstlisting}
class PCA
{
public:
// default constructor
PCA();
// computes PCA for a set of vectors stored as data rows or columns.
PCA(const Mat& data, const Mat& mean, int flags, int maxComponents=0);
// computes PCA for a set of vectors stored as data rows or columns
PCA& operator()(const Mat& data, const Mat& mean, int flags, int maxComponents=0);
// projects vector into the principal components space
Mat project(const Mat& vec) const;
void project(const Mat& vec, Mat& result) const;
// reconstructs the vector from its PC projection
Mat backProject(const Mat& vec) const;
void backProject(const Mat& vec, Mat& result) const;
// eigenvectors of the PC space, stored as the matrix rows
Mat eigenvectors;
// the corresponding eigenvalues; not used for PCA compression/decompression
Mat eigenvalues;
// mean vector, subtracted from the projected vector
// or added to the reconstructed vector
Mat mean;
};
\end{lstlisting}
The class \texttt{PCA} is used to compute the special basis for a set of vectors. The basis will consist of eigenvectors of the covariance matrix computed from the input set of vectors. And also the class \texttt{PCA} can transform vectors to/from the new coordinate space, defined by the basis. Usually, in this new coordinate system each vector from the original set (and any linear combination of such vectors) can be quite accurately approximated by taking just the first few its components, corresponding to the eigenvectors of the largest eigenvalues of the covariance matrix. Geometrically it means that we compute projection of the vector to a subspace formed by a few eigenvectors corresponding to the dominant eigenvalues of the covariation matrix. And usually such a projection is very close to the original vector. That is, we can represent the original vector from a high-dimensional space with a much shorter vector consisting of the projected vector's coordinates in the subspace. Such a transformation is also known as Karhunen-Loeve Transform, or KLT. See \url{http://en.wikipedia.org/wiki/Principal\_component\_analysis}
The following sample is the function that takes two matrices. The first one stores the set of vectors (a row per vector) that is used to compute PCA, the second one stores another "test" set of vectors (a row per vector) that are first compressed with PCA, then reconstructed back and then the reconstruction error norm is computed and printed for each vector.
\begin{lstlisting}
PCA compressPCA(const Mat& pcaset, int maxComponents,
const Mat& testset, Mat& compressed)
{
PCA pca(pcaset, // pass the data
Mat(), // we do not have a pre-computed mean vector,
// so let the PCA engine to compute it
CV_PCA_DATA_AS_ROW, // indicate that the vectors
// are stored as matrix rows
// (use CV_PCA_DATA_AS_COL if the vectors are
// the matrix columns)
maxComponents // specify, how many principal components to retain
);
// if there is no test data, just return the computed basis, ready-to-use
if( !testset.data )
return pca;
CV_Assert( testset.cols == pcaset.cols );
compressed.create(testset.rows, maxComponents, testset.type());
Mat reconstructed;
for( int i = 0; i < testset.rows; i++ )
{
Mat vec = testset.row(i), coeffs = compressed.row(i);
// compress the vector, the result will be stored
// in the i-th row of the output matrix
pca.project(vec, coeffs);
// and then reconstruct it
pca.backProject(coeffs, reconstructed);
// and measure the error
printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
}
return pca;
}
\end{lstlisting}
See also: \cvCppCross{calcCovarMatrix}, \cvCppCross{mulTransposed}, \cvCppCross{SVD}, \cvCppCross{dft}, \cvCppCross{dct}
\cvCppFunc{PCA::PCA}
PCA constructors
\cvdefCpp{
PCA::PCA();\newline
PCA::PCA(const Mat\& data, const Mat\& mean, int flags, int maxComponents=0);
}
\begin{description}
\cvarg{data}{the input samples, stored as the matrix rows or as the matrix columns}
\cvarg{mean}{the optional mean value. If the matrix is empty (\texttt{Mat()}), the mean is computed from the data.}
\cvarg{flags}{operation flags. Currently the parameter is only used to specify the data layout.}
\begin{description}
\cvarg{CV\_PCA\_DATA\_AS\_ROWS}{Indicates that the input samples are stored as matrix rows.}
\cvarg{CV\_PCA\_DATA\_AS\_COLS}{Indicates that the input samples are stored as matrix columns.}
\end{description}
\cvarg{maxComponents}{The maximum number of components that PCA should retain. By default, all the components are retained.}
\end{description}
The default constructor initializes empty PCA structure. The second constructor initializes the structure and calls \cvCppCross{PCA::operator ()}.
\cvCppFunc{PCA::operator ()}
Performs Principal Component Analysis of the supplied dataset.
\cvdefCpp{
PCA\& PCA::operator()(const Mat\& data, const Mat\& mean, int flags, int maxComponents=0);
}
\begin{description}
\cvarg{data}{the input samples, stored as the matrix rows or as the matrix columns}
\cvarg{mean}{the optional mean value. If the matrix is empty (\texttt{Mat()}), the mean is computed from the data.}
\cvarg{flags}{operation flags. Currently the parameter is only used to specify the data layout.}
\begin{description}
\cvarg{CV\_PCA\_DATA\_AS\_ROWS}{Indicates that the input samples are stored as matrix rows.}
\cvarg{CV\_PCA\_DATA\_AS\_COLS}{Indicates that the input samples are stored as matrix columns.}
\end{description}
\cvarg{maxComponents}{The maximum number of components that PCA should retain. By default, all the components are retained.}
\end{description}
The operator performs PCA of the supplied dataset. It is safe to reuse the same PCA structure for multiple dataset. That is, if the structure has been previously used with another dataset, the existing internal data is reclaimed and the new \texttt{eigenvalues}, \texttt{eigenvectors} and \texttt{mean} are allocated and computed.
The computed eigenvalues are sorted from the largest to the smallest and the corresponding eigenvectors are stored as \texttt{PCA::eigenvectors} rows.
\cvCppFunc{PCA::project}
Project vector(s) to the principal component subspace
\cvdefCpp{
Mat PCA::project(const Mat\& vec) const;\newline
void PCA::project(const Mat\& vec, Mat\& result) const;
}
\begin{description}
\cvarg{vec}{the input vector(s). They have to have the same dimensionality and the same layout as the input data used at PCA phase. That is, if \texttt{CV\_PCA\_DATA\_AS\_ROWS} had been specified, then \texttt{vec.cols==data.cols} (that's vectors' dimensionality) and \texttt{vec.rows} is the number of vectors to project; and similarly for the \texttt{CV\_PCA\_DATA\_AS\_COLS} case.}
\cvarg{result}{the output vectors. Let's now consider \texttt{CV\_PCA\_DATA\_AS\_COLS} case. In this case the output matrix will have as many columns as the number of input vectors, i.e. \texttt{result.cols==vec.cols} and the number of rows will match the number of principal components (e.g. \texttt{maxComponents} parameter passed to the constructor).}
\end{description}
The methods project one or more vectors to the principal component subspace, where each vector projection is represented by coefficients in the principal component basis. The first form of the method returns the matrix that the second form writes to the result. So the first form can be used as a part of expression, while the second form can be more efficient in a processing loop.
\cvCppFunc{PCA::backProject}
Reconstruct vectors from their PC projections.
\cvdefCpp{
Mat PCA::backProject(const Mat\& vec) const;\newline
void PCA::backProject(const Mat\& vec, Mat\& result) const;
}
\begin{description}
\cvarg{vec}{Coordinates of the vectors in the principal component subspace. The layout and size are the same as of \texttt{PCA::project} output vectors.}
\cvarg{result}{The reconstructed vectors. The layout and size are the same as of \texttt{PCA::project} input vectors.}
\end{description}
The methods are inverse operations to \cvCppCross{PCA::project}. They take PC coordinates of projected vectors and reconstruct the original vectors. Of course, unless all the principal components have been retained, the reconstructed vectors will be different from the originals, but typically the difference will be small is if the number of components is large enough (but still much smaller than the original vector dimensionality) - that's why PCA is used after all.
\cvCppFunc{perspectiveTransform}
Performs perspective matrix transformation of vectors.
\cvdefCpp{void perspectiveTransform(const Mat\& src, \par Mat\& dst, const Mat\& mtx );}
\begin{description}
\cvarg{src}{The source two-channel or three-channel floating-point array;
each element is 2D/3D vector to be transformed}
\cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src}}
\cvarg{mtx}{$3\times 3$ or $4 \times 4$ transformation matrix}
\end{description}
The function \texttt{perspectiveTransform} transforms every element of \texttt{src},
by treating it as 2D or 3D vector, in the following way (here 3D vector transformation is shown; in the case of 2D vector transformation the $z$ component is omitted):
\[ (x, y, z) \rightarrow (x'/w, y'/w, z'/w) \]
where
\[
(x', y', z', w') = \texttt{mat} \cdot
\begin{bmatrix} x & y & z & 1 \end{bmatrix}
\]
and
\[ w = \fork{w'}{if $w' \ne 0$}{\infty}{otherwise} \]
Note that the function transforms a sparse set of 2D or 3D vectors. If you want to transform an image using perspective transformation, use \cvCppCross{warpPerspective}. If you have an inverse task, i.e. want to compute the most probable perspective transformation out of several pairs of corresponding points, you can use \cvCppCross{getPerspectiveTransform} or \cvCppCross{findHomography}.
See also: \cvCppCross{transform}, \cvCppCross{warpPerspective}, \cvCppCross{getPerspectiveTransform}, \cvCppCross{findHomography}
\cvCppFunc{phase}
Calculates the rotation angle of 2d vectors
\cvdefCpp{void phase(const Mat\& x, const Mat\& y, Mat\& angle,\par
bool angleInDegrees=false);}
\begin{description}
\cvarg{x}{The source floating-point array of x-coordinates of 2D vectors}
\cvarg{y}{The source array of y-coordinates of 2D vectors; must have the same size and the same type as \texttt{x}}
\cvarg{angle}{The destination array of vector angles; it will have the same size and same type as \texttt{x}}
\cvarg{angleInDegrees}{When it is true, the function will compute angle in degrees, otherwise they will be measured in radians}
\end{description}
The function \texttt{phase} computes the rotation angle of each 2D vector that is formed from the corresponding elements of \texttt{x} and \texttt{y}:
\[\texttt{angle}(I) = \texttt{atan2}(\texttt{y}(I), \texttt{x}(I))\]
The angle estimation accuracy is $\sim\,0.3^\circ$, when \texttt{x(I)=y(I)=0}, the corresponding \texttt{angle}(I) is set to $0$.
See also:
\cvCppFunc{polarToCart}
Computes x and y coordinates of 2D vectors from their magnitude and angle.
\cvdefCpp{void polarToCart(const Mat\& magnitude, const Mat\& angle,\par
Mat\& x, Mat\& y, bool angleInDegrees=false);}
\begin{description}
\cvarg{magnitude}{The source floating-point array of magnitudes of 2D vectors. It can be an empty matrix (\texttt{=Mat()}) - in this case the function assumes that all the magnitudes are =1. If it's not empty, it must have the same size and same type as \texttt{angle}}
\cvarg{angle}{The source floating-point array of angles of the 2D vectors}
\cvarg{x}{The destination array of x-coordinates of 2D vectors; will have the same size and the same type as \texttt{angle}}
\cvarg{y}{The destination array of y-coordinates of 2D vectors; will have the same size and the same type as \texttt{angle}}
\cvarg{angleInDegrees}{When it is true, the input angles are measured in degrees, otherwise they are measured in radians}
\end{description}
The function \texttt{polarToCart} computes the cartesian coordinates of each 2D vector represented by the corresponding elements of \texttt{magnitude} and \texttt{angle}:
\[
\begin{array}{l}
\texttt{x}(I) = \texttt{magnitude}(I)\cos(\texttt{angle}(I))\\
\texttt{y}(I) = \texttt{magnitude}(I)\sin(\texttt{angle}(I))\\
\end{array}
\]
The relative accuracy of the estimated coordinates is $\sim\,10^{-6}$.
See also: \cvCppCross{cartToPolar}, \cvCppCross{magnitude}, \cvCppCross{phase}, \cvCppCross{exp}, \cvCppCross{log}, \cvCppCross{pow}, \cvCppCross{sqrt}
\cvCppFunc{pow}
Raises every array element to a power.
\cvdefCpp{void pow(const Mat\& src, double p, Mat\& dst);\newline
void pow(const MatND\& src, double p, MatND\& dst);}
\begin{description}
\cvarg{src}{The source array}
\cvarg{p}{The exponent of power}
\cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
\end{description}
The function \texttt{pow} raises every element of the input array to \texttt{p}:
\[
\texttt{dst}(I) = \fork
{\texttt{src}(I)^p}{if \texttt{p} is integer}
{|\texttt{src}(I)|^p}{otherwise}
\]
That is, for a non-integer power exponent the absolute values of input array elements are used. However, it is possible to get true values for negative values using some extra operations, as the following example, computing the 5th root of array \texttt{src}, shows:
\begin{lstlisting}
Mat mask = src < 0;
pow(src, 1./5, dst);
subtract(Scalar::all(0), dst, dst, mask);
\end{lstlisting}
For some values of \texttt{p}, such as integer values, 0.5, and -0.5, specialized faster algorithms are used.
See also: \cvCppCross{sqrt}, \cvCppCross{exp}, \cvCppCross{log}, \cvCppCross{cartToPolar}, \cvCppCross{polarToCart}
\subsection{RNG}\label{RNG}
Random number generator class.
\begin{lstlisting}
class CV_EXPORTS RNG
{
public:
enum { A=4164903690U, UNIFORM=0, NORMAL=1 };
// constructors
RNG();
RNG(uint64 state);
// returns 32-bit unsigned random number
unsigned next();
// return random numbers of the specified type
operator uchar();
operator schar();
operator ushort();
operator short();
operator unsigned();
// returns a random integer sampled uniformly from [0, N).
unsigned operator()(unsigned N);
unsigned operator()();
operator int();
operator float();
operator double();
// returns a random number sampled uniformly from [a, b) range
int uniform(int a, int b);
float uniform(float a, float b);
double uniform(double a, double b);
// returns Gaussian random number with zero mean.
double gaussian(double sigma);
// fills array with random numbers sampled from the specified distribution
void fill( Mat& mat, int distType, const Scalar& a, const Scalar& b );
void fill( MatND& mat, int distType, const Scalar& a, const Scalar& b );
// internal state of the RNG (could change in the future)
uint64 state;
};
\end{lstlisting}
The class \texttt{RNG} implements random number generator. It encapsulates the RNG state (currently, a 64-bit integer) and has methods to return scalar random values and to fill arrays with random values. Currently it supports uniform and Gaussian (normal) distributions. The generator uses Multiply-With-Carry algorithm, introduced by G. Marsaglia (\url{http://en.wikipedia.org/wiki/Multiply-with-carry}). Gaussian-distribution random numbers are generated using Ziggurat algorithm (\url{http://en.wikipedia.org/wiki/Ziggurat_algorithm}), introduced by G. Marsaglia and W. W. Tsang.
\cvCppFunc{RNG::RNG}
RNG constructors
\cvdefCpp{
RNG::RNG();\newline
RNG::RNG(uint64 state);
}
\begin{description}
\cvarg{state}{the 64-bit value used to initialize the RNG}
\end{description}
These are the RNG constructors. The first form sets the state to some pre-defined value, equal to \texttt{2**32-1} in the current implementation. The second form sets the state to the specified value. If the user passed \texttt{state=0}, the constructor uses the above default value instead, to avoid the singular random number sequence, consisting of all zeros.
\cvCppFunc{RNG::next}
Returns the next random number
\cvdefCpp{
unsigned RNG::next();
}
The method updates the state using MWC algorithm and returns the next 32-bit random number.
\cvCppFunc{RNG::operator T}
Returns the next random number of the specified type
\cvdefCpp{
RNG::operator uchar();
RNG::operator schar();
RNG::operator ushort();
RNG::operator short();
RNG::operator unsigned();
RNG::operator int();
RNG::operator float();
RNG::operator double();
}
Each of the methods updates the state using MWC algorithm and returns the next random number of the specified type. In the case of integer types the returned number is from the whole available value range for the specified type. In the case of floating-point types the returned value is from \texttt{[0,1)} range.
\cvCppFunc{RNG::operator ()}
Returns the next random number
\cvdefCpp{
unsigned RNG::operator ()();\newline
unsigned RNG::operator ()(unsigned N);
}
\begin{description}
\cvarg{N}{The upper non-inclusive boundary of the returned random number}
\end{description}
The methods transforms the state using MWC algorithm and returns the next random number. The first form is equivalent to \cvCppCross{RNG::next}, the second form returns the random number modulo \texttt{N}, i.e. the result will be in the range \texttt{[0, N)}.
\cvCppFunc{RNG::uniform}
Returns the next random number sampled from the uniform distribution
\cvdefCpp{
int RNG::uniform(int a, int b);\newline
float RNG::uniform(float a, float b);\newline
double RNG::uniform(double a, double b);
}
\begin{description}
\cvarg{a}{The lower inclusive boundary of the returned random numbers}
\cvarg{b}{The upper non-inclusive boundary of the returned random numbers}
\end{description}
The methods transforms the state using MWC algorithm and returns the next uniformly-distributed random number of the specified type, deduced from the input parameter type, from the range \texttt{[a, b)}. There is one nuance, illustrated by the following sample:
\begin{lstlisting}
cv::RNG rng;
// will always produce 0
double a = rng.uniform(0, 1);
// will produce double from [0, 1)
double a1 = rng.uniform((double)0, (double)1);
// will produce float from [0, 1)
double b = rng.uniform(0.f, 1.f);
// will produce double from [0, 1)
double c = rng.uniform(0., 1.);
// will likely cause compiler error because of ambiguity:
// RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
double d = rng.uniform(0, 0.999999);
\end{lstlisting}
That is, the compiler does not take into account type of the variable that you assign the result of \texttt{RNG::uniform} to, the only thing that matters to it is the type of \texttt{a} and \texttt{b} parameters. So if you want a floating-point random number, but the range boundaries are integer numbers, either put dots in the end, if they are constants, or use explicit type cast operators, as in \texttt{a1} initialization above.
\cvCppFunc{RNG::gaussian}
Returns the next random number sampled from the Gaussian distribution
\cvdefCpp{
double RNG::gaussian(double sigma);
}
\begin{description}
\cvarg{sigma}{The standard deviation of the distribution}
\end{description}
The methods transforms the state using MWC algorithm and returns the next random number from the Gaussian distribution \texttt{N(0,sigma)}. That is, the mean value of the returned random numbers will be zero and the standard deviation will be the specified \texttt{sigma}.
\cvCppFunc{RNG::fill}
Fill arrays with random numbers
\cvdefCpp{
void RNG::fill( Mat\& mat, int distType, const Scalar\& a, const Scalar\& b );\newline
void RNG::fill( MatND\& mat, int distType, const Scalar\& a, const Scalar\& b );
}
\begin{description}
\cvarg{mat}{2D or N-dimensional matrix. Currently matrices with more than 4 channels are not supported by the methods. Use \cvCppCross{reshape} as a possible workaround.}
\cvarg{distType}{The distribution type, \texttt{RNG::UNIFORM} or \texttt{RNG::NORMAL}}
\cvarg{a}{The first distribution parameter. In the case of uniform distribution this is inclusive lower boundary. In the case of normal distribution this is mean value.}
\cvarg{b}{The second distribution parameter. In the case of uniform distribution this is non-inclusive upper boundary. In the case of normal distribution this is standard deviation.}
\end{description}
Each of the methods fills the matrix with the random values from the specified distribution. As the new numbers are generated, the RNG state is updated accordingly. In the case of multiple-channel images every channel is filled independently, i.e. RNG can not generate samples from multi-dimensional Gaussian distribution with non-diagonal covariation matrix directly. To do that, first, generate matrix from the distribution $N(0, I_n)$, i.e. Gaussian distribution with zero mean and identity covariation matrix, and then transform it using \cvCppCross{transform} and the specific covariation matrix.
\cvCppFunc{randu}
Generates a single uniformly-distributed random number or array of random numbers
\cvdefCpp{template<typename \_Tp> \_Tp randu();\newline
void randu(Mat\& mtx, const Scalar\& low, const Scalar\& high);}
\begin{description}
\cvarg{mtx}{The output array of random numbers. The array must be pre-allocated and have 1 to 4 channels}
\cvarg{low}{The inclusive lower boundary of the generated random numbers}
\cvarg{high}{The exclusive upper boundary of the generated random numbers}
\end{description}
The template functions \texttt{randu} generate and return the next uniformly-distributed random value of the specified type. \texttt{randu<int>()} is equivalent to \texttt{(int)theRNG();} etc. See \cvCppCross{RNG} description.
The second non-template variant of the function fills the matrix \texttt{mtx} with uniformly-distributed random numbers from the specified range:
\[\texttt{low}_c \leq \texttt{mtx}(I)_c < \texttt{high}_c\]
See also: \cvCppCross{RNG}, \cvCppCross{randn}, \cvCppCross{theRNG}.
\cvCppFunc{randn}
Fills array with normally distributed random numbers
\cvdefCpp{void randn(Mat\& mtx, const Scalar\& mean, const Scalar\& stddev);}
\begin{description}
\cvarg{mtx}{The output array of random numbers. The array must be pre-allocated and have 1 to 4 channels}
\cvarg{mean}{The mean value (expectation) of the generated random numbers}
\cvarg{stddev}{The standard deviation of the generated random numbers}
\end{description}
The function \texttt{randn} fills the matrix \texttt{mtx} with normally distributed random numbers with the specified mean and standard deviation. \hyperref[cppfunc.saturatecast]{saturate\_cast} is applied to the generated numbers (i.e. the values are clipped)
See also: \cvCppCross{RNG}, \cvCppCross{randu}
\cvCppFunc{randShuffle}
Shuffles the array elements randomly
\cvdefCpp{void randShuffle(Mat\& mtx, double iterFactor=1., RNG* rng=0);}
\begin{description}
\cvarg{mtx}{The input/output numerical 1D array}
\cvarg{iterFactor}{The scale factor that determines the number of random swap operations. See the discussion}
\cvarg{rng}{The optional random number generator used for shuffling. If it is zero, \cvCppCross{theRNG}() is used instead}
\end{description}
The function \texttt{randShuffle} shuffles the specified 1D array by randomly choosing pairs of elements and swapping them. The number of such swap operations will be \texttt{mtx.rows*mtx.cols*iterFactor}
See also: \cvCppCross{RNG}, \cvCppCross{sort}
\cvCppFunc{reduce}
Reduces a matrix to a vector
\cvdefCpp{void reduce(const Mat\& mtx, Mat\& vec, \par int dim, int reduceOp, int dtype=-1);}
\begin{description}
\cvarg{mtx}{The source 2D matrix}
\cvarg{vec}{The destination vector. Its size and type is defined by \texttt{dim} and \texttt{dtype} parameters}
\cvarg{dim}{The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row and 1 means that the matrix is reduced to a single column}
\cvarg{reduceOp}{The reduction operation, one of:
\begin{description}
\cvarg{CV\_REDUCE\_SUM}{The output is the sum of all of the matrix's rows/columns.}
\cvarg{CV\_REDUCE\_AVG}{The output is the mean vector of all of the matrix's rows/columns.}
\cvarg{CV\_REDUCE\_MAX}{The output is the maximum (column/row-wise) of all of the matrix's rows/columns.}
\cvarg{CV\_REDUCE\_MIN}{The output is the minimum (column/row-wise) of all of the matrix's rows/columns.}
\end{description}}
\cvarg{dtype}{When it is negative, the destination vector will have the same type as the source matrix, otherwise, its type will be \texttt{CV\_MAKE\_TYPE(CV\_MAT\_DEPTH(dtype), mtx.channels())}}
\end{description}
The function \texttt{reduce} reduces matrix to a vector by treating the matrix rows/columns as a set of 1D vectors and performing the specified operation on the vectors until a single row/column is obtained. For example, the function can be used to compute horizontal and vertical projections of an raster image. In the case of \texttt{CV\_REDUCE\_SUM} and \texttt{CV\_REDUCE\_AVG} the output may have a larger element bit-depth to preserve accuracy. And multi-channel arrays are also supported in these two reduction modes.
See also: \cvCppCross{repeat}
\cvCppFunc{repeat}
Fill the destination array with repeated copies of the source array.
\cvdefCpp{void repeat(const Mat\& src, int ny, int nx, Mat\& dst);\newline
Mat repeat(const Mat\& src, int ny, int nx);}
\begin{description}
\cvarg{src}{The source array to replicate}
\cvarg{dst}{The destination array; will have the same type as \texttt{src}}
\cvarg{ny}{How many times the \texttt{src} is repeated along the vertical axis}
\cvarg{nx}{How many times the \texttt{src} is repeated along the horizontal axis}
\end{description}
The functions \cvCppCross{repeat} duplicate the source array one or more times along each of the two axes:
\[\texttt{dst}_{ij}=\texttt{src}_{i\mod\texttt{src.rows},\;j\mod\texttt{src.cols}}\]
The second variant of the function is more convenient to use with \cross{Matrix Expressions}
See also: \cvCppCross{reduce}, \cross{Matrix Expressions}
\ifplastex
\cvfunc{saturate\_cast}\label{cppfunc.saturatecast}
\else
\subsection{saturate\_cast}\label{cppfunc.saturatecast}
\fi
Template function for accurate conversion from one primitive type to another
\cvdefCpp{template<typename \_Tp> inline \_Tp saturate\_cast(unsigned char v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(signed char v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(unsigned short v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(signed short v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(int v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(unsigned int v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(float v);\newline
template<typename \_Tp> inline \_Tp saturate\_cast(double v);}
\begin{description}
\cvarg{v}{The function parameter}
\end{description}
The functions \texttt{saturate\_cast} resembles the standard C++ cast operations, such as \texttt{static\_cast<T>()} etc. They perform an efficient and accurate conversion from one primitive type to another, see the introduction. "saturate" in the name means that when the input value \texttt{v} is out of range of the target type, the result will not be formed just by taking low bits of the input, but instead the value will be clipped. For example:
\begin{lstlisting}
uchar a = saturate_cast<uchar>(-100); // a = 0 (UCHAR_MIN)
short b = saturate_cast<short>(33333.33333); // b = 32767 (SHRT_MAX)
\end{lstlisting}
Such clipping is done when the target type is \texttt{unsigned char, signed char, unsigned short or signed short} - for 32-bit integers no clipping is done.
When the parameter is floating-point value and the target type is an integer (8-, 16- or 32-bit), the floating-point value is first rounded to the nearest integer and then clipped if needed (when the target type is 8- or 16-bit).
This operation is used in most simple or complex image processing functions in OpenCV.
See also: \cvCppCross{add}, \cvCppCross{subtract}, \cvCppCross{multiply}, \cvCppCross{divide}, \cvCppCross{Mat::convertTo}
\cvCppFunc{scaleAdd}
Calculates the sum of a scaled array and another array.
\cvdefCpp{void scaleAdd(const Mat\& src1, double scale, \par const Mat\& src2, Mat\& dst);\newline
void scaleAdd(const MatND\& src1, double scale, \par const MatND\& src2, MatND\& dst);}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{scale}{Scale factor for the first array}
\cvarg{src2}{The second source array; must have the same size and the same type as \texttt{src1}}
\cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src1}}
\end{description}
The function \texttt{cvScaleAdd} is one of the classical primitive linear algebra operations, known as \texttt{DAXPY} or \texttt{SAXPY} in \href{http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms}{BLAS}. It calculates the sum of a scaled array and another array:
\[
\texttt{dst}(I)=\texttt{scale} \cdot \texttt{src1}(I) + \texttt{src2}(I)
\]
The function can also be emulated with a matrix expression, for example:
\begin{lstlisting}
Mat A(3, 3, CV_64F);
...
A.row(0) = A.row(1)*2 + A.row(2);
\end{lstlisting}
See also: \cvCppCross{add}, \cvCppCross{addWeighted}, \cvCppCross{subtract}, \cvCppCross{Mat::dot}, \cvCppCross{Mat::convertTo}, \cross{Matrix Expressions}
\cvCppFunc{setIdentity}
Initializes a scaled identity matrix
\cvdefCpp{void setIdentity(Mat\& dst, const Scalar\& value=Scalar(1));}
\begin{description}
\cvarg{dst}{The matrix to initialize (not necessarily square)}
\cvarg{value}{The value to assign to the diagonal elements}
\end{description}
The function \cvCppCross{setIdentity} initializes a scaled identity matrix:
\[
\texttt{dst}(i,j)=\fork{\texttt{value}}{ if $i=j$}{0}{otherwise}
\]
The function can also be emulated using the matrix initializers and the matrix expressions:
\begin{lstlisting}
Mat A = Mat::eye(4, 3, CV_32F)*5;
// A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
\end{lstlisting}
See also: \cvCppCross{Mat::zeros}, \cvCppCross{Mat::ones}, \cross{Matrix Expressions},
\cvCppCross{Mat::setTo}, \cvCppCross{Mat::operator=},
\cvCppFunc{solve}
Solves one or more linear systems or least-squares problems.
\cvdefCpp{bool solve(const Mat\& src1, const Mat\& src2, \par Mat\& dst, int flags=DECOMP\_LU);}
\begin{description}
\cvarg{src1}{The input matrix on the left-hand side of the system}
\cvarg{src2}{The input matrix on the right-hand side of the system}
\cvarg{dst}{The output solution}
\cvarg{flags}{The solution (matrix inversion) method
\begin{description}
\cvarg{DECOMP\_LU}{Gaussian elimination with optimal pivot element chosen}
\cvarg{DECOMP\_CHOLESKY}{Cholesky $LL^T$ factorization; the matrix \texttt{src1} must be symmetrical and positively defined}
\cvarg{DECOMP\_EIG}{Eigenvalue decomposition; the matrix \texttt{src1} must be symmetrical}
\cvarg{DECOMP\_SVD}{Singular value decomposition (SVD) method; the system can be over-defined and/or the matrix \texttt{src1} can be singular}
\cvarg{DECOMP\_QR}{QR factorization; the system can be over-defined and/or the matrix \texttt{src1} can be singular}
\cvarg{DECOMP\_NORMAL}{While all the previous flags are mutually exclusive, this flag can be used together with any of the previous. It means that the normal equations $\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}$ are solved instead of the original system $\texttt{src1}\cdot\texttt{dst}=\texttt{src2}$}
\end{description}}
\end{description}
The function \texttt{solve} solves a linear system or least-squares problem (the latter is possible with SVD or QR methods, or by specifying the flag \texttt{DECOMP\_NORMAL}):
\[
\texttt{dst} = \arg \min_X\|\texttt{src1}\cdot\texttt{X} - \texttt{src2}\|
\]
If \texttt{DECOMP\_LU} or \texttt{DECOMP\_CHOLESKY} method is used, the function returns 1 if \texttt{src1} (or $\texttt{src1}^T\texttt{src1}$) is non-singular and 0 otherwise; in the latter case \texttt{dst} is not valid. Other methods find some pseudo-solution in the case of singular left-hand side part.
Note that if you want to find unity-norm solution of an under-defined singular system $\texttt{src1}\cdot\texttt{dst}=0$, the function \texttt{solve} will not do the work. Use \cvCppCross{SVD::solveZ} instead.
See also: \cvCppCross{invert}, \cvCppCross{SVD}, \cvCppCross{eigen}
\cvCppFunc{solveCubic}
Finds the real roots of a cubic equation.
\cvdefCpp{void solveCubic(const Mat\& coeffs, Mat\& roots);}
\begin{description}
\cvarg{coeffs}{The equation coefficients, an array of 3 or 4 elements}
\cvarg{roots}{The destination array of real roots which will have 1 or 3 elements}
\end{description}
The function \texttt{solveCubic} finds the real roots of a cubic equation:
(if coeffs is a 4-element vector)
\[
\texttt{coeffs}[0] x^3 + \texttt{coeffs}[1] x^2 + \texttt{coeffs}[2] x + \texttt{coeffs}[3] = 0
\]
or (if coeffs is 3-element vector):
\[
x^3 + \texttt{coeffs}[0] x^2 + \texttt{coeffs}[1] x + \texttt{coeffs}[2] = 0
\]
The roots are stored to \texttt{roots} array.
\cvCppFunc{solvePoly}
Finds the real or complex roots of a polynomial equation
\cvdefCpp{void solvePoly(const Mat\& coeffs, Mat\& roots, \par int maxIters=20, int fig=100);}
\begin{description}
\cvarg{coeffs}{The array of polynomial coefficients}
\cvarg{roots}{The destination (complex) array of roots}
\cvarg{maxIters}{The maximum number of iterations the algorithm does}
\cvarg{fig}{}
\end{description}
The function \texttt{solvePoly} finds real and complex roots of a polynomial equation:
\[
\texttt{coeffs}[0] x^{n} + \texttt{coeffs}[1] x^{n-1} + ... + \texttt{coeffs}[n-1] x + \texttt{coeffs}[n] = 0
\]
\cvCppFunc{sort}
Sorts each row or each column of a matrix
\cvdefCpp{void sort(const Mat\& src, Mat\& dst, int flags);}
\begin{description}
\cvarg{src}{The source single-channel array}
\cvarg{dst}{The destination array of the same size and the same type as \texttt{src}}
\cvarg{flags}{The operation flags, a combination of the following values:
\begin{description}
\cvarg{CV\_SORT\_EVERY\_ROW}{Each matrix row is sorted independently}
\cvarg{CV\_SORT\_EVERY\_COLUMN}{Each matrix column is sorted independently. This flag and the previous one are mutually exclusive}
\cvarg{CV\_SORT\_ASCENDING}{Each matrix row is sorted in the ascending order}
\cvarg{CV\_SORT\_DESCENDING}{Each matrix row is sorted in the descending order. This flag and the previous one are also mutually exclusive}
\end{description}}
\end{description}
The function \texttt{sort} sorts each matrix row or each matrix column in ascending or descending order. If you want to sort matrix rows or columns lexicographically, you can use STL \texttt{std::sort} generic function with the proper comparison predicate.
See also: \cvCppCross{sortIdx}, \cvCppCross{randShuffle}
\cvCppFunc{sortIdx}
Sorts each row or each column of a matrix
\cvdefCpp{void sortIdx(const Mat\& src, Mat\& dst, int flags);}
\begin{description}
\cvarg{src}{The source single-channel array}
\cvarg{dst}{The destination integer array of the same size as \texttt{src}}
\cvarg{flags}{The operation flags, a combination of the following values:
\begin{description}
\cvarg{CV\_SORT\_EVERY\_ROW}{Each matrix row is sorted independently}
\cvarg{CV\_SORT\_EVERY\_COLUMN}{Each matrix column is sorted independently. This flag and the previous one are mutually exclusive}
\cvarg{CV\_SORT\_ASCENDING}{Each matrix row is sorted in the ascending order}
\cvarg{CV\_SORT\_DESCENDING}{Each matrix row is sorted in the descending order. This flag and the previous one are also mutually exclusive}
\end{description}}
\end{description}
The function \texttt{sortIdx} sorts each matrix row or each matrix column in ascending or descending order. Instead of reordering the elements themselves, it stores the indices of sorted elements in the destination array. For example:
\begin{lstlisting}
Mat A = Mat::eye(3,3,CV_32F), B;
sortIdx(A, B, CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
// B will probably contain
// (because of equal elements in A some permutations are possible):
// [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
\end{lstlisting}
See also: \cvCppCross{sort}, \cvCppCross{randShuffle}
\cvCppFunc{split}
Divides multi-channel array into several single-channel arrays
\cvdefCpp{void split(const Mat\& mtx, Mat* mv);\newline
void split(const Mat\& mtx, vector<Mat>\& mv);\newline
void split(const MatND\& mtx, MatND* mv);\newline
void split(const MatND\& mtx, vector<MatND>\& mv);}
\begin{description}
\cvarg{mtx}{The source multi-channel array}
\cvarg{mv}{The destination array or vector of arrays; The number of arrays must match \texttt{mtx.channels()}. The arrays themselves will be reallocated if needed}
\end{description}
The functions \texttt{split} split multi-channel array into separate single-channel arrays:
\[ \texttt{mv}[c](I) = \texttt{mtx}(I)_c \]
If you need to extract a single-channel or do some other sophisticated channel permutation, use \cvCppCross{mixChannels}
See also: \cvCppCross{merge}, \cvCppCross{mixChannels}, \cvCppCross{cvtColor}
\cvCppFunc{sqrt}
Calculates square root of array elements
\cvdefCpp{void sqrt(const Mat\& src, Mat\& dst);\newline
void sqrt(const MatND\& src, MatND\& dst);}
\begin{description}
\cvarg{src}{The source floating-point array}
\cvarg{dst}{The destination array; will have the same size and the same type as \texttt{src}}
\end{description}
The functions \texttt{sqrt} calculate square root of each source array element. in the case of multi-channel arrays each channel is processed independently. The function accuracy is approximately the same as of the built-in \texttt{std::sqrt}.
See also: \cvCppCross{pow}, \cvCppCross{magnitude}
\cvCppFunc{subtract}
Calculates per-element difference between two arrays or array and a scalar
\cvdefCpp{void subtract(const Mat\& src1, const Mat\& src2, Mat\& dst);\newline
void subtract(const Mat\& src1, const Mat\& src2, \par Mat\& dst, const Mat\& mask);\newline
void subtract(const Mat\& src1, const Scalar\& sc, \par Mat\& dst, const Mat\& mask=Mat());\newline
void subtract(const Scalar\& sc, const Mat\& src2, \par Mat\& dst, const Mat\& mask=Mat());\newline
void subtract(const MatND\& src1, const MatND\& src2, MatND\& dst);\newline
void subtract(const MatND\& src1, const MatND\& src2, \par MatND\& dst, const MatND\& mask);\newline
void subtract(const MatND\& src1, const Scalar\& sc, \par MatND\& dst, const MatND\& mask=MatND());\newline
void subtract(const Scalar\& sc, const MatND\& src2, \par MatND\& dst, const MatND\& mask=MatND());}
\begin{description}
\cvarg{src1}{The first source array}
\cvarg{src2}{The second source array. It must have the same size and same type as \texttt{src1}}
\cvarg{sc}{Scalar; the first or the second input parameter}
\cvarg{dst}{The destination array; it will have the same size and same type as \texttt{src1}; see \texttt{Mat::create}}
\cvarg{mask}{The optional operation mask, 8-bit single channel array;
specifies elements of the destination array to be changed}
\end{description}
The functions \texttt{subtract} compute
\begin{itemize}
\item the difference between two arrays
\[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) - \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
\item the difference between array and a scalar:
\[\texttt{dst}(I) = \texttt{saturate}(\texttt{src1}(I) - \texttt{sc})\quad\texttt{if mask}(I)\ne0\]
\item the difference between scalar and an array:
\[\texttt{dst}(I) = \texttt{saturate}(\texttt{sc} - \texttt{src2}(I))\quad\texttt{if mask}(I)\ne0\]
\end{itemize}
where \texttt{I} is multi-dimensional index of array elements.
The first function in the above list can be replaced with matrix expressions:
\begin{lstlisting}
dst = src1 - src2;
dst -= src2; // equivalent to subtract(dst, src2, dst);
\end{lstlisting}
See also: \cvCppCross{add}, \cvCppCross{addWeighted}, \cvCppCross{scaleAdd}, \cvCppCross{convertScale},
\cross{Matrix Expressions}, \hyperref[cppfunc.saturatecast]{saturate\_cast}.
\cvclass{SVD}
Class for computing Singular Value Decomposition
\begin{lstlisting}
class SVD
{
public:
enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };
// default empty constructor
SVD();
// decomposes A into u, w and vt: A = u*w*vt;
// u and vt are orthogonal, w is diagonal
SVD( const Mat& A, int flags=0 );
// decomposes A into u, w and vt.
SVD& operator ()( const Mat& A, int flags=0 );
// finds such vector x, norm(x)=1, so that A*x = 0,
// where A is singular matrix
static void solveZ( const Mat& A, Mat& x );
// does back-subsitution:
// x = vt.t()*inv(w)*u.t()*rhs ~ inv(A)*rhs
void backSubst( const Mat& rhs, Mat& x ) const;
Mat u, w, vt;
};
\end{lstlisting}
The class \texttt{SVD} is used to compute Singular Value Decomposition of a floating-point matrix and then use it to solve least-square problems, under-determined linear systems, invert matrices, compute condition numbers etc.
For a bit faster operation you can pass \texttt{flags=SVD::MODIFY\_A|...} to modify the decomposed matrix when it is not necessarily to preserve it. If you want to compute condition number of a matrix or absolute value of its determinant - you do not need \texttt{u} and \texttt{vt}, so you can pass \texttt{flags=SVD::NO\_UV|...}. Another flag \texttt{FULL\_UV} indicates that full-size \texttt{u} and \texttt{vt} must be computed, which is not necessary most of the time.
See also: \cvCppCross{invert}, \cvCppCross{solve}, \cvCppCross{eigen}, \cvCppCross{determinant}
\cvCppFunc{SVD::SVD}
SVD constructors
\cvdefCpp{
SVD::SVD();\newline
SVD::SVD( const Mat\& A, int flags=0 );
}
\begin{description}
\cvarg{A}{The decomposed matrix}
\cvarg{flags}{Operation flags}
\begin{description}
\cvarg{SVD::MODIFY\_A}{The algorithm can modify the decomposed matrix. It can save some space and speed-up processing a bit}
\cvarg{SVD::NO\_UV}{Only singular values are needed. The algorithm will not compute \texttt{U} and \texttt{V} matrices}
\cvarg{SVD::FULL\_UV}{When the matrix is not square, by default the algorithm produces \texttt{U} and \texttt{V} matrices of sufficiently large size for the further \texttt{A} reconstruction. If, however, \texttt{FULL\_UV} flag is specified, \texttt{U} and \texttt{V} will be full-size square orthogonal matrices.}
\end{description}
\end{description}
The first constructor initializes empty \texttt{SVD} structure. The second constructor initializes empty \texttt{SVD} structure and then calls \cvCppCross{SVD::operator ()}.
\cvCppFunc{SVD::operator ()}
Performs SVD of a matrix
\cvdefCpp{
SVD\& SVD::operator ()( const Mat\& A, int flags=0 );
}
\begin{description}
\cvarg{A}{The decomposed matrix}
\cvarg{flags}{Operation flags}
\begin{description}
\cvarg{SVD::MODIFY\_A}{The algorithm can modify the decomposed matrix. It can save some space and speed-up processing a bit}
\cvarg{SVD::NO\_UV}{Only singular values are needed. The algorithm will not compute \texttt{U} and \texttt{V} matrices}
\cvarg{SVD::FULL\_UV}{When the matrix is not square, by default the algorithm produces \texttt{U} and \texttt{V} matrices of sufficiently large size for the further \texttt{A} reconstruction. If, however, \texttt{FULL\_UV} flag is specified, \texttt{U} and \texttt{V} will be full-size square orthogonal matrices.}
\end{description}
\end{description}
The operator performs singular value decomposition of the supplied matrix. The \texttt{U}, transposed \texttt{V} and the diagonal of \texttt{W} are stored in the structure. The same \texttt{SVD} structure can be reused many times with different matrices. Each time, if needed, the previous \texttt{u}, \texttt{vt} and \texttt{w} are reclaimed and the new matrices are created, which is all handled by \cvCppCross{Mat::create}.
\cvCppFunc{SVD::solveZ}
Solves under-determined singular linear system
\cvdefCpp{
static void SVD::solveZ( const Mat\& A, Mat\& x );
}
\begin{description}
\cvarg{A}{The left-hand-side matrix.}
\cvarg{x}{The found solution}
\end{description}
The method finds unit-length solution \textbf{x} of the under-determined system $A x = 0$. Theory says that such system has infinite number of solutions, so the algorithm finds the unit-length solution as the right singular vector corresponding to the smallest singular value (which should be 0). In practice, because of round errors and limited floating-point accuracy, the input matrix can appear to be close-to-singular rather than just singular. So, strictly speaking, the algorithm solves the following problem:
\[
x^* = \arg \min_{x: \|x\|=1} \|A \cdot x \|
\]
\cvCppFunc{SVD::backSubst}
Performs singular value back substitution
\cvdefCpp{
void SVD::backSubst( const Mat\& rhs, Mat\& x ) const;
}
\begin{description}
\cvarg{rhs}{The right-hand side of a linear system $\texttt{A} \texttt{x} = \texttt{rhs}$ being solved, where \texttt{A} is the matrix passed to \cvCppCross{SVD::SVD} or \cvCppCross{SVD::operator ()}}
\cvarg{x}{The found solution of the system}
\end{description}
The method computes back substitution for the specified right-hand side:
\[
\texttt{x} = \texttt{vt}^T \cdot diag(\texttt{w})^{-1} \cdot \texttt{u}^T \cdot \texttt{rhs} \sim \texttt{A}^{-1} \cdot \texttt{rhs}
\]
Using this technique you can either get a very accurate solution of convenient linear system, or the best (in the least-squares terms) pseudo-solution of an overdetermined linear system. Note that explicit SVD with the further back substitution only makes sense if you need to solve many linear systems with the same left-hand side (e.g. \texttt{A}). If all you need is to solve a single system (possibly with multiple \texttt{rhs} immediately available), simply call \cvCppCross{solve} add pass \texttt{cv::DECOMP\_SVD} there - it will do absolutely the same thing.
\cvCppFunc{sum}
Calculates sum of array elements
\cvdefCpp{Scalar sum(const Mat\& mtx);\newline
Scalar sum(const MatND\& mtx);}
\begin{description}
\cvarg{mtx}{The source array; must have 1 to 4 channels}
\end{description}
The functions \texttt{sum} calculate and return the sum of array elements, independently for each channel.
See also: \cvCppCross{countNonZero}, \cvCppCross{mean}, \cvCppCross{meanStdDev}, \cvCppCross{norm}, \cvCppCross{minMaxLoc}, \cvCppCross{reduce}
\cvCppFunc{theRNG}
Returns the default random number generator
\cvdefCpp{RNG\& theRNG();}
The function \texttt{theRNG} returns the default random number generator. For each thread there is separate random number generator, so you can use the function safely in multi-thread environments. If you just need to get a single random number using this generator or initialize an array, you can use \cvCppCross{randu} or \cvCppCross{randn} instead. But if you are going to generate many random numbers inside a loop, it will be much faster to use this function to retrieve the generator and then use \texttt{RNG::operator \_Tp()}.
See also: \cvCppCross{RNG}, \cvCppCross{randu}, \cvCppCross{randn}
\cvCppFunc{trace}
Returns the trace of a matrix
\cvdefCpp{Scalar trace(const Mat\& mtx);}
\begin{description}
\cvarg{mtx}{The source matrix}
\end{description}
The function \texttt{trace} returns the sum of the diagonal elements of the matrix \texttt{mtx}.
\[ \mathrm{tr}(\texttt{mtx}) = \sum_i \texttt{mtx}(i,i) \]
\cvCppFunc{transform}
Performs matrix transformation of every array element.
\cvdefCpp{void transform(const Mat\& src, \par Mat\& dst, const Mat\& mtx );}
\begin{description}
\cvarg{src}{The source array; must have as many channels (1 to 4) as \texttt{mtx.cols} or \texttt{mtx.cols-1}}
\cvarg{dst}{The destination array; will have the same size and depth as \texttt{src} and as many channels as \texttt{mtx.rows}}
\cvarg{mtx}{The transformation matrix}
\end{description}
The function \texttt{transform} performs matrix transformation of every element of array \texttt{src} and stores the results in \texttt{dst}:
\[
\texttt{dst}(I) = \texttt{mtx} \cdot \texttt{src}(I)
\]
(when \texttt{mtx.cols=src.channels()}), or
\[
\texttt{dst}(I) = \texttt{mtx} \cdot [\texttt{src}(I); 1]
\]
(when \texttt{mtx.cols=src.channels()+1})
That is, every element of an \texttt{N}-channel array \texttt{src} is
considered as \texttt{N}-element vector, which is transformed using
a $\texttt{M} \times \texttt{N}$ or $\texttt{M} \times \texttt{N+1}$ matrix \texttt{mtx} into
an element of \texttt{M}-channel array \texttt{dst}.
The function may be used for geometrical transformation of $N$-dimensional
points, arbitrary linear color space transformation (such as various kinds of RGB$\rightarrow$YUV transforms), shuffling the image channels and so forth.
See also: \cvCppCross{perspectiveTransform}, \cvCppCross{getAffineTransform}, \cvCppCross{estimateRigidTransform}, \cvCppCross{warpAffine}, \cvCppCross{warpPerspective}
\cvCppFunc{transpose}
Transposes a matrix
\cvdefCpp{void transpose(const Mat\& src, Mat\& dst);}
\begin{description}
\cvarg{src}{The source array}
\cvarg{dst}{The destination array of the same type as \texttt{src}}
\end{description}
The function \cvCppCross{transpose} transposes the matrix \texttt{src}:
\[ \texttt{dst}(i,j) = \texttt{src}(j,i) \]
Note that no complex conjugation is done in the case of a complex
matrix, it should be done separately if needed.
\fi
|