Mental model
Browser image classification decodes an image into pixels, applies the model's configured resize and normalization, and runs a classifier in the client runtime. The output logits become class probabilities, but a useful result also needs a correct label map, a calibrated decision threshold, a supported device, and a traceable input. Classification labels an image as a whole; object detection returns locations as well as labels.
Theory
A browser pipeline starts with an encoded file such as JPEG or PNG. The decoder handles orientation and color representation, then the model's image processor resizes or crops to the shape used during training. It may convert channels to RGB, scale integer pixels, and normalize each channel with model-specific means and standard deviations. A model trained on center-cropped 224 by 224 images should not receive a stretched 640 by 480 bitmap merely because that fits the page. CSS resizing changes presentation; it does not change the tensor sent to inference.
A classifier's final layer produces one logit per class. Softmax converts logits into values that sum to one:
Here, is the logit for class , is the number of classes, and is a dimensionless normalized score. A top result is a ranking, not proof that the label is correct. Calibration asks whether predictions assigned a probability such as 0.8 are correct about 80 percent of the time on a representative sample. A single-label classifier assumes one class wins; multilabel tasks need independent sigmoid scores and per-class thresholds. Do not apply a softmax threshold to a detector whose output contains separate boxes and scores.
ResNet's residual connections and the Vision Transformer (ViT)'s image patches are different model designs, but both still rely on the exact preprocessing and label mapping shipped with their checkpoint. The Transformers.js image processor can apply the model-specific transform before its ONNX Runtime backend executes the graph. Keep the processor configuration with the weights and pin a model revision; otherwise the same file can produce a different tensor after a model or processor update.
Memory estimate and worked example
Decoded image memory is often the first surprise on a phone. For a decoded bitmap with width pixels, height pixels, channels, and bytes per channel:
The result is bytes. A 4032 by 3024 photograph decoded as four 8-bit channels occupies bytes, about 46.5 MiB. A 224 by 224 RGB tensor in float32 occupies bytes, about 0.57 MiB. During preprocessing, the large bitmap and smaller tensor can coexist; the model weights, activations, WebGPU buffers, and page itself add more. A safe budget is measured at peak, not inferred from the final tensor size.
Runtime path
If WebGPU is available in the worker, a browser runtime may accelerate supported graph operations. WebGPU support and operator coverage vary by browser, operating system, and model; WASM is a useful CPU fallback for supported models, often with different latency and memory behavior. The worker below checks the decoded dimensions, shrinks an oversized bitmap before the model processor creates a tensor, and releases each ImageBitmap after inference. The decoder must materialize the source image before its dimensions are known, so a compressed-file byte limit alone cannot guarantee a hard peak-memory ceiling. A browser can evict cached model files or terminate a worker under memory pressure, so local inference still needs a retry or explicit failure state.
Implementation example
Instantiate this file as a module worker in the page, then post a File and request id to it. Image decoding, bounded resizing, model loading, and inference run away from the UI thread. The checkpoint's processor performs its own model-specific resize and normalization after the bounded bitmap is produced. Returned scores are candidates for ranking, not calibrated decisions.
typescriptimport { pipeline } from "@huggingface/transformers";type Job = { id: number; file: File };type Prediction = { label: string; score: number };const worker = self as unknown as DedicatedWorkerGlobalScope;const maxEdge = 1024;const maxPixels = maxEdge * maxEdge;const modelId = "Xenova/vit-base-patch16-224";const classifierPromise = (async () => {if (navigator.gpu) {try {return await pipeline("image-classification", modelId, { device: "webgpu" });} catch {// Feature detection cannot guarantee model or operator support.}}return pipeline("image-classification", modelId);})();worker.onmessage = async ({ data }: MessageEvent<Job>) => {let bitmap: ImageBitmap | undefined;try {if (!data.file.type.startsWith("image/") || data.file.size > 15 * 1024 * 1024) {throw new TypeError("Unsupported image or file exceeds the byte limit");}bitmap = await createImageBitmap(data.file, { imageOrientation: "from-image" });const edge = Math.max(bitmap.width, bitmap.height);if (edge > maxEdge) {const scale = maxEdge / edge;const smaller = await createImageBitmap(bitmap, {resizeWidth: Math.max(1, Math.floor(bitmap.width * scale)),resizeHeight: Math.max(1, Math.floor(bitmap.height * scale)),resizeQuality: "high",});bitmap.close();bitmap = smaller;}if (bitmap.width > maxEdge || bitmap.height > maxEdge ||bitmap.width * bitmap.height > maxPixels) {throw new RangeError("Decoded image exceeds the pixel budget");}const classifier = await classifierPromise;const output = await classifier(bitmap, { top_k: 5 });const predictions = output.filter((item: Prediction) => Number.isFinite(item.score),);worker.postMessage({ id: data.id, predictions });} catch (error) {worker.postMessage({id: data.id,error: error instanceof Error ? error.message : "Image inference failed",});} finally {bitmap?.close();}};
Failure modes and misconceptions
A common bug is to normalize twice: the application scales and standardizes pixels, then the model processor repeats the same transform. Another is to preserve the correct dimensions but swap RGB and BGR channel order. Both can yield plausible scores while destroying accuracy. Record the processor revision and test known images through the same preprocessing path used in the browser.
The highest score is not automatically a safe action. A photo may contain an out-of-distribution object, multiple valid labels, or a crop that removes the evidence. Measure per-class calibration and error rates on the images users actually submit. If the score does not clear a validated threshold, ask for another photo or route the item for review. Object detection needs a different output contract because boxes, coordinates, and per-object confidence must be validated too.
Trade-offs
Keeping image bytes on the device can reduce exposure and work offline after model download, but the initial weights still consume bandwidth and local storage. WebGPU may reduce inference time on one GPU and fail on another; WASM is more widely available but can block a small device with CPU work unless inference runs off the main thread. A smaller quantized model may fit more devices but change borderline predictions. Compare backend and model variants on the same labeled holdout set and measure cold download, warm inference, peak memory, and battery use separately.
Decision scenario
A catalog app receives 12-megapixel package photos. A ViT classifier is accurate on desktop but mobile Safari falls back to WASM and occasionally runs out of memory. Do not lower the confidence threshold to make the demo look complete. Decode in a worker, enforce a 1024-pixel longest-edge and one-megapixel output budget before model tensor creation, and measure peak memory and latency on representative phones. Keep ambiguous or low-confidence labels as suggestions, and use a detector only if the workflow needs object locations rather than one label for the whole photo.
Learning outcomes
- Trace encoded image bytes through decode, preprocessing, logits, calibration, and a user-facing label.
- Estimate decoded and tensor memory in bytes and explain why peak memory is larger.
- Distinguish whole-image classification from object detection and choose an appropriate output contract.
- Design a browser fallback and review path for unsupported operators or uncertain predictions.