这是一个使用摄像头扫描图像并将其转换为头像的网站。你可以使用它来创建头像、个性化社交媒体资料,或仅仅是出于乐趣。
css
/ {box-sizing: border-box;margin: 0;padding: 0;
} /body {font-family: Arial, sans-serif;line-height: 1.5;
}h1 {margin-bottom: 1em;
}p {margin-bottom: 1em;
}camera {width: 320px;height: 240px;border: 1px solid black;margin: 0 auto;
}video {width: 100%;height: 100%;
}start-button {display: block;margin: 0 auto;padding: 10px;background: 333;color: fff;border: none;cursor: pointer;
}results {width: 100%;padding: 10px;margin: 20px auto;border: 1px solid black;
}.avatar {width: 100px;height: 100px;margin: 0 auto;border: 1px solid black;border-radius: 50%;
}
javascript
const video = document.getElementById("video");
const results = document.getElementById("results");
const startButton = document.getElementById("start-button");let model;async function loadModel() {model = await tf.loadGraphModel('model.json');
}async function startCamera() {const stream = await navigator.mediaDevices.getUserMedia({ video: true });video.srcObject = stream;await video.play();startButton.classList.add("hidden");const canvas = document.createElement("canvas");canvas.width = video.videoWidth;canvas.height = video.videoHeight;const ctx = canvas.getContext("2d");const loop = async () => {ctx.drawImage(video, 0, 0, canvas.width, canvas.height);const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);const input = tf.browser.fromPixels(imageData);const resized = tf.image.resizeBilinear(input, [224, 224]);const preprocessed = tf.div(resized, 255.0);const predictions = await model.predict(preprocessed);const top5 = tf.topk(predictions, 5);const values = await top5.values;const indices = await top5.indices;results.innerHTML = "";for (let i= 0; i < values.shape[0]; i++) {const avatar = document.createElement("div");avatar.classList.add("avatar");avatar.style.backgroundColor = `rgb(${values[i].data[0]}, ${values[i].data[1]}, ${values[i].data[2]})`;results.appendChild(avatar);}requestAnimationFrame(loop);};loop();
}loadModel();