index.html 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. <!-- Pre and post-processing functions from: https://github.com/AndreyGermanov/yolov8_onnx_javascript -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>YOLOv8 tinygrad WebGL</title>
  7. <script src="./net.js"></script>
  8. <style>
  9. body {
  10. text-align: center;
  11. font-family: Arial, sans-serif;
  12. margin: 0;
  13. padding: 0;
  14. overflow: hidden;
  15. }
  16. .video-container {
  17. position: relative;
  18. width: 100%;
  19. margin: 0 auto;
  20. }
  21. #video, #canvas {
  22. position: absolute;
  23. top: 0;
  24. left: 0;
  25. width: 100%;
  26. height: auto;
  27. }
  28. #canvas {
  29. background: transparent;
  30. }
  31. h1 {
  32. margin-top: 20px;
  33. }
  34. </style>
  35. </head>
  36. <body>
  37. <h1>YOLOv8 tinygrad WebGL</h1>
  38. <div class="video-container">
  39. <video id="video" muted autoplay playsinline></video>
  40. <canvas id="canvas"></canvas>
  41. </div>
  42. <script>
  43. let net = null;
  44. const video = document.getElementById('video');
  45. const canvas = document.getElementById('canvas');
  46. const context = canvas.getContext('2d');
  47. const offscreenCanvas = document.createElement('canvas');
  48. offscreenCanvas.width = 640;
  49. offscreenCanvas.height = 640;
  50. const offscreenContext = offscreenCanvas.getContext('2d');
  51. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  52. navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(function (stream) {
  53. video.srcObject = stream;
  54. video.onloadedmetadata = function() {
  55. canvas.width = video.clientWidth;
  56. canvas.height = video.clientHeight;
  57. }
  58. });
  59. }
  60. async function processFrame() {
  61. offscreenContext.drawImage(video, 0, 0, 640, 640);
  62. const boxes = await detectObjectsOnFrame(offscreenContext);
  63. drawBoxes(offscreenCanvas, boxes);
  64. requestAnimationFrame(processFrame);
  65. }
  66. requestAnimationFrame(processFrame);
  67. function drawBoxes(offscreenCanvas, boxes) {
  68. const canvas = document.querySelector("canvas");
  69. const ctx = canvas.getContext("2d");
  70. ctx.clearRect(0, 0, canvas.width, canvas.height);
  71. ctx.lineWidth = 3;
  72. ctx.font = "20px serif";
  73. const scaleX = canvas.width / 640;
  74. const scaleY = canvas.height / 640;
  75. boxes.forEach(([x1, y1, x2, y2, label]) => {
  76. const classIndex = yolo_classes.indexOf(label);
  77. const color = classColors[classIndex];
  78. const textWidth = ctx.measureText(label).width;
  79. ctx.strokeStyle = color;
  80. ctx.fillStyle = color;
  81. let adjustedX1 = x1 * scaleX;
  82. let adjustedY1 = y1 * scaleY;
  83. let adjustedX2 = x2 * scaleX;
  84. let adjustedY2 = y2 * scaleY;
  85. let boxWidth = adjustedX2 - adjustedX1;
  86. let boxHeight = adjustedY2 - adjustedY1;
  87. ctx.strokeRect(adjustedX1, adjustedY1, boxWidth, boxHeight);
  88. ctx.fillRect(adjustedX1, adjustedY1 - 25, textWidth + 10, 25);
  89. ctx.fillStyle = "#000000";
  90. ctx.fillText(label, adjustedX1, adjustedY1 - 7);
  91. });
  92. }
  93. async function detectObjectsOnFrame(offscreenContext) {
  94. if (!net) net = await loadNet();
  95. let start = performance.now();
  96. const [input,img_width,img_height] = await prepareInput(offscreenContext);
  97. console.log("Preprocess took: " + (performance.now() - start) + " ms");
  98. start = performance.now();
  99. const output = net(new Float32Array(input));
  100. console.log("Inference took: " + (performance.now() - start) + " ms");
  101. start = performance.now();
  102. let out = processOutput(output,img_width,img_height);
  103. console.log("Postprocess took: " + (performance.now() - start) + " ms");
  104. return out;
  105. }
  106. async function prepareInput(offscreenContext) {
  107. return new Promise(resolve => {
  108. const [img_width,img_height] = [640, 640]
  109. const imgData = offscreenContext.getImageData(0,0,640,640);
  110. const pixels = imgData.data;
  111. const red = [], green = [], blue = [];
  112. for (let index=0; index<pixels.length; index+=4) {
  113. red.push(pixels[index]/255.0);
  114. green.push(pixels[index+1]/255.0);
  115. blue.push(pixels[index+2]/255.0);
  116. }
  117. const input = [...red, ...green, ...blue];
  118. resolve([input, img_width, img_height])
  119. })
  120. }
  121. const loadNet = async () => {
  122. try {
  123. const safetensor = await (new Uint8Array(await (await fetch("./net.safetensors")).arrayBuffer()));
  124. const gl = document.createElement("canvas").getContext("webgl2");
  125. return setupNet(gl, safetensor);
  126. } catch (e) {
  127. console.log(e);
  128. return null;
  129. }
  130. }
  131. function processOutput(output, img_width, img_height) {
  132. let boxes = [];
  133. for (let index=0;index<8400;index++) {
  134. const [class_id,prob] = [...Array(80).keys()]
  135. .map(col => [col, output[8400*(col+4)+index]])
  136. .reduce((accum, item) => item[1]>accum[1] ? item : accum,[0,0]);
  137. if (prob < 0.25) {
  138. continue;
  139. }
  140. const label = yolo_classes[class_id];
  141. const xc = output[index];
  142. const yc = output[8400+index];
  143. const w = output[2*8400+index];
  144. const h = output[3*8400+index];
  145. const x1 = (xc-w/2)/640*img_width;
  146. const y1 = (yc-h/2)/640*img_height;
  147. const x2 = (xc+w/2)/640*img_width;
  148. const y2 = (yc+h/2)/640*img_height;
  149. boxes.push([x1,y1,x2,y2,label,prob]);
  150. }
  151. boxes = boxes.sort((box1,box2) => box2[5]-box1[5])
  152. const result = [];
  153. while (boxes.length>0) {
  154. result.push(boxes[0]);
  155. boxes = boxes.filter(box => iou(boxes[0],box)<0.7);
  156. }
  157. return result;
  158. }
  159. function iou(box1,box2) {
  160. return intersection(box1,box2)/union(box1,box2);
  161. }
  162. function union(box1,box2) {
  163. const [box1_x1,box1_y1,box1_x2,box1_y2] = box1;
  164. const [box2_x1,box2_y1,box2_x2,box2_y2] = box2;
  165. const box1_area = (box1_x2-box1_x1)*(box1_y2-box1_y1)
  166. const box2_area = (box2_x2-box2_x1)*(box2_y2-box2_y1)
  167. return box1_area + box2_area - intersection(box1,box2)
  168. }
  169. function intersection(box1,box2) {
  170. const [box1_x1,box1_y1,box1_x2,box1_y2] = box1;
  171. const [box2_x1,box2_y1,box2_x2,box2_y2] = box2;
  172. const x1 = Math.max(box1_x1,box2_x1);
  173. const y1 = Math.max(box1_y1,box2_y1);
  174. const x2 = Math.min(box1_x2,box2_x2);
  175. const y2 = Math.min(box1_y2,box2_y2);
  176. return (x2-x1)*(y2-y1)
  177. }
  178. const yolo_classes = [
  179. 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat',
  180. 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',
  181. 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase',
  182. 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
  183. 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
  184. 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant',
  185. 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven',
  186. 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
  187. ];
  188. function generateColors(numColors) {
  189. const colors = [];
  190. for (let i = 0; i < 360; i += 360 / numColors) {
  191. colors.push(`hsl(${i}, 100%, 50%)`);
  192. }
  193. return colors;
  194. }
  195. const classColors = generateColors(yolo_classes.length);
  196. </script>
  197. </body>
  198. </html>