| 10 | const image = useRef(null); |
| 11 | |
| 12 | const load = async () => { |
| 13 | try { |
| 14 | // Load mobilenet. |
| 15 | await tf.ready(); |
| 16 | const model = await mobilenet.load(); |
| 17 | setIsTfReady(true); |
| 18 | |
| 19 | // Start inference and show result. |
| 20 | const image = require('./basketball.jpg'); |
| 21 | const imageAssetPath = Image.resolveAssetSource(image); |
| 22 | const response = await fetch(imageAssetPath.uri, {}, { isBinary: true }); |
| 23 | const imageDataArrayBuffer = await response.arrayBuffer(); |
| 24 | const imageData = new Uint8Array(imageDataArrayBuffer); |
| 25 | const imageTensor = decodeJpeg(imageData); |
| 26 | const prediction = await model.classify(imageTensor); |
| 27 | if (prediction && prediction.length > 0) { |
| 28 | setResult( |
| 29 | `${prediction[0].className} (${prediction[0].probability.toFixed(3)})` |
| 30 | ); |
| 31 | } |
| 32 | } catch (err) { |
| 33 | console.log(err); |
| 34 | } |
| 35 | }; |
| 36 | |
| 37 | useEffect(() => { |
| 38 | load(); |