Edge detection with OpenCV.js
Updated
OpenCV.js, imported from a CDN, finds the edges in a picture drawn on a script canvas with Canny edge detection, and two planes show the picture and its edges side by side.
OpenCV.js is an 11 MB download (2.8 MB compressed): wait a few seconds for the edges to appear. Then click the scene and press Space to try other thresholds. Drag to orbit the camera, scroll to zoom.
Edge detection with OpenCV.js
#pragma import(cv="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@4.11.0-release.1/dist/opencv.js")#pragma lifecycle(startup, update)
const SIZE = 512;const THRESHOLDS = [[50, 150], [100, 200], [20, 60]]; // Canny low and highlet level = 0;let photo = null;let edges = null;let texture = null;
function addPlane(map, x) { const plane = new THREE.Mesh(new THREE.PlaneGeometry(1.4, 1.4), new THREE.MeshBasicMaterial({ map })); plane.position.x = x; self.parent.add(plane);}
function detectEdges() { const [low, high] = THRESHOLDS[level]; const source = cv.imread(photo); // RGBA pixels of the canvas const gray = new cv.Mat(); const result = new cv.Mat(); cv.cvtColor(source, gray, cv.COLOR_RGBA2GRAY); cv.Canny(gray, result, low, high); cv.imshow(edges, result); // white edges on black texture.needsUpdate = true; // Mats live in OpenCV's WebAssembly memory, which is not garbage-collected source.delete(); gray.delete(); result.delete(); log(`Canny thresholds ${low} and ${high}`);}
async function startup() { const image = await new THREE.ImageLoader().loadAsync('/example-assets/Stormtrooper_D.jpg'); photo = Canvas.create(SIZE, SIZE); photo.getContext('2d', { willReadFrequently: true }).drawImage(image, 0, 0, SIZE, SIZE); // cv.imread reads it often edges = Canvas.create(SIZE, SIZE); texture = Canvas.texture(edges); addPlane(Canvas.texture(photo), -0.75); addPlane(texture, 0.75); detectEdges();}
function update() { if (!texture || !Input.keyboard.isKeyReleased(Key.Space)) return; level = (level + 1) % THRESHOLDS.length; detectEdges();}How it works
Section titled “How it works”The script is explained step by step in Edge detection with OpenCV.js.
Open it in XR Creator
Section titled “Open it in XR Creator”Download the project file below, then import it in XR Hub with Projects › New › Import, as described in Projects and templates. It opens in XR Creator with the same scene you see running above, each script already attached to its Behavior entity. From there you can edit the scripts, adjust components and their props, preview your changes, and deploy the result as a world of your own.
OpencvEdges.xrproj