Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 'use client' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { OpenCvProvider, useOpenCv } from 'opencv-react' import { css } from '../../../../styled-system/css' import { useQuadDetection, type DetectedQuad, type TrackedQuad, type Point, type DebugPolygon, type QuadDetectorConfig, } from '@/lib/vision/useQuadDetection' import type { PreprocessingStrategy } from '@/lib/vision/quadDetector' /** * Test page for quad detection. * Uses opencv-react for loading OpenCV, and the new useQuadDetection hook. * * Step 5: Testing useQuadDetection hook */ export default function QuadTestPage() { return ( <OpenCvProvider openCvPath="/opencv.js"> <QuadTestContent /> </OpenCvProvider> ) } function QuadTestContent() { const videoRef = useRef<HTMLVideoElement>(null) const overlayRef = useRef<HTMLCanvasElement>(null) const [isCameraActive, setIsCameraActive] = useState(false) const [cameraError, setCameraError] = useState<string | null>(null) const streamRef = useRef<MediaStream | null>(null) const animationFrameRef = useRef<number | null>(null) // Static image testing const [staticImageCanvas, setStaticImageCanvas] = useState<HTMLCanvasElement | null>(null) const [staticDetectionResult, setStaticDetectionResult] = useState<{ detected: boolean quads: DetectedQuad[] corners: Point[] detectionTimeMs: number } | null>(null) // Debug mode toggle const [debugMode, setDebugMode] = useState(true) // Detection profiles for different scenarios type DetectionProfile = { name: string description: string strategy: PreprocessingStrategy histogramEqualization: boolean adaptiveThreshold: boolean morphGradient: boolean blockSize: number adaptiveC: number cannyLow: number cannyHigh: number houghLines: boolean houghThreshold: number houghMinLineLength: number houghMaxLineGap: number // Optional detector config overrides minAreaRatio?: number maxAreaRatio?: number } const DETECTION_PROFILES: Record<string, DetectionProfile> = { balanced: { name: 'Balanced', description: 'Good all-around detection for typical conditions', strategy: 'multi', histogramEqualization: true, adaptiveThreshold: true, morphGradient: true, blockSize: 11, adaptiveC: 2, cannyLow: 50, cannyHigh: 150, houghLines: true, houghThreshold: 50, houghMinLineLength: 50, houghMaxLineGap: 10, }, lowContrast: { name: 'Low Contrast', description: 'For faded, washed-out, or poorly lit documents', strategy: 'multi', histogramEqualization: true, adaptiveThreshold: true, morphGradient: true, blockSize: 15, adaptiveC: 5, cannyLow: 20, cannyHigh: 80, houghLines: true, houghThreshold: 30, houghMinLineLength: 40, houghMaxLineGap: 20, }, highContrast: { name: 'High Contrast', description: 'For well-lit documents with clear edges', strategy: 'standard', histogramEqualization: false, adaptiveThreshold: false, morphGradient: false, blockSize: 11, adaptiveC: 2, cannyLow: 80, cannyHigh: 200, houghLines: false, houghThreshold: 50, houghMinLineLength: 50, houghMaxLineGap: 10, }, fingerOcclusion: { name: 'Finger Occlusion', description: 'When hands are covering document edges', strategy: 'multi', histogramEqualization: true, adaptiveThreshold: true, morphGradient: true, blockSize: 11, adaptiveC: 2, cannyLow: 40, cannyHigh: 120, houghLines: true, houghThreshold: 30, houghMinLineLength: 30, houghMaxLineGap: 30, }, complexBackground: { name: 'Complex Background', description: 'For busy backgrounds with many edges', strategy: 'enhanced', histogramEqualization: true, adaptiveThreshold: false, morphGradient: false, blockSize: 11, adaptiveC: 2, cannyLow: 80, cannyHigh: 200, houghLines: true, houghThreshold: 70, houghMinLineLength: 80, houghMaxLineGap: 5, minAreaRatio: 0.2, }, bookPages: { name: 'Book Pages', description: 'For detecting pages in open books', strategy: 'multi', histogramEqualization: true, adaptiveThreshold: true, morphGradient: false, blockSize: 9, adaptiveC: 3, cannyLow: 30, cannyHigh: 100, houghLines: true, houghThreshold: 40, houghMinLineLength: 40, houghMaxLineGap: 15, minAreaRatio: 0.08, maxAreaRatio: 0.6, }, aggressive: { name: 'Aggressive', description: 'Maximum edge detection - may have false positives', strategy: 'multi', histogramEqualization: true, adaptiveThreshold: true, morphGradient: true, blockSize: 7, adaptiveC: 0, cannyLow: 15, cannyHigh: 50, houghLines: true, houghThreshold: 20, houghMinLineLength: 20, houghMaxLineGap: 40, minAreaRatio: 0.05, }, } // Active profile const [activeProfile, setActiveProfile] = useState<string>('balanced') // Preprocessing config defaults (matches 'balanced' profile) const PREPROCESSING_DEFAULTS = DETECTION_PROFILES.balanced const STORAGE_KEY = 'quad-detection-preprocessing' // Preprocessing config state - initialize with defaults to avoid hydration mismatch const [preprocessingStrategy, setPreprocessingStrategy] = useState<PreprocessingStrategy>( PREPROCESSING_DEFAULTS.strategy ) const [enableHistogramEqualization, setEnableHistogramEqualization] = useState( PREPROCESSING_DEFAULTS.histogramEqualization ) const [enableAdaptiveThreshold, setEnableAdaptiveThreshold] = useState( PREPROCESSING_DEFAULTS.adaptiveThreshold ) const [enableMorphGradient, setEnableMorphGradient] = useState( PREPROCESSING_DEFAULTS.morphGradient ) const [adaptiveBlockSize, setAdaptiveBlockSize] = useState(PREPROCESSING_DEFAULTS.blockSize) const [adaptiveC, setAdaptiveC] = useState(PREPROCESSING_DEFAULTS.adaptiveC) const [cannyLow, setCannyLow] = useState(PREPROCESSING_DEFAULTS.cannyLow) const [cannyHigh, setCannyHigh] = useState(PREPROCESSING_DEFAULTS.cannyHigh) // Hough line detection const [enableHoughLines, setEnableHoughLines] = useState(PREPROCESSING_DEFAULTS.houghLines) const [houghThreshold, setHoughThreshold] = useState(PREPROCESSING_DEFAULTS.houghThreshold) const [houghMinLineLength, setHoughMinLineLength] = useState( PREPROCESSING_DEFAULTS.houghMinLineLength ) const [houghMaxLineGap, setHoughMaxLineGap] = useState(PREPROCESSING_DEFAULTS.houghMaxLineGap) // Track if we've loaded from storage const hasLoadedFromStorage = useRef(false) const [isSettingsLoaded, setIsSettingsLoaded] = useState(false) // Load from localStorage on mount (client-side only, after hydration) useEffect(() => { if (hasLoadedFromStorage.current) return hasLoadedFromStorage.current = true try { const stored = localStorage.getItem(STORAGE_KEY) if (stored) { const settings = JSON.parse(stored) if (settings.strategy) setPreprocessingStrategy(settings.strategy) if (settings.histogramEqualization !== undefined) setEnableHistogramEqualization(settings.histogramEqualization) if (settings.adaptiveThreshold !== undefined) setEnableAdaptiveThreshold(settings.adaptiveThreshold) if (settings.morphGradient !== undefined) setEnableMorphGradient(settings.morphGradient) if (settings.blockSize !== undefined) setAdaptiveBlockSize(settings.blockSize) if (settings.adaptiveC !== undefined) setAdaptiveC(settings.adaptiveC) if (settings.cannyLow !== undefined) setCannyLow(settings.cannyLow) if (settings.cannyHigh !== undefined) setCannyHigh(settings.cannyHigh) // Hough line settings if (settings.houghLines !== undefined) setEnableHoughLines(settings.houghLines) if (settings.houghThreshold !== undefined) setHoughThreshold(settings.houghThreshold) if (settings.houghMinLineLength !== undefined) setHoughMinLineLength(settings.houghMinLineLength) if (settings.houghMaxLineGap !== undefined) setHoughMaxLineGap(settings.houghMaxLineGap) } } catch { // Ignore parse errors } setIsSettingsLoaded(true) }, []) // Save to localStorage when settings change (skip until after initial load) useEffect(() => { if (!hasLoadedFromStorage.current) return // Don't save until we've loaded const settings = { strategy: preprocessingStrategy, histogramEqualization: enableHistogramEqualization, adaptiveThreshold: enableAdaptiveThreshold, morphGradient: enableMorphGradient, blockSize: adaptiveBlockSize, adaptiveC, cannyLow, cannyHigh, // Hough line settings houghLines: enableHoughLines, houghThreshold, houghMinLineLength, houghMaxLineGap, } localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)) }, [ preprocessingStrategy, enableHistogramEqualization, enableAdaptiveThreshold, enableMorphGradient, adaptiveBlockSize, adaptiveC, cannyLow, cannyHigh, enableHoughLines, houghThreshold, houghMinLineLength, houghMaxLineGap, ]) // Apply a profile const applyProfile = useCallback((profileKey: string) => { const profile = DETECTION_PROFILES[profileKey] if (!profile) return setActiveProfile(profileKey) setPreprocessingStrategy(profile.strategy) setEnableHistogramEqualization(profile.histogramEqualization) setEnableAdaptiveThreshold(profile.adaptiveThreshold) setEnableMorphGradient(profile.morphGradient) setAdaptiveBlockSize(profile.blockSize) setAdaptiveC(profile.adaptiveC) setCannyLow(profile.cannyLow) setCannyHigh(profile.cannyHigh) setEnableHoughLines(profile.houghLines) setHoughThreshold(profile.houghThreshold) setHoughMinLineLength(profile.houghMinLineLength) setHoughMaxLineGap(profile.houghMaxLineGap) }, []) // Reset to defaults (balanced profile) const resetPreprocessingSettings = useCallback(() => { applyProfile('balanced') localStorage.removeItem(STORAGE_KEY) }, [applyProfile]) // Build detector config from state - memoize to prevent detector recreation every frame const detectorConfig = useMemo<Partial<QuadDetectorConfig>>(() => { const profile = DETECTION_PROFILES[activeProfile] return { preprocessing: preprocessingStrategy, enableHistogramEqualization, enableAdaptiveThreshold, enableMorphGradient, adaptiveBlockSize, adaptiveC, cannyThresholds: [cannyLow, cannyHigh], // Hough line settings enableHoughLines, houghThreshold, houghMinLineLength, houghMaxLineGap, // Profile-specific area constraints ...(profile?.minAreaRatio !== undefined && { minAreaRatio: profile.minAreaRatio, }), ...(profile?.maxAreaRatio !== undefined && { maxAreaRatio: profile.maxAreaRatio, }), } }, [ activeProfile, preprocessingStrategy, enableHistogramEqualization, enableAdaptiveThreshold, enableMorphGradient, adaptiveBlockSize, adaptiveC, cannyLow, cannyHigh, enableHoughLines, houghThreshold, houghMinLineLength, houghMaxLineGap, ]) // Use the new combined hook with config const { isReady, isLoading, detectInImage, detectWithDebug, processFrame, stats, resetTracking } = useQuadDetection({ detector: detectorConfig }) // Also get raw opencv for load time measurement (test page specific) const { loaded: opencvLoaded } = useOpenCv() // Track load time for opencv-react const [loadStartTime] = useState(() => Date.now()) const [opencvLoadTime, setOpencvLoadTime] = useState<number | null>(null) useEffect(() => { if (opencvLoaded && !opencvLoadTime) { setOpencvLoadTime(Date.now() - loadStartTime) } }, [opencvLoaded, opencvLoadTime, loadStartTime]) // Load image to canvas utility const loadImageToCanvas = useCallback(async (file: File): Promise<HTMLCanvasElement | null> => { return new Promise((resolve) => { const img = new Image() const url = URL.createObjectURL(file) img.onload = () => { URL.revokeObjectURL(url) const canvas = document.createElement('canvas') canvas.width = img.naturalWidth canvas.height = img.naturalHeight const ctx = canvas.getContext('2d') if (!ctx) { resolve(null) return } ctx.drawImage(img, 0, 0) resolve(canvas) } img.onerror = () => { URL.revokeObjectURL(url) resolve(null) } img.src = url }) }, []) // Capture video frame to canvas const captureVideoFrame = useCallback((video: HTMLVideoElement): HTMLCanvasElement | null => { if (!video.videoWidth || !video.videoHeight) return null const canvas = document.createElement('canvas') canvas.width = video.videoWidth canvas.height = video.videoHeight const ctx = canvas.getContext('2d') if (!ctx) return null ctx.drawImage(video, 0, 0) return canvas }, []) // Handle static image upload const handleFileUpload = useCallback( async (e: React.ChangeEvent<HTMLInputElement>) => { const file = e.target.files?.[0] if (!file) return if (!isReady) { setCameraError('Detector not ready') return } const canvas = await loadImageToCanvas(file) if (!canvas) { setCameraError('Failed to load image') return } setStaticImageCanvas(canvas) // Run detection with timing const startTime = performance.now() try { const quads = detectInImage(canvas) const detectionTimeMs = performance.now() - startTime setStaticDetectionResult({ detected: quads.length > 0, quads, corners: quads[0]?.corners ?? getFallbackCorners(canvas.width, canvas.height), detectionTimeMs, }) setCameraError(null) } catch (err) { setCameraError(err instanceof Error ? err.message : 'Detection failed') setStaticDetectionResult(null) } }, [isReady, detectInImage, loadImageToCanvas] ) // Start camera const startCamera = useCallback(async () => { try { setCameraError(null) if (!isReady) { setCameraError('Detector not ready') return } const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 }, }, }) streamRef.current = stream if (videoRef.current) { videoRef.current.srcObject = stream await videoRef.current.play() setIsCameraActive(true) } } catch (err) { setCameraError(err instanceof Error ? err.message : 'Failed to start camera') } }, [isReady]) // Stop camera const stopCamera = useCallback(() => { if (animationFrameRef.current) { cancelAnimationFrame(animationFrameRef.current) animationFrameRef.current = null } if (streamRef.current) { streamRef.current.getTracks().forEach((track) => track.stop()) streamRef.current = null } if (videoRef.current) { videoRef.current.srcObject = null } setIsCameraActive(false) }, []) // Camera detection loop state const [cameraDebugInfo, setCameraDebugInfo] = useState<{ quadsDetected: number detectionTimeMs: number trackedCount: number bestStability: number bestFrameCount: number isStable: boolean isLocked: boolean debugPolygons: DebugPolygon[] }>({ quadsDetected: 0, detectionTimeMs: 0, // QuadTracker stats trackedCount: 0, bestStability: 0, bestFrameCount: 0, isStable: false, isLocked: false, debugPolygons: [], }) // Detection loop for camera useEffect(() => { if (!isCameraActive || !isReady) return // Reset tracker when camera starts resetTracking() let errorCount = 0 const MAX_CONSECUTIVE_ERRORS = 5 const runDetection = () => { if (videoRef.current && overlayRef.current) { const frame = captureVideoFrame(videoRef.current) if (frame) { const startTime = performance.now() try { if (debugMode) { // Use debug mode to see all candidate polygons const debugResult = detectWithDebug(frame) const detectionTimeMs = performance.now() - startTime setCameraDebugInfo({ quadsDetected: debugResult.quads.length, detectionTimeMs, trackedCount: 0, bestStability: 0, bestFrameCount: 0, isStable: false, isLocked: false, debugPolygons: debugResult.debugPolygons, }) // Draw overlay with debug polygons drawDebugOverlay( overlayRef.current, frame.width, frame.height, debugResult.quads, debugResult.debugPolygons ) } else { // Use the hook's processFrame which handles detection + tracking const result = processFrame(frame) const detectionTimeMs = performance.now() - startTime setCameraDebugInfo({ quadsDetected: result.detectedQuads.length, detectionTimeMs, trackedCount: result.stats.trackedCount, bestStability: result.stats.bestStability, bestFrameCount: result.stats.bestFrameCount, isStable: result.trackedQuad?.isStable ?? false, isLocked: result.trackedQuad?.isLocked ?? false, debugPolygons: [], }) // Draw overlay with tracked quad drawTrackedQuadOverlay( overlayRef.current, frame.width, frame.height, result.detectedQuads, result.trackedQuad ) } // Reset error count on success errorCount = 0 } catch (err) { errorCount++ // Only log occasionally to avoid console spam if (errorCount === 1 || errorCount === MAX_CONSECUTIVE_ERRORS) { console.error( `Detection error (${errorCount}x):`, typeof err === 'number' ? `OpenCV error code: ${err} (0x${err.toString(16)})` : err ) } // If too many errors, slow down to avoid hammering if (errorCount >= MAX_CONSECUTIVE_ERRORS) { console.warn('Too many detection errors, pausing for 1 second...') setTimeout(() => { errorCount = 0 animationFrameRef.current = requestAnimationFrame(runDetection) }, 1000) return } } } } animationFrameRef.current = requestAnimationFrame(runDetection) } runDetection() return () => { if (animationFrameRef.current) { cancelAnimationFrame(animationFrameRef.current) } } }, [ isCameraActive, isReady, debugMode, processFrame, detectWithDebug, resetTracking, captureVideoFrame, ]) // Cleanup on unmount useEffect(() => { return () => { stopCamera() } }, [stopCamera]) // Draw static detection result useEffect(() => { if (!staticImageCanvas || !staticDetectionResult) return const container = document.getElementById('static-image-container') if (!container) return container.innerHTML = '' const wrapper = document.createElement('div') wrapper.style.position = 'relative' wrapper.style.display = 'inline-block' // Add source image const imgCanvas = document.createElement('canvas') imgCanvas.width = staticImageCanvas.width imgCanvas.height = staticImageCanvas.height imgCanvas.style.maxWidth = '100%' imgCanvas.style.height = 'auto' const imgCtx = imgCanvas.getContext('2d') imgCtx?.drawImage(staticImageCanvas, 0, 0) wrapper.appendChild(imgCanvas) // Add overlay canvas const overlayCanvas = document.createElement('canvas') overlayCanvas.width = staticImageCanvas.width overlayCanvas.height = staticImageCanvas.height overlayCanvas.style.position = 'absolute' overlayCanvas.style.top = '0' overlayCanvas.style.left = '0' overlayCanvas.style.maxWidth = '100%' overlayCanvas.style.height = 'auto' overlayCanvas.style.pointerEvents = 'none' wrapper.appendChild(overlayCanvas) // Draw quad on overlay drawQuadOverlay( overlayCanvas, staticImageCanvas.width, staticImageCanvas.height, staticDetectionResult.quads ) container.appendChild(wrapper) }, [staticImageCanvas, staticDetectionResult]) return ( <div data-component="quad-test-page" className={css({ minHeight: '100vh', bg: 'gray.900', color: 'gray.100', p: 4, })} > <h1 className={css({ fontSize: '2xl', fontWeight: 'bold', mb: 4 })}> Quad Detection Test Page </h1> {/* Status bar */} <div className={css({ display: 'flex', gap: 4, mb: 4, p: 3, bg: 'gray.800', borderRadius: 'lg', flexWrap: 'wrap', })} > <StatusBadge label="opencv-react" status={opencvLoaded ? 'ready' : 'loading'} /> <StatusBadge label="useQuadDetection" status={isReady ? 'ready' : isLoading ? 'loading' : 'idle'} /> {cameraError && <span className={css({ color: 'red.400' })}>Error: {cameraError}</span>} </div> {/* Debug info */} <div className={css({ mb: 4, p: 3, bg: 'gray.800', borderRadius: 'lg', fontFamily: 'mono', fontSize: 'sm', })} > <div className={css({ fontWeight: 'bold', mb: 2 })}>Debug Info:</div> <div className={css({ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 2, })} > <div> opencv-react load: {opencvLoadTime ?? '-'}ms {opencvLoaded && ( <span className={css({ color: 'green.400', ml: 2 })}>✓ cv available</span> )} </div> <div> useQuadDetection:{' '} {isReady ? ( <span className={css({ color: 'green.400' })}>✓ ready</span> ) : ( <span className={css({ color: 'gray.500' })}>waiting...</span> )} </div> {isCameraActive && ( <> <div>Camera quads: {cameraDebugInfo.quadsDetected}</div> <div>Camera detection: {cameraDebugInfo.detectionTimeMs.toFixed(1)}ms</div> <div>Tracked quads: {cameraDebugInfo.trackedCount}</div> <div>Best stability: {(cameraDebugInfo.bestStability * 100).toFixed(0)}%</div> <div>Best frames: {cameraDebugInfo.bestFrameCount}</div> <div> Status:{' '} <span className={css({ color: cameraDebugInfo.isLocked ? 'green.400' : cameraDebugInfo.isStable ? 'yellow.400' : 'gray.400', })} > {cameraDebugInfo.isLocked ? 'LOCKED' : cameraDebugInfo.isStable ? 'STABLE' : 'tracking...'} </span> </div> </> )} {staticDetectionResult && ( <> <div>Static quads: {staticDetectionResult.quads.length}</div> <div>Static detection: {staticDetectionResult.detectionTimeMs.toFixed(1)}ms</div> </> )} </div> </div> {/* Two-column layout */} <div className={css({ display: 'grid', gridTemplateColumns: { base: '1fr', lg: '1fr 1fr' }, gap: 4, })} > {/* Camera section */} <div className={css({ bg: 'gray.800', borderRadius: 'lg', p: 4 })}> <h2 className={css({ fontSize: 'lg', fontWeight: 'bold', mb: 3 })}> Camera Feed (Real-time Detection) </h2> <div className={css({ mb: 3, display: 'flex', gap: 2, flexWrap: 'wrap', })} > {!isCameraActive ? ( <button type="button" onClick={startCamera} disabled={!isReady} className={css({ px: 4, py: 2, bg: 'blue.600', color: 'white', borderRadius: 'md', border: 'none', cursor: 'pointer', _hover: { bg: 'blue.500' }, _disabled: { opacity: 0.5, cursor: 'not-allowed' }, })} > {isLoading ? 'Loading OpenCV...' : !isReady ? 'Creating detector...' : 'Start Camera'} </button> ) : ( <button type="button" onClick={stopCamera} className={css({ px: 4, py: 2, bg: 'red.600', color: 'white', borderRadius: 'md', border: 'none', cursor: 'pointer', _hover: { bg: 'red.500' }, })} > Stop Camera </button> )} <button type="button" onClick={() => setDebugMode(!debugMode)} className={css({ px: 4, py: 2, bg: debugMode ? 'orange.600' : 'gray.600', color: 'white', borderRadius: 'md', border: 'none', cursor: 'pointer', _hover: { bg: debugMode ? 'orange.500' : 'gray.500' }, })} > {debugMode ? 'Debug ON' : 'Debug OFF'} </button> </div> {/* Preprocessing Controls */} <div className={css({ mb: 3, p: 3, bg: 'gray.700', borderRadius: 'md', opacity: isSettingsLoaded ? 1 : 0, transition: 'opacity 0.15s ease-in', })} > <div className={css({ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2, })} > <div className={css({ fontWeight: 'bold', fontSize: 'sm' })}> Preprocessing Controls </div> <button type="button" onClick={resetPreprocessingSettings} className={css({ px: 2, py: 1, fontSize: 'xs', bg: 'gray.600', color: 'gray.300', borderRadius: 'sm', border: 'none', cursor: 'pointer', _hover: { bg: 'gray.500', color: 'white' }, })} > Reset to Defaults </button> </div> {/* Profile Selector */} <div className={css({ mb: 3 })}> <div className={css({ fontSize: 'xs', color: 'gray.300', mb: 2, fontWeight: 'medium', })} > Quick Profiles </div> <div className={css({ display: 'flex', flexWrap: 'wrap', gap: 1, })} > {Object.entries(DETECTION_PROFILES).map(([key, profile]) => ( <button key={key} type="button" onClick={() => applyProfile(key)} title={profile.description} className={css({ px: 2, py: 1, fontSize: 'xs', bg: activeProfile === key ? 'blue.600' : 'gray.600', color: activeProfile === key ? 'white' : 'gray.300', borderRadius: 'sm', border: activeProfile === key ? '1px solid' : '1px solid transparent', borderColor: activeProfile === key ? 'blue.400' : 'transparent', cursor: 'pointer', transition: 'all 0.15s', _hover: { bg: activeProfile === key ? 'blue.500' : 'gray.500', color: 'white', }, })} > {profile.name} </button> ))} </div> {activeProfile && DETECTION_PROFILES[activeProfile] && ( <div className={css({ fontSize: 'xs', color: 'gray.400', mt: 2, lineHeight: 1.3, })} > <strong className={css({ color: 'gray.300' })}> {DETECTION_PROFILES[activeProfile].name}: </strong>{' '} {DETECTION_PROFILES[activeProfile].description} </div> )} </div> <div className={css({ fontSize: 'xs', color: 'gray.400', mb: 3, lineHeight: 1.4, })} > Select a profile above for quick setup, or adjust individual settings below. </div> {/* Strategy selector */} <div className={css({ mb: 3 })}> <label className={css({ display: 'block', fontSize: 'xs', color: 'gray.300', mb: 1, fontWeight: 'medium', })} > Strategy </label> <select value={preprocessingStrategy} onChange={(e) => setPreprocessingStrategy(e.target.value as PreprocessingStrategy)} className={css({ bg: 'gray.600', color: 'white', border: '1px solid', borderColor: 'gray.500', borderRadius: 'md', px: 2, py: 1, fontSize: 'sm', width: '100%', })} > <option value="standard">Standard - Basic edge detection</option> <option value="enhanced">Enhanced - Better for low contrast</option> <option value="adaptive">Adaptive - Best for uneven lighting</option> <option value="multi">Multi - Tries everything (recommended)</option> </select> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.3, })} > {preprocessingStrategy === 'standard' && 'Fast but needs good lighting and clear edges.'} {preprocessingStrategy === 'enhanced' && 'Boosts contrast first. Good for faded or washed-out images.'} {preprocessingStrategy === 'adaptive' && 'Handles shadows and uneven lighting. Good for documents on dark surfaces.'} {preprocessingStrategy === 'multi' && 'Combines all methods. Best detection but slightly slower.'} </div> </div> {/* Toggle switches with descriptions */} <div className={css({ mb: 3 })}> <div className={css({ fontSize: 'xs', color: 'gray.300', mb: 2, fontWeight: 'medium', })} > Enhancement Options </div> <div className={css({ display: 'flex', flexDirection: 'column', gap: 2, })} > <div> <ToggleSwitch label="Histogram Equalization" checked={enableHistogramEqualization} onChange={setEnableHistogramEqualization} /> <div className={css({ fontSize: 'xs', color: 'gray.500', ml: '44px', mt: '2px', })} > Spreads out brightness levels. Turn ON for low-contrast images. </div> </div> <div> <ToggleSwitch label="Adaptive Threshold" checked={enableAdaptiveThreshold} onChange={setEnableAdaptiveThreshold} /> <div className={css({ fontSize: 'xs', color: 'gray.500', ml: '44px', mt: '2px', })} > Detects edges locally. Turn ON when lighting is uneven across the document. </div> </div> <div> <ToggleSwitch label="Morphological Gradient" checked={enableMorphGradient} onChange={setEnableMorphGradient} /> <div className={css({ fontSize: 'xs', color: 'gray.500', ml: '44px', mt: '2px', })} > Finds edges by dilation-erosion. Turn ON for thick or blurry edges. </div> </div> </div> </div> {/* Sliders with descriptions */} <div className={css({ mb: 2 })}> <div className={css({ fontSize: 'xs', color: 'gray.300', mb: 2, fontWeight: 'medium', })} > Fine-Tuning </div> <div className={css({ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 3, })} > <div> <SliderControl label="Adaptive Block Size" value={adaptiveBlockSize} onChange={setAdaptiveBlockSize} min={3} max={31} step={2} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Neighborhood size for local thresholding. Larger = smoother edges, smaller = more detail. </div> </div> <div> <SliderControl label="Adaptive C" value={adaptiveC} onChange={setAdaptiveC} min={-10} max={20} step={1} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Threshold offset. Higher = fewer edges detected, lower = more noise. </div> </div> <div> <SliderControl label="Canny Low" value={cannyLow} onChange={setCannyLow} min={10} max={150} step={5} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Weak edge threshold. Lower = detect faint edges (more noise). </div> </div> <div> <SliderControl label="Canny High" value={cannyHigh} onChange={setCannyHigh} min={50} max={300} step={10} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Strong edge threshold. Lower = more edges, higher = only strong edges. </div> </div> </div> </div> {/* Hough Line Detection */} <div className={css({ mb: 3 })}> <div className={css({ fontSize: 'xs', color: 'gray.300', mb: 2, fontWeight: 'medium', })} > Hough Line Detection (Finger Occlusion) </div> <div> <ToggleSwitch label="Enable Hough Lines" checked={enableHoughLines} onChange={setEnableHoughLines} /> <div className={css({ fontSize: 'xs', color: 'gray.500', ml: '44px', mt: '2px', })} > Detects straight lines and infers corners from intersections. Fallback when contours fail. </div> </div> {enableHoughLines && ( <div className={css({ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 3, mt: 2, })} > <div> <SliderControl label="Threshold" value={houghThreshold} onChange={setHoughThreshold} min={20} max={100} step={5} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Min votes. Lower = more lines. </div> </div> <div> <SliderControl label="Min Length" value={houghMinLineLength} onChange={setHoughMinLineLength} min={20} max={150} step={10} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Min line segment length. </div> </div> <div> <SliderControl label="Max Gap" value={houghMaxLineGap} onChange={setHoughMaxLineGap} min={5} max={50} step={5} /> <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 1, lineHeight: 1.2, })} > Max gap to merge segments. </div> </div> </div> )} </div> {/* Quick tips */} <div className={css({ mt: 3, p: 2, bg: 'gray.800', borderRadius: 'sm', fontSize: 'xs', color: 'gray.400', })} > <strong className={css({ color: 'gray.300' })}>Tips:</strong> <ul className={css({ mt: 1, pl: 3, listStyleType: 'disc', lineHeight: 1.4, })} > <li>Document not detected? Lower Canny thresholds or enable Histogram Eq.</li> <li>Too many false edges? Raise Canny thresholds or increase Adaptive C.</li> <li> Fingers blocking edges? Enable Hough Lines - it finds edges by detecting straight lines and computing their intersections. </li> </ul> </div> </div> <div className={css({ position: 'relative', bg: 'black', borderRadius: 'md', overflow: 'hidden', })} > <video ref={videoRef} autoPlay playsInline muted className={css({ width: '100%', height: 'auto', display: isCameraActive ? 'block' : 'none', })} /> <canvas ref={overlayRef} className={css({ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', pointerEvents: 'none', })} /> {!isCameraActive && ( <div className={css({ width: '100%', height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'gray.500', })} > Camera not active </div> )} </div> {/* Debug polygon info */} {debugMode && isCameraActive && cameraDebugInfo.debugPolygons.length > 0 && ( <div className={css({ mt: 3, p: 2, bg: 'gray.700', borderRadius: 'md', fontSize: 'xs', maxHeight: '200px', overflow: 'auto', })} > <div className={css({ fontWeight: 'bold', mb: 2 })}> Candidate Polygons ({cameraDebugInfo.debugPolygons.length}): </div> {cameraDebugInfo.debugPolygons.slice(0, 10).map((poly, i) => ( <div key={i} className={css({ mb: 1, p: 1, bg: poly.status === 'accepted' ? 'green.900' : 'gray.800', borderRadius: 'sm', fontFamily: 'mono', })} > <span className={css({ color: poly.status === 'accepted' ? 'green.400' : poly.status === 'too_small' ? 'gray.500' : poly.status === 'too_large' ? 'red.400' : poly.status === 'bad_aspect_ratio' ? 'yellow.400' : 'orange.400', })} > [{poly.status}] </span>{' '} vertices: {poly.vertexCount}, area: {(poly.areaRatio * 100).toFixed(1)}% {poly.hullVertices && ` → hull: ${poly.hullVertices.length}`} {poly.aspectRatio && ` ratio: ${poly.aspectRatio.toFixed(2)}`} </div> ))} {cameraDebugInfo.debugPolygons.length > 10 && ( <div className={css({ color: 'gray.500' })}> ... and {cameraDebugInfo.debugPolygons.length - 10} more </div> )} </div> )} </div> {/* Static image section */} <div className={css({ bg: 'gray.800', borderRadius: 'lg', p: 4 })}> <h2 className={css({ fontSize: 'lg', fontWeight: 'bold', mb: 3 })}> Static Image (One-shot Detection) </h2> <div className={css({ mb: 3 })}> <label className={css({ display: 'inline-block', px: 4, py: 2, bg: isReady ? 'purple.600' : 'gray.600', color: 'white', borderRadius: 'md', cursor: isReady ? 'pointer' : 'not-allowed', opacity: isReady ? 1 : 0.5, _hover: isReady ? { bg: 'purple.500' } : {}, })} > {isReady ? 'Upload Image' : 'Loading...'} <input type="file" accept="image/*" onChange={handleFileUpload} disabled={!isReady} className={css({ display: 'none' })} /> </label> </div> <div id="static-image-container" className={css({ bg: 'black', borderRadius: 'md', overflow: 'hidden', minHeight: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center', })} > {!staticImageCanvas && ( <span className={css({ color: 'gray.500' })}>No image loaded</span> )} </div> {staticDetectionResult && ( <div className={css({ mt: 3, p: 2, bg: 'gray.700', borderRadius: 'md', fontSize: 'sm', })} > <div> Detection:{' '} <span className={css({ color: staticDetectionResult.detected ? 'green.400' : 'yellow.400', })} > {staticDetectionResult.detected ? `${staticDetectionResult.quads.length} quad${staticDetectionResult.quads.length !== 1 ? 's' : ''} found` : 'No quads found'} </span> </div> <div className={css({ fontFamily: 'mono', fontSize: 'xs', mt: 1 })}> Corners:{' '} {JSON.stringify( staticDetectionResult.corners.map((c) => [Math.round(c.x), Math.round(c.y)]) )} </div> </div> )} </div> </div> {/* Info section */} <div className={css({ mt: 4, p: 4, bg: 'gray.800', borderRadius: 'lg', fontSize: 'sm', color: 'gray.400', })} > <h3 className={css({ fontWeight: 'medium', color: 'gray.200', mb: 2 })}> Current Architecture (Step 5: useQuadDetection Hook) </h3> <ul className={css({ listStyleType: 'disc', pl: 4, lineHeight: 1.6 })}> <li> <strong>OpenCvProvider</strong> wraps the page and loads OpenCV via opencv-react </li> <li> <strong>useQuadDetection()</strong> combines OpenCV loading, detection, and tracking </li> <li> Hook provides: <code>isReady</code>, <code>detectInImage</code>,{' '} <code>processFrame</code>, <code>resetTracking</code> </li> <li> <code>detectInImage(canvas)</code> for static images (no tracking) </li> <li> <code>processFrame(canvas)</code> for camera feeds (with tracking) </li> <li> Status: orange=tracking, yellow=stable (3+ frames), green=locked (5+ frames, high stability) </li> <li>Next step: Update useDocumentDetection to use new modules</li> </ul> </div> </div> ) } // ============================================================================ // Helpers // ============================================================================ function getFallbackCorners(width: number, height: number): Point[] { return [ { x: 0, y: 0 }, { x: width, y: 0 }, { x: width, y: height }, { x: 0, y: height }, ] } function drawQuadOverlay( canvas: HTMLCanvasElement, frameWidth: number, frameHeight: number, quads: DetectedQuad[] ): void { canvas.width = frameWidth canvas.height = frameHeight const ctx = canvas.getContext('2d') if (!ctx) return ctx.clearRect(0, 0, frameWidth, frameHeight) // Draw all quads for (let i = 0; i < quads.length; i++) { const quad = quads[i] const isFirst = i === 0 // Color: green for best quad, yellow for others ctx.strokeStyle = isFirst ? 'rgba(0, 255, 100, 0.9)' : 'rgba(255, 200, 0, 0.6)' ctx.lineWidth = isFirst ? 4 : 2 ctx.lineCap = 'round' ctx.lineJoin = 'round' // Draw quad outline ctx.beginPath() ctx.moveTo(quad.corners[0].x, quad.corners[0].y) for (let j = 1; j < 4; j++) { ctx.lineTo(quad.corners[j].x, quad.corners[j].y) } ctx.closePath() ctx.stroke() // Draw corner circles for best quad if (isFirst) { ctx.fillStyle = 'rgba(0, 255, 100, 0.9)' for (const corner of quad.corners) { ctx.beginPath() ctx.arc(corner.x, corner.y, 8, 0, Math.PI * 2) ctx.fill() } } } } /** * Draw quad overlay with tracking status indicators */ function drawTrackedQuadOverlay( canvas: HTMLCanvasElement, frameWidth: number, frameHeight: number, detectedQuads: DetectedQuad[], trackedQuad: TrackedQuad | null ): void { canvas.width = frameWidth canvas.height = frameHeight const ctx = canvas.getContext('2d') if (!ctx) return ctx.clearRect(0, 0, frameWidth, frameHeight) // Draw all detected quads in faint color for (const quad of detectedQuads) { ctx.strokeStyle = 'rgba(100, 100, 100, 0.3)' ctx.lineWidth = 1 ctx.beginPath() ctx.moveTo(quad.corners[0].x, quad.corners[0].y) for (let j = 1; j < 4; j++) { ctx.lineTo(quad.corners[j].x, quad.corners[j].y) } ctx.closePath() ctx.stroke() } // Draw tracked quad with status-based color if (trackedQuad) { // Color based on status: locked=green, stable=yellow, tracking=orange const color = trackedQuad.isLocked ? 'rgba(0, 255, 100, 0.95)' : trackedQuad.isStable ? 'rgba(255, 220, 0, 0.9)' : 'rgba(255, 140, 0, 0.8)' ctx.strokeStyle = color ctx.lineWidth = trackedQuad.isLocked ? 5 : trackedQuad.isStable ? 4 : 3 ctx.lineCap = 'round' ctx.lineJoin = 'round' // Draw quad outline ctx.beginPath() ctx.moveTo(trackedQuad.corners[0].x, trackedQuad.corners[0].y) for (let j = 1; j < 4; j++) { ctx.lineTo(trackedQuad.corners[j].x, trackedQuad.corners[j].y) } ctx.closePath() ctx.stroke() // Draw corner circles - size based on stability const cornerRadius = 6 + trackedQuad.stabilityScore * 8 ctx.fillStyle = color for (const corner of trackedQuad.corners) { ctx.beginPath() ctx.arc(corner.x, corner.y, cornerRadius, 0, Math.PI * 2) ctx.fill() } // Draw stability bar at top const barWidth = 200 const barHeight = 8 const barX = (frameWidth - barWidth) / 2 const barY = 20 // Background ctx.fillStyle = 'rgba(0, 0, 0, 0.5)' ctx.fillRect(barX, barY, barWidth, barHeight) // Fill based on stability const fillWidth = barWidth * trackedQuad.stabilityScore ctx.fillStyle = color ctx.fillRect(barX, barY, fillWidth, barHeight) // Border ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)' ctx.lineWidth = 1 ctx.strokeRect(barX, barY, barWidth, barHeight) // Status text ctx.fillStyle = 'white' ctx.font = 'bold 14px sans-serif' ctx.textAlign = 'center' const statusText = trackedQuad.isLocked ? `LOCKED (${(trackedQuad.stabilityScore * 100).toFixed(0)}%)` : trackedQuad.isStable ? `STABLE (${(trackedQuad.stabilityScore * 100).toFixed(0)}%)` : `Tracking... (${trackedQuad.frameCount} frames)` ctx.fillText(statusText, frameWidth / 2, barY + barHeight + 18) } } /** * Draw debug overlay showing all candidate polygons with status-based colors */ function drawDebugOverlay( canvas: HTMLCanvasElement, frameWidth: number, frameHeight: number, quads: DetectedQuad[], debugPolygons: DebugPolygon[] ): void { canvas.width = frameWidth canvas.height = frameHeight const ctx = canvas.getContext('2d') if (!ctx) return ctx.clearRect(0, 0, frameWidth, frameHeight) // Color map for each status const statusColors: Record<DebugPolygon['status'], { stroke: string; fill: string }> = { accepted: { stroke: 'rgba(0, 255, 100, 0.9)', fill: 'rgba(0, 255, 100, 0.2)', }, too_small: { stroke: 'rgba(100, 100, 100, 0.5)', fill: 'rgba(100, 100, 100, 0.1)', }, too_large: { stroke: 'rgba(255, 50, 50, 0.7)', fill: 'rgba(255, 50, 50, 0.1)', }, too_few_vertices: { stroke: 'rgba(150, 150, 150, 0.5)', fill: 'rgba(150, 150, 150, 0.1)', }, too_many_vertices: { stroke: 'rgba(255, 150, 0, 0.7)', fill: 'rgba(255, 150, 0, 0.1)', }, bad_aspect_ratio: { stroke: 'rgba(255, 220, 0, 0.8)', fill: 'rgba(255, 220, 0, 0.1)', }, corner_extraction_failed: { stroke: 'rgba(255, 100, 200, 0.7)', fill: 'rgba(255, 100, 200, 0.1)', }, } // Draw all debug polygons (except too_small which clutters the view) for (const poly of debugPolygons) { if (poly.status === 'too_small') continue // Skip tiny polygons const colors = statusColors[poly.status] ctx.strokeStyle = colors.stroke ctx.fillStyle = colors.fill ctx.lineWidth = poly.status === 'accepted' ? 3 : 2 ctx.lineCap = 'round' ctx.lineJoin = 'round' // Draw polygon outline if (poly.vertices.length > 0) { ctx.beginPath() ctx.moveTo(poly.vertices[0].x, poly.vertices[0].y) for (let j = 1; j < poly.vertices.length; j++) { ctx.lineTo(poly.vertices[j].x, poly.vertices[j].y) } ctx.closePath() ctx.fill() ctx.stroke() // Draw vertex count at centroid const cx = poly.vertices.reduce((s, v) => s + v.x, 0) / poly.vertices.length const cy = poly.vertices.reduce((s, v) => s + v.y, 0) / poly.vertices.length ctx.fillStyle = 'white' ctx.font = 'bold 12px sans-serif' ctx.textAlign = 'center' ctx.textBaseline = 'middle' ctx.fillText(`${poly.vertexCount}v`, cx, cy) } // Draw convex hull if available (dashed line) if (poly.hullVertices && poly.hullVertices.length > 0) { ctx.strokeStyle = 'rgba(0, 200, 255, 0.6)' ctx.lineWidth = 1 ctx.setLineDash([5, 5]) ctx.beginPath() ctx.moveTo(poly.hullVertices[0].x, poly.hullVertices[0].y) for (let j = 1; j < poly.hullVertices.length; j++) { ctx.lineTo(poly.hullVertices[j].x, poly.hullVertices[j].y) } ctx.closePath() ctx.stroke() ctx.setLineDash([]) } } // Draw accepted quads with corner markers on top for (const quad of quads) { ctx.strokeStyle = 'rgba(0, 255, 100, 1)' ctx.lineWidth = 4 ctx.beginPath() ctx.moveTo(quad.corners[0].x, quad.corners[0].y) for (let j = 1; j < 4; j++) { ctx.lineTo(quad.corners[j].x, quad.corners[j].y) } ctx.closePath() ctx.stroke() // Corner circles ctx.fillStyle = 'rgba(0, 255, 100, 1)' for (const corner of quad.corners) { ctx.beginPath() ctx.arc(corner.x, corner.y, 8, 0, Math.PI * 2) ctx.fill() } } // Draw legend ctx.fillStyle = 'rgba(0, 0, 0, 0.7)' ctx.fillRect(10, 10, 180, 130) ctx.font = '11px sans-serif' ctx.textAlign = 'left' ctx.textBaseline = 'top' const legendItems: Array<{ color: string; label: string }> = [ { color: statusColors['accepted'].stroke, label: 'Accepted (quad found)' }, { color: statusColors['bad_aspect_ratio'].stroke, label: 'Bad aspect ratio', }, { color: statusColors['too_many_vertices'].stroke, label: 'Too many vertices (>8)', }, { color: statusColors['too_large'].stroke, label: 'Too large (>95%)' }, { color: 'rgba(0, 200, 255, 0.8)', label: 'Convex hull (dashed)' }, ] legendItems.forEach((item, i) => { ctx.fillStyle = item.color ctx.fillRect(15, 15 + i * 22, 12, 12) ctx.fillStyle = 'white' ctx.fillText(item.label, 32, 15 + i * 22) }) } function StatusBadge({ label, status, }: { label: string status: 'idle' | 'loading' | 'ready' | 'error' }) { const colors = { idle: { bg: 'gray.600', color: 'gray.300' }, loading: { bg: 'yellow.600', color: 'yellow.100' }, ready: { bg: 'green.600', color: 'green.100' }, error: { bg: 'red.600', color: 'red.100' }, } return ( <span className={css({ px: 2, py: 1, borderRadius: 'md', fontSize: 'sm', fontWeight: 'medium', ...colors[status], })} > {label}: {status} </span> ) } function ToggleSwitch({ label, checked, onChange, }: { label: string checked: boolean onChange: (checked: boolean) => void }) { return ( <label className={css({ display: 'flex', alignItems: 'center', gap: 2, cursor: 'pointer', fontSize: 'xs', })} > <div className={css({ position: 'relative', width: '36px', height: '20px', bg: checked ? 'green.600' : 'gray.600', borderRadius: 'full', transition: 'background-color 0.2s', })} onClick={() => onChange(!checked)} > <div className={css({ position: 'absolute', top: '2px', left: checked ? '18px' : '2px', width: '16px', height: '16px', bg: 'white', borderRadius: 'full', transition: 'left 0.2s', })} /> </div> <span className={css({ color: checked ? 'gray.200' : 'gray.400' })}>{label}</span> </label> ) } function SliderControl({ label, value, onChange, min, max, step, }: { label: string value: number onChange: (value: number) => void min: number max: number step: number }) { return ( <div className={css({ fontSize: 'xs' })}> <div className={css({ display: 'flex', justifyContent: 'space-between', mb: 1, })} > <span className={css({ color: 'gray.400' })}>{label}</span> <span className={css({ color: 'gray.200', fontFamily: 'mono' })}>{value}</span> </div> <input type="range" value={value} onChange={(e) => onChange(Number(e.target.value))} min={min} max={max} step={step} className={css({ width: '100%', height: '4px', bg: 'gray.600', borderRadius: 'full', appearance: 'none', cursor: 'pointer', _focusVisible: { outline: 'none', }, })} /> </div> ) } |