以下是一個基于JavaScript的商品圖片識別示例代碼:
<!DOCTYPE html>
<html>
<head>
<title>商品圖片識別</title>
</head>
<body>
<input type="file" id="fileInput" accept="image/*">
<button onclick="recognize()">識別圖片</button>
<div id="result"></div>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"></script>
<script>
async function recognize() {
const fileInput = document.getElementById("fileInput");
const file = fileInput.files[0];
if (!file) {
alert("請先選擇圖片");
return;
}
const imgElement = document.createElement("img");
imgElement.src = URL.createObjectURL(file);
imgElement.width = 224;
imgElement.height = 224;
const resultElement = document.getElementById("result");
resultElement.innerHTML = "";
resultElement.appendChild(imgElement);
const model = await mobilenet.load();
const predictions = await model.classify(imgElement);
for (let i = 0; i < predictions.length; i++) {
const { className, probability } = predictions[i];
const pElement = document.createElement("p");
pElement.innerText = `${className}: ${probability.toFixed(3)}`;
resultElement.appendChild(pElement);
}
}
</script>
</body>
</html>
你可以將上述代碼保存為一個名為 index.html
的文件,并在瀏覽器中打開該文件。然后,選擇你的商品圖片并點擊 "識別圖片" 按鈕,識別結果將會顯示在頁面上。
請注意,該示例使用了 TensorFlow.js 庫和 MobileNet 模型來進行圖片分類。要從互聯網加載模型,需要聯網訪問 https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet
。此外,圖片文件沒有限制,但需要確保圖片文件為有效的圖像文件。
希望這能幫助到你!