File size: 51,733 Bytes
12eb9ba |
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 |
(function () {
'use strict';
/**
* Camera management module for video stream handling
*/
class CameraManager {
constructor() {
this.currentStream = null;
this.availableCameras = [];
this.selectedCameraId = null;
this.videoElement = null;
this.preferredConstraints = {
width: {
ideal: 480,
min: 240
},
height: {
ideal: 640,
min: 320
}
};
this.fallbackConstraints = {
width: {
ideal: 640,
min: 320
},
height: {
ideal: 480,
min: 240
}
};
}
/**
* Initialize camera manager and enumerate devices
* @returns {Promise<void>}
*/
async initialize() {
try {
// Request permission first
await this.requestCameraPermission();
// Enumerate cameras
await this.enumerateCameras();
console.log(`Found ${this.availableCameras.length} camera(s)`);
} catch (error) {
console.error('Failed to initialize camera manager:', error);
throw new Error(`Camera initialization failed: ${error.message}`);
}
}
/**
* Request camera permission
* @returns {Promise<void>}
*/
async requestCameraPermission() {
try {
// Request basic camera access to get permissions
const tempStream = await navigator.mediaDevices.getUserMedia({
video: true
});
// Stop the temporary stream
tempStream.getTracks().forEach(track => track.stop());
console.log('Camera permission granted');
} catch (error) {
throw new Error('Camera permission denied or not available');
}
}
/**
* Enumerate available cameras
* @returns {Promise<void>}
*/
async enumerateCameras() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
this.availableCameras = devices.filter(device => device.kind === 'videoinput').map((device, index) => ({
id: device.deviceId,
label: device.label || `Camera ${index + 1}`,
groupId: device.groupId
}));
if (this.availableCameras.length === 0) {
throw new Error('No cameras found');
}
// Select first camera by default
this.selectedCameraId = this.availableCameras[0].id;
} catch (error) {
throw new Error(`Failed to enumerate cameras: ${error.message}`);
}
}
/**
* Get list of available cameras
* @returns {Array}
*/
getAvailableCameras() {
return [...this.availableCameras];
}
/**
* Start video stream with selected camera
* @param {HTMLVideoElement} videoElement
* @param {string} cameraId
* @returns {Promise<Object>} - Stream info
*/
async startCamera(videoElement) {
let cameraId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
try {
// Stop current stream if exists
if (this.currentStream) {
this.stopCamera();
}
// Use provided camera or current selection
const targetCameraId = cameraId || this.selectedCameraId;
this.selectedCameraId = targetCameraId;
// Store video element reference
this.videoElement = videoElement;
// Try preferred resolution first (480x640)
let stream = null;
let usedConstraints = null;
try {
const constraints = {
video: {
deviceId: {
exact: targetCameraId
},
...this.preferredConstraints
}
};
console.log('Trying preferred resolution (480x640)...');
stream = await navigator.mediaDevices.getUserMedia(constraints);
usedConstraints = this.preferredConstraints;
} catch (error) {
console.log('Preferred resolution failed, trying fallback (640x480)...');
const constraints = {
video: {
deviceId: {
exact: targetCameraId
},
...this.fallbackConstraints
}
};
stream = await navigator.mediaDevices.getUserMedia(constraints);
usedConstraints = this.fallbackConstraints;
}
// Set up video element
videoElement.srcObject = stream;
this.currentStream = stream;
// Wait for video metadata to load
await new Promise((resolve, reject) => {
videoElement.addEventListener('loadedmetadata', resolve, {
once: true
});
videoElement.addEventListener('error', reject, {
once: true
});
// Timeout after 10 seconds
setTimeout(() => reject(new Error('Video load timeout')), 10000);
});
// Get actual video dimensions
const videoWidth = videoElement.videoWidth;
const videoHeight = videoElement.videoHeight;
console.log(`Video stream started: ${videoWidth}x${videoHeight}`);
// Determine if camera should be rotated for display
//const shouldRotateDisplay = ImageUtils.shouldRotateCamera(videoWidth, videoHeight);
const shouldRotateDisplay = false;
const isPortrait = videoHeight > videoWidth;
// Get video wrapper for aspect ratio handling
const videoWrapper = videoElement.closest('.video-wrapper');
// Apply rotation CSS if needed
if (shouldRotateDisplay) ; else {
videoElement.classList.remove('rotate-90ccw');
}
// Apply portrait aspect ratio if video is vertical
if (videoWrapper) {
if (isPortrait) {
videoWrapper.classList.add('portrait');
console.log('Applied portrait aspect ratio (3:4)');
} else {
videoWrapper.classList.remove('portrait');
}
}
return {
width: videoWidth,
height: videoHeight,
rotated: shouldRotateDisplay,
constraints: usedConstraints,
cameraId: targetCameraId,
cameraLabel: this.getCameraLabel(targetCameraId)
};
} catch (error) {
console.error('Failed to start camera:', error);
throw new Error(`Camera start failed: ${error.message}`);
}
}
/**
* Stop current video stream
*/
stopCamera() {
if (this.currentStream) {
this.currentStream.getTracks().forEach(track => {
track.stop();
console.log(`Stopped ${track.kind} track`);
});
this.currentStream = null;
}
if (this.videoElement) {
this.videoElement.srcObject = null;
this.videoElement.classList.remove('rotate-90ccw');
// Remove portrait class from wrapper
const videoWrapper = this.videoElement.closest('.video-wrapper');
if (videoWrapper) {
videoWrapper.classList.remove('portrait');
}
}
console.log('Camera stopped');
}
/**
* Switch to a different camera
* @param {string} cameraId
* @returns {Promise<Object>}
*/
async switchCamera(cameraId) {
if (!this.videoElement) {
throw new Error('No video element available');
}
return await this.startCamera(this.videoElement, cameraId);
}
/**
* Get label for camera ID
* @param {string} cameraId
* @returns {string}
*/
getCameraLabel(cameraId) {
const camera = this.availableCameras.find(cam => cam.id === cameraId);
return camera ? camera.label : 'Unknown Camera';
}
/**
* Get current camera information
* @returns {Object|null}
*/
getCurrentCameraInfo() {
if (!this.selectedCameraId || !this.videoElement) {
return null;
}
return {
id: this.selectedCameraId,
label: this.getCameraLabel(this.selectedCameraId),
width: this.videoElement.videoWidth,
height: this.videoElement.videoHeight,
isRotated: this.videoElement.classList.contains('rotate-90ccw')
};
}
/**
* Check if camera is currently active
* @returns {boolean}
*/
isActive() {
return this.currentStream !== null && this.currentStream.getTracks().some(track => track.readyState === 'live');
}
/**
* Get video element reference
* @returns {HTMLVideoElement|null}
*/
getVideoElement() {
return this.videoElement;
}
/**
* Set up camera selection dropdown
* @param {HTMLSelectElement} selectElement
*/
populateCameraSelect(selectElement) {
// Clear existing options
selectElement.innerHTML = '';
if (this.availableCameras.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = 'No cameras available';
option.disabled = true;
selectElement.appendChild(option);
return;
}
// Add camera options
this.availableCameras.forEach(camera => {
const option = document.createElement('option');
option.value = camera.id;
option.textContent = camera.label;
selectElement.appendChild(option);
});
// Select current camera
if (this.selectedCameraId) {
selectElement.value = this.selectedCameraId;
}
}
/**
* Handle device change events (camera plugged/unplugged)
* @param {Function} callback
*/
onDeviceChange(callback) {
navigator.mediaDevices.addEventListener('devicechange', async () => {
console.log('Camera devices changed');
try {
await this.enumerateCameras();
callback(this.availableCameras);
} catch (error) {
console.error('Error handling device change:', error);
callback([]);
}
});
}
/**
* Dispose of resources
*/
dispose() {
this.stopCamera();
this.availableCameras = [];
this.selectedCameraId = null;
this.videoElement = null;
console.log('Camera manager disposed');
}
}
/**
* Image utilities for preprocessing and transformations
*/
class ImageUtils {
/**
* Create a canvas element for image processing
* @param {number} width
* @param {number} height
* @returns {HTMLCanvasElement}
*/
static createCanvas(width, height) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
/**
* Rotate image 90 degrees counterclockwise
* @param {ImageData} imageData
* @returns {ImageData}
*/
static rotateImage90CCW(imageData) {
const {
width,
height,
data
} = imageData;
const rotatedCanvas = this.createCanvas(height, width);
const ctx = rotatedCanvas.getContext('2d');
// Create temporary canvas with original image
const tempCanvas = this.createCanvas(width, height);
const tempCtx = tempCanvas.getContext('2d');
tempCtx.putImageData(imageData, 0, 0);
// Apply rotation transformation
ctx.translate(height, 0);
ctx.rotate(Math.PI / 2);
ctx.drawImage(tempCanvas, 0, 0);
return ctx.getImageData(0, 0, height, width);
}
/**
* Resize image to target dimensions
* @param {ImageData} imageData
* @param {number} targetWidth
* @param {number} targetHeight
* @returns {ImageData}
*/
static resizeImage(imageData, targetWidth, targetHeight) {
const {
width,
height
} = imageData;
// Create canvas with original image
const sourceCanvas = this.createCanvas(width, height);
const sourceCtx = sourceCanvas.getContext('2d');
sourceCtx.putImageData(imageData, 0, 0);
// Create target canvas
const targetCanvas = this.createCanvas(targetWidth, targetHeight);
const targetCtx = targetCanvas.getContext('2d');
// Resize using canvas scaling
targetCtx.drawImage(sourceCanvas, 0, 0, width, height, 0, 0, targetWidth, targetHeight);
return targetCtx.getImageData(0, 0, targetWidth, targetHeight);
}
/**
* Extract image data from video element
* @param {HTMLVideoElement} video
* @returns {ImageData}
*/
static getVideoFrame(video) {
const canvas = this.createCanvas(video.videoWidth, video.videoHeight);
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0);
return ctx.getImageData(0, 0, video.videoWidth, video.videoHeight);
}
/**
* Normalize image data for model inference
* Uses ImageNet normalization values
* @param {ImageData} imageData
* @returns {Float32Array}
*/
static normalizeImageData(imageData) {
const {
width,
height,
data
} = imageData;
const normalizedData = new Float32Array(3 * width * height);
// ImageNet normalization constants
const mean = [0.485, 0.456, 0.406];
const std = [0.229, 0.224, 0.225];
let pixelIndex = 0;
for (let i = 0; i < data.length; i += 4) {
// Extract RGB values (skip alpha channel)
const r = data[i] / 255.0;
const g = data[i + 1] / 255.0;
const b = data[i + 2] / 255.0;
// Apply normalization: (pixel - mean) / std
normalizedData[pixelIndex] = (r - mean[0]) / std[0]; // R channel
normalizedData[pixelIndex + width * height] = (g - mean[1]) / std[1]; // G channel
normalizedData[pixelIndex + 2 * width * height] = (b - mean[2]) / std[2]; // B channel
pixelIndex++;
}
return normalizedData;
}
/**
* Preprocess image for model inference
* @param {HTMLVideoElement} video
* @param {number} targetWidth
* @param {number} targetHeight
* @param {boolean} shouldRotate - Whether to rotate 90 degrees CCW
* @returns {Float32Array}
*/
static preprocessVideoFrame(video, targetWidth, targetHeight) {
try {
// Extract frame from video
let imageData = this.getVideoFrame(video);
//console.log("In", imageData.width, imageData.height);
imageData = this.cropCenter3to4(imageData);
// Rotate if needed (for 640x480 -> 480x640)
//if (shouldRotate) {
// imageData = this.rotateImage90CCW(imageData);
//}
// Resize to target dimensions
if (imageData.width !== targetWidth || imageData.height !== targetHeight) {
imageData = this.resizeImage(imageData, targetWidth, targetHeight);
}
// Normalize for model input
return this.normalizeImageData(imageData);
} catch (error) {
console.error('Error preprocessing video frame:', error);
throw error;
}
}
/**
* Create tensor from preprocessed data
* @param {Float32Array} normalizedData
* @param {number} height
* @param {number} width
* @returns {Object} - Tensor-like object for ONNX
*/
static createInputTensor(normalizedData, height, width) {
return {
data: normalizedData,
dims: [1, 3, height, width],
type: 'float32'
};
}
/**
* Process model output to create segmentation mask
* @param {Float32Array} modelOutput
* @param {number} height
* @param {number} width
* @returns {Uint8Array} - Binary mask
*/
static processModelOutput(modelOutput, height, width) {
const mask = new Uint8Array(height * width);
// Apply softmax and get argmax for each pixel
for (let i = 0; i < height * width; i++) {
const backgroundLogit = modelOutput[i];
const cardLogit = modelOutput[i + height * width];
// Simple argmax (card class = 1, background = 0)
mask[i] = cardLogit > backgroundLogit ? 255 : 0;
}
return mask;
}
/**
* Create overlay canvas with segmentation mask
* @param {Uint8Array} mask
* @param {number} width
* @param {number} height
* @param {HTMLCanvasElement} targetCanvas
* @param {boolean} shouldRotate - Whether to rotate mask back
*/
static drawSegmentationOverlay(mask, width, height, targetCanvas) {
let shouldRotate = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
const ctx = targetCanvas.getContext('2d');
// Create mask canvas
const maskCanvas = this.createCanvas(width, height);
const maskCtx = maskCanvas.getContext('2d');
const maskImageData = maskCtx.createImageData(width, height);
// Fill mask with cyan color where mask is active
for (let i = 0; i < mask.length; i++) {
const pixelIndex = i * 4;
if (mask[i] > 0) {
maskImageData.data[pixelIndex] = 0; // R
maskImageData.data[pixelIndex + 1] = 255; // G (cyan)
maskImageData.data[pixelIndex + 2] = 255; // B (cyan)
maskImageData.data[pixelIndex + 3] = 128; // A (50% transparent)
} else {
maskImageData.data[pixelIndex + 3] = 0; // Fully transparent
}
}
maskCtx.putImageData(maskImageData, 0, 0);
// Clear target canvas
ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
shouldRotate = false;
// Draw mask with rotation if needed
if (shouldRotate) {
ctx.save();
ctx.translate(targetCanvas.width, 0);
ctx.rotate(Math.PI / 2);
ctx.drawImage(maskCanvas, 0, 0, height, width, 0, 0, targetCanvas.height, targetCanvas.width);
ctx.restore();
} else {
ctx.drawImage(maskCanvas, 0, 0, width, height, 0, 0, targetCanvas.width, targetCanvas.height);
}
}
/**
* Check if camera orientation suggests it should be rotated
* @param {number} width
* @param {number} height
* @returns {boolean}
*/
static shouldRotateCamera(width, height) {
return width > height; // Horizontal camera should be rotated to vertical
}
/**
* Check if input image needs rotation for model (640x480 -> 480x640)
* @param {number} width
* @param {number} height
* @returns {boolean}
*/
static shouldRotateForModel(width, height) {
return width === 640 && height === 480;
}
/**
* Crop the center of an image to 3:4 aspect ratio (width:height)
* Returns the largest possible crop that maintains the 3:4 proportion
* @param {ImageData} imageData
* @returns {ImageData}
*/
static cropCenter3to4(imageData) {
const {
width,
height
} = imageData;
// Calculate the largest possible 3:4 crop
let cropWidth, cropHeight;
// Determine crop dimensions based on original aspect ratio
if (width / height > 3 / 4) {
// Image is wider than 3:4, crop width
cropHeight = height;
cropWidth = Math.floor(height * 3 / 4);
} else {
// Image is taller than 3:4, crop height
cropWidth = width;
cropHeight = Math.floor(width * 4 / 3);
}
// Calculate crop position (center the crop)
const startX = Math.floor((width - cropWidth) / 2);
const startY = Math.floor((height - cropHeight) / 2);
// Create source canvas
const sourceCanvas = this.createCanvas(width, height);
const sourceCtx = sourceCanvas.getContext('2d');
sourceCtx.putImageData(imageData, 0, 0);
// Create target canvas for cropped image
const targetCanvas = this.createCanvas(cropWidth, cropHeight);
const targetCtx = targetCanvas.getContext('2d');
// Draw the cropped portion
targetCtx.drawImage(sourceCanvas, startX, startY, cropWidth, cropHeight,
// Source rectangle
0, 0, cropWidth, cropHeight // Destination rectangle
);
return targetCtx.getImageData(0, 0, cropWidth, cropHeight);
}
}
/**
* Model inference module using ONNX Runtime Web
*/
class ModelInference {
constructor() {
this.session = null;
this.isModelLoaded = false;
this.isInferring = false;
this.modelPath = 'models/card_segmentation_fp16.onnx';
// Model specifications
this.inputHeight = 320;
this.inputWidth = 240;
this.numClasses = 2;
// GPU acceleration info
this.accelerationInfo = {
activeProvider: 'unknown',
availableProviders: [],
gpuInfo: null,
supportsWebGL: false,
supportsWebGPU: false
};
// Performance tracking
this.inferenceStats = {
totalInferences: 0,
totalTime: 0,
averageTime: 0,
lastInferenceTime: 0
};
}
/**
* Initialize ONNX Runtime and load the model with GPU acceleration
* @returns {Promise<boolean>}
*/
async initialize() {
try {
console.log('Initializing ONNX Runtime with GPU acceleration...');
// Configure ONNX Runtime
ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/';
ort.env.wasm.numThreads = 1; // Single thread for stability
// Detect GPU capabilities
await this.detectGPUCapabilities();
// Determine optimal execution providers
const executionProviders = this.getOptimalExecutionProviders();
console.log('Attempting to load model with providers:', executionProviders);
console.log(`Loading model from: ${this.modelPath}`);
// Try to load model with optimal providers
this.session = await this.loadModelWithFallback(executionProviders);
console.log(`Model loaded successfully with provider: ${this.accelerationInfo.activeProvider}`);
this.isModelLoaded = true;
// Log model and acceleration information
this.logModelInfo();
this.logAccelerationInfo();
return true;
} catch (error) {
console.error('Failed to initialize model:', error);
this.isModelLoaded = false;
throw new Error(`Model initialization failed: ${error.message}`);
}
}
/**
* Detect GPU capabilities and available acceleration
*/
async detectGPUCapabilities() {
console.log('Detecting GPU capabilities...');
// Check WebGL support
this.accelerationInfo.supportsWebGL = this.checkWebGLSupport();
// Check WebGPU support
this.accelerationInfo.supportsWebGPU = await this.checkWebGPUSupport();
// Get GPU info if available
if (this.accelerationInfo.supportsWebGL) {
this.accelerationInfo.gpuInfo = this.getWebGLInfo();
}
console.log('GPU Capabilities:', {
WebGL: this.accelerationInfo.supportsWebGL,
WebGPU: this.accelerationInfo.supportsWebGPU,
GPU: this.accelerationInfo.gpuInfo
});
}
/**
* Check WebGL support
* @returns {boolean}
*/
checkWebGLSupport() {
try {
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
return !!gl;
} catch (error) {
console.warn('WebGL check failed:', error);
return false;
}
}
/**
* Check WebGPU support
* @returns {Promise<boolean>}
*/
async checkWebGPUSupport() {
try {
if (!navigator.gpu) {
return false;
}
const adapter = await navigator.gpu.requestAdapter();
return !!adapter;
} catch (error) {
console.warn('WebGPU check failed:', error);
return false;
}
}
/**
* Get WebGL renderer information
* @returns {Object|null}
*/
getWebGLInfo() {
try {
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (!gl) return null;
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
return {
vendor: debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : gl.getParameter(gl.VENDOR),
renderer: debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER),
version: gl.getParameter(gl.VERSION),
shadingLanguageVersion: gl.getParameter(gl.SHADING_LANGUAGE_VERSION)
};
} catch (error) {
console.warn('Failed to get WebGL info:', error);
return null;
}
}
/**
* Determine optimal execution providers based on capabilities
* @returns {Array<string>}
*/
getOptimalExecutionProviders() {
const providers = [];
// Prioritize WebGPU first for best performance
if (this.accelerationInfo.supportsWebGPU) {
providers.push('webgpu');
this.accelerationInfo.availableProviders.push('webgpu');
}
// Fall back to WebGL if WebGPU is not available or fails
if (this.accelerationInfo.supportsWebGL) {
providers.push('webgl');
this.accelerationInfo.availableProviders.push('webgl');
}
// Always add WASM as final fallback
providers.push('wasm');
this.accelerationInfo.availableProviders.push('wasm');
return providers;
}
/**
* Load model with fallback mechanism
* @param {Array<string>} executionProviders
* @returns {Promise<InferenceSession>}
*/
async loadModelWithFallback(executionProviders) {
const baseOptions = {
enableMemPattern: false,
enableCpuMemArena: false,
graphOptimizationLevel: 'all'
};
// Try each provider in order
for (const provider of executionProviders) {
try {
console.log(`Attempting to load model with ${provider} provider...`);
const options = {
...baseOptions,
executionProviders: [provider]
};
const session = await ort.InferenceSession.create(this.modelPath, options);
this.accelerationInfo.activeProvider = provider;
console.log(`✓ Successfully loaded with ${provider} provider`);
return session;
} catch (error) {
const errorMsg = error.message;
// Log specific information for operator compatibility issues
if (errorMsg.includes('cannot resolve operator')) {
var _errorMsg$match;
const operatorName = ((_errorMsg$match = errorMsg.match(/operator '(\w+)'/)) === null || _errorMsg$match === void 0 ? void 0 : _errorMsg$match[1]) || 'unknown';
console.warn(`✗ ${provider.toUpperCase()} provider doesn't support operator '${operatorName}' - falling back to next provider`);
} else {
console.warn(`✗ Failed to load with ${provider} provider:`, errorMsg);
}
// Store failed provider info for reporting
this.accelerationInfo[`${provider}Error`] = errorMsg;
continue;
}
}
throw new Error('Failed to load model with any execution provider');
}
/**
* Log acceleration information
*/
logAccelerationInfo() {
console.log('=== Acceleration Information ===');
console.log(`Active Provider: ${this.accelerationInfo.activeProvider}`);
console.log(`Available Providers: ${this.accelerationInfo.availableProviders.join(', ')}`);
console.log(`WebGL Support: ${this.accelerationInfo.supportsWebGL}`);
console.log(`WebGPU Support: ${this.accelerationInfo.supportsWebGPU}`);
if (this.accelerationInfo.gpuInfo) {
console.log('GPU Information:');
console.log(` Vendor: ${this.accelerationInfo.gpuInfo.vendor}`);
console.log(` Renderer: ${this.accelerationInfo.gpuInfo.renderer}`);
console.log(` Version: ${this.accelerationInfo.gpuInfo.version}`);
}
console.log('===============================');
}
/**
* Get acceleration information
* @returns {Object}
*/
getAccelerationInfo() {
return {
...this.accelerationInfo
};
}
/**
* Log model information for debugging
*/
logModelInfo() {
if (!this.session) return;
console.log('=== Model Information ===');
console.log('Input tensors:');
this.session.inputNames.forEach((name, index) => {
// Try to access input metadata safely
try {
if (this.session.inputs && this.session.inputs[index]) {
const input = this.session.inputs[index];
console.log(` ${name}: ${input.dims} (${input.type})`);
} else {
console.log(` ${name}: metadata not available`);
}
} catch (error) {
console.log(` ${name}: metadata not available`);
}
});
console.log('Output tensors:');
this.session.outputNames.forEach((name, index) => {
// Try to access output metadata safely
try {
if (this.session.outputs && this.session.outputs[index]) {
const output = this.session.outputs[index];
console.log(` ${name}: ${output.dims} (${output.type})`);
} else {
console.log(` ${name}: metadata not available`);
}
} catch (error) {
console.log(` ${name}: metadata not available`);
}
});
console.log('========================');
}
/**
* Run inference on preprocessed image data
* @param {Float32Array} inputData
* @returns {Promise<Float32Array>}
*/
async runInference(inputData) {
if (!this.isModelLoaded || !this.session) {
throw new Error('Model not loaded. Call initialize() first.');
}
if (this.isInferring) {
console.warn('Inference already in progress, skipping...');
return null;
}
try {
this.isInferring = true;
const startTime = performance.now();
// Create input tensor
const inputTensor = new ort.Tensor('float32', inputData, [1, 3, this.inputHeight, this.inputWidth]);
// Get input name from model
const inputName = this.session.inputNames[0];
// Run inference
const results = await this.session.run({
[inputName]: inputTensor
});
// Get output tensor
const outputName = this.session.outputNames[0];
const outputTensor = results[outputName];
// Calculate inference time
const endTime = performance.now();
const inferenceTime = endTime - startTime;
// Update statistics
this.updateInferenceStats(inferenceTime);
console.log(`Inference completed in ${inferenceTime.toFixed(2)}ms`);
return outputTensor.data;
} catch (error) {
console.error('Inference failed:', error);
throw new Error(`Inference failed: ${error.message}`);
} finally {
this.isInferring = false;
}
}
/**
* Process video frame and return segmentation mask
* @param {HTMLVideoElement} video
* @returns {Promise<Object>} - {mask: Uint8Array, stats: Object}
*/
async processVideoFrame(video) {
try {
// Check if model is ready
if (!this.isModelLoaded) {
throw new Error('Model not initialized');
}
// Get video dimensions
const videoWidth = video.videoWidth;
const videoHeight = video.videoHeight;
if (videoWidth === 0 || videoHeight === 0) {
throw new Error('Video not ready');
}
// Determine if rotation is needed for model input
const shouldRotateForModel = ImageUtils.shouldRotateForModel(videoWidth, videoHeight);
// Preprocess video frame
const preprocessedData = ImageUtils.preprocessVideoFrame(video, this.inputWidth, this.inputHeight, shouldRotateForModel);
// Run inference
const modelOutput = await this.runInference(preprocessedData);
if (!modelOutput) {
return null; // Inference skipped
}
// Process model output to create mask
const mask = ImageUtils.processModelOutput(modelOutput, this.inputHeight, this.inputWidth);
return {
mask: mask,
shouldRotateBack: shouldRotateForModel,
stats: this.getInferenceStats()
};
} catch (error) {
console.error('Error processing video frame:', error);
throw error;
}
}
/**
* Update inference performance statistics
* @param {number} inferenceTime
*/
updateInferenceStats(inferenceTime) {
this.inferenceStats.totalInferences++;
this.inferenceStats.totalTime += inferenceTime;
this.inferenceStats.averageTime = this.inferenceStats.totalTime / this.inferenceStats.totalInferences;
this.inferenceStats.lastInferenceTime = inferenceTime;
}
/**
* Get current inference statistics
* @returns {Object}
*/
getInferenceStats() {
return {
...this.inferenceStats,
fps: this.inferenceStats.lastInferenceTime > 0 ? 1000 / this.inferenceStats.lastInferenceTime : 0
};
}
/**
* Reset inference statistics
*/
resetStats() {
this.inferenceStats = {
totalInferences: 0,
totalTime: 0,
averageTime: 0,
lastInferenceTime: 0
};
}
/**
* Check if model is ready for inference
* @returns {boolean}
*/
isReady() {
return this.isModelLoaded && !this.isInferring;
}
/**
* Get model specifications
* @returns {Object}
*/
getModelSpecs() {
return {
inputHeight: this.inputHeight,
inputWidth: this.inputWidth,
numClasses: this.numClasses,
isLoaded: this.isModelLoaded
};
}
/**
* Dispose of the model and free resources
*/
dispose() {
if (this.session) {
this.session.release();
this.session = null;
}
this.isModelLoaded = false;
this.isInferring = false;
console.log('Model resources disposed');
}
}
/**
* Main application module
* Coordinates camera, model inference, and UI interactions
*/
class CardSegmentationApp {
constructor() {
// Core modules
this.cameraManager = new CameraManager();
this.modelInference = new ModelInference();
// DOM elements
this.elements = {};
// Application state
this.state = {
isInitialized: false,
isModelLoaded: false,
isCameraActive: false,
isInferenceRunning: false,
currentError: null
};
// Animation frame ID for inference loop
this.inferenceLoopId = null;
// Performance tracking
this.performanceStats = {
frameCount: 0,
lastFpsUpdate: 0,
fps: 0
};
}
/**
* Initialize the application
*/
async init() {
try {
console.log('Initializing Card Segmentation App...');
// Get DOM elements
this.setupDOMElements();
// Set up event listeners
this.setupEventListeners();
// Show loading indicator
this.showLoading('Initializing cameras...');
// Initialize camera manager
await this.cameraManager.initialize();
this.populateCameraDropdown();
// Initialize model
this.showLoading('Loading AI model...');
await this.modelInference.initialize();
// Update acceleration info display
this.updateAccelerationInfo();
// Hide loading, show camera selection
this.hideLoading();
this.showCameraSelection();
this.state.isInitialized = true;
this.state.isModelLoaded = true;
console.log('Application initialized successfully');
} catch (error) {
console.error('Application initialization failed:', error);
this.showError('Failed to initialize application', error.message);
}
}
/**
* Set up DOM element references
*/
setupDOMElements() {
this.elements = {
// Main containers
cameraSelection: document.getElementById('cameraSelection'),
videoContainer: document.getElementById('videoContainer'),
loadingIndicator: document.getElementById('loadingIndicator'),
errorDisplay: document.getElementById('errorDisplay'),
// Camera selection
cameraSelect: document.getElementById('cameraSelect'),
startCamera: document.getElementById('startCamera'),
// Video and controls
videoElement: document.getElementById('videoElement'),
overlayCanvas: document.getElementById('overlayCanvas'),
toggleInference: document.getElementById('toggleInference'),
switchCamera: document.getElementById('switchCamera'),
// Info displays
resolutionInfo: document.getElementById('resolutionInfo'),
fpsInfo: document.getElementById('fpsInfo'),
inferenceStatus: document.getElementById('inferenceStatus'),
accelerationInfo: document.getElementById('accelerationInfo'),
// Loading and error
loadingText: document.getElementById('loadingText'),
errorMessage: document.getElementById('errorMessage'),
retryButton: document.getElementById('retryButton')
};
}
/**
* Set up event listeners
*/
setupEventListeners() {
// Camera selection
this.elements.cameraSelect.addEventListener('change', e => {
this.elements.startCamera.disabled = !e.target.value;
});
this.elements.startCamera.addEventListener('click', () => {
this.startCamera();
});
// Video controls
this.elements.toggleInference.addEventListener('click', () => {
this.toggleInference();
});
this.elements.switchCamera.addEventListener('click', () => {
this.showCameraSelection();
});
// Error handling
this.elements.retryButton.addEventListener('click', () => {
this.hideError();
this.init();
});
// Handle video loaded
this.elements.videoElement.addEventListener('loadedmetadata', () => {
this.setupOverlayCanvas();
});
// Handle camera device changes
this.cameraManager.onDeviceChange(() => {
this.populateCameraDropdown();
});
// Handle page unload
window.addEventListener('beforeunload', () => {
this.cleanup();
});
}
/**
* Populate camera selection dropdown
*/
populateCameraDropdown() {
this.cameraManager.populateCameraSelect(this.elements.cameraSelect);
this.elements.startCamera.disabled = this.elements.cameraSelect.value === '';
}
/**
* Start camera with selected device
*/
async startCamera() {
try {
const selectedCameraId = this.elements.cameraSelect.value;
if (!selectedCameraId) {
throw new Error('No camera selected');
}
this.showLoading('Starting camera...');
// Start camera stream
const streamInfo = await this.cameraManager.startCamera(this.elements.videoElement, selectedCameraId);
// Update UI
this.updateResolutionInfo(streamInfo);
this.setupOverlayCanvas();
// Show video container
this.hideLoading();
this.hideCameraSelection();
this.showVideoContainer();
this.state.isCameraActive = true;
console.log('Camera started successfully:', streamInfo);
} catch (error) {
console.error('Failed to start camera:', error);
this.showError('Failed to start camera', error.message);
}
}
/**
* Set up overlay canvas to match video dimensions
*/
setupOverlayCanvas() {
const video = this.elements.videoElement;
const canvas = this.elements.overlayCanvas;
if (video.videoWidth && video.videoHeight) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// Apply same rotation class as video if needed
if (video.classList.contains('rotate-90ccw')) {
canvas.classList.add('rotate-90ccw');
} else {
canvas.classList.remove('rotate-90ccw');
}
}
}
/**
* Toggle inference on/off
*/
toggleInference() {
if (this.state.isInferenceRunning) {
this.stopInference();
} else {
this.startInference();
}
}
/**
* Start continuous inference
*/
startInference() {
if (!this.state.isModelLoaded || !this.state.isCameraActive) {
this.showError('Cannot start inference', 'Camera or model not ready');
return;
}
this.state.isInferenceRunning = true;
this.elements.toggleInference.textContent = 'Stop Detection';
this.elements.toggleInference.className = 'btn btn-danger';
this.updateInferenceStatus('Detection: Running');
// Reset performance stats
this.performanceStats.frameCount = 0;
this.performanceStats.lastFpsUpdate = performance.now();
// Start inference loop
this.runInferenceLoop();
console.log('Inference started');
}
/**
* Stop continuous inference
*/
stopInference() {
this.state.isInferenceRunning = false;
this.elements.toggleInference.textContent = 'Start Detection';
this.elements.toggleInference.className = 'btn btn-success';
this.updateInferenceStatus('Detection: Off');
// Cancel animation frame
if (this.inferenceLoopId) {
cancelAnimationFrame(this.inferenceLoopId);
this.inferenceLoopId = null;
}
// Clear overlay
const ctx = this.elements.overlayCanvas.getContext('2d');
ctx.clearRect(0, 0, this.elements.overlayCanvas.width, this.elements.overlayCanvas.height);
console.log('Inference stopped');
}
/**
* Main inference loop
*/
async runInferenceLoop() {
if (!this.state.isInferenceRunning) {
return;
}
try {
// Process video frame
const result = await this.modelInference.processVideoFrame(this.elements.videoElement);
if (result && result.mask) {
// Draw segmentation overlay
ImageUtils.drawSegmentationOverlay(result.mask, this.modelInference.inputWidth, this.modelInference.inputHeight, this.elements.overlayCanvas, result.shouldRotateBack);
// Update performance stats
this.updatePerformanceStats(result.stats);
}
} catch (error) {
console.error('Inference loop error:', error);
// Don't stop inference for individual frame errors
}
// Schedule next frame
if (this.state.isInferenceRunning) {
this.inferenceLoopId = requestAnimationFrame(() => this.runInferenceLoop());
}
}
/**
* Update performance statistics display
*/
updatePerformanceStats(inferenceStats) {
this.performanceStats.frameCount++;
const now = performance.now();
// Update FPS every second
if (now - this.performanceStats.lastFpsUpdate >= 1000) {
this.performanceStats.fps = this.performanceStats.frameCount;
this.performanceStats.frameCount = 0;
this.performanceStats.lastFpsUpdate = now;
// Update UI
this.elements.fpsInfo.textContent = `FPS: ${this.performanceStats.fps}`;
}
}
/**
* Update resolution information display
*/
updateResolutionInfo(streamInfo) {
const resText = `Resolution: ${streamInfo.width}x${streamInfo.height}${streamInfo.rotated ? ' (rotated)' : ''}`;
this.elements.resolutionInfo.textContent = resText;
}
/**
* Update inference status display
*/
updateInferenceStatus(status) {
this.elements.inferenceStatus.textContent = status;
// Update status styling
this.elements.inferenceStatus.className = 'status-inactive';
if (status.includes('Running')) {
this.elements.inferenceStatus.className = 'status-active';
} else if (status.includes('Processing')) {
this.elements.inferenceStatus.className = 'status-processing';
}
}
/**
* Update acceleration information display
*/
updateAccelerationInfo() {
if (!this.elements.accelerationInfo) return;
const accelerationInfo = this.modelInference.getAccelerationInfo();
// Create acceleration status text
let accelerationText = `Acceleration: ${accelerationInfo.activeProvider.toUpperCase()}`;
// Add GPU info if available
if (accelerationInfo.gpuInfo && accelerationInfo.activeProvider !== 'wasm') {
const gpu = accelerationInfo.gpuInfo;
const vendor = gpu.vendor.includes('Google') ? gpu.renderer.split(' ')[0] : gpu.vendor;
accelerationText += ` (${vendor})`;
}
// Add note if using CPU fallback due to GPU limitations
if (accelerationInfo.activeProvider === 'wasm') {
if (accelerationInfo.webglError && accelerationInfo.webglError.includes('cannot resolve operator')) {
accelerationText += ' (GPU unsupported operators)';
} else if (accelerationInfo.supportsWebGL || accelerationInfo.supportsWebGPU) {
accelerationText += ' (GPU provider failed)';
} else {
accelerationText += ' (No GPU support)';
}
}
this.elements.accelerationInfo.textContent = accelerationText;
// Update styling based on acceleration type
this.elements.accelerationInfo.className = 'acceleration-info';
if (accelerationInfo.activeProvider === 'webgpu') {
this.elements.accelerationInfo.classList.add('acceleration-webgpu');
} else if (accelerationInfo.activeProvider === 'webgl') {
this.elements.accelerationInfo.classList.add('acceleration-webgl');
} else {
this.elements.accelerationInfo.classList.add('acceleration-wasm');
}
}
/**
* Show loading indicator
*/
showLoading() {
let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Loading...';
this.elements.loadingText.textContent = message;
this.elements.loadingIndicator.style.display = 'block';
this.elements.cameraSelection.style.display = 'none';
this.elements.videoContainer.style.display = 'none';
this.elements.errorDisplay.style.display = 'none';
}
/**
* Hide loading indicator
*/
hideLoading() {
this.elements.loadingIndicator.style.display = 'none';
}
/**
* Show camera selection
*/
showCameraSelection() {
this.stopInference();
this.cameraManager.stopCamera();
this.state.isCameraActive = false;
this.elements.cameraSelection.style.display = 'block';
this.elements.videoContainer.style.display = 'none';
this.elements.errorDisplay.style.display = 'none';
}
/**
* Hide camera selection
*/
hideCameraSelection() {
this.elements.cameraSelection.style.display = 'none';
}
/**
* Show video container
*/
showVideoContainer() {
this.elements.videoContainer.style.display = 'block';
this.elements.errorDisplay.style.display = 'none';
}
/**
* Show error message
*/
showError(title, message) {
this.elements.errorMessage.innerHTML = `<strong>${title}</strong><br>${message}`;
this.elements.errorDisplay.style.display = 'block';
this.elements.loadingIndicator.style.display = 'none';
this.elements.cameraSelection.style.display = 'none';
this.elements.videoContainer.style.display = 'none';
this.state.currentError = {
title,
message
};
}
/**
* Hide error display
*/
hideError() {
this.elements.errorDisplay.style.display = 'none';
this.state.currentError = null;
}
/**
* Clean up resources
*/
cleanup() {
console.log('Cleaning up application...');
this.stopInference();
this.cameraManager.dispose();
this.modelInference.dispose();
this.state = {
isInitialized: false,
isModelLoaded: false,
isCameraActive: false,
isInferenceRunning: false,
currentError: null
};
}
}
// Initialize application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
const app = new CardSegmentationApp();
app.init();
// Make app globally available for debugging
window.cardSegmentationApp = app;
});
})();
//# sourceMappingURL=bundle.js.map
|