* Given an image element, makes a prediction through mobilenet returning the * probabilities of the top K classes.
(imgElement)
| 59 | * probabilities of the top K classes. |
| 60 | */ |
| 61 | async function predict(imgElement) { |
| 62 | status('Predicting...'); |
| 63 | |
| 64 | // The first start time includes the time it takes to extract the image |
| 65 | // from the HTML and preprocess it, in additon to the predict() call. |
| 66 | const startTime1 = performance.now(); |
| 67 | // The second start time excludes the extraction and preprocessing and |
| 68 | // includes only the predict() call. |
| 69 | let startTime2; |
| 70 | const logits = tf.tidy(() => { |
| 71 | // tf.browser.fromPixels() returns a Tensor from an image element. |
| 72 | const img = tf.cast(tf.browser.fromPixels(imgElement), 'float32'); |
| 73 | |
| 74 | const offset = tf.scalar(127.5); |
| 75 | // Normalize the image from [0, 255] to [-1, 1]. |
| 76 | const normalized = img.sub(offset).div(offset); |
| 77 | |
| 78 | // Reshape to a single-element batch so we can pass it to predict. |
| 79 | const batched = normalized.reshape([1, IMAGE_SIZE, IMAGE_SIZE, 3]); |
| 80 | |
| 81 | startTime2 = performance.now(); |
| 82 | // Make a prediction through mobilenet. |
| 83 | return mobilenet.predict(batched); |
| 84 | }); |
| 85 | |
| 86 | // Convert logits to probabilities and class names. |
| 87 | const classes = await getTopKClasses(logits, TOPK_PREDICTIONS); |
| 88 | const totalTime1 = performance.now() - startTime1; |
| 89 | const totalTime2 = performance.now() - startTime2; |
| 90 | status(`Done in ${Math.floor(totalTime1)} ms ` + |
| 91 | `(not including preprocessing: ${Math.floor(totalTime2)} ms)`); |
| 92 | |
| 93 | // Show the classes in the DOM. |
| 94 | showResults(imgElement, classes); |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Computes the probabilities of the topK classes given logits by computing |
no test coverage detected