Skip to content

Quick Start

This page takes you from an exported model to live classification on a camera.

Before you start

Your folder should look like this:

my-project/
├── model.tflite
├── labels.txt
└── app.py

Your first classifier

Save this as app.py:

"""Classify webcam frames and show the result on the video. Press Esc to quit."""
import cv2 as cv

from teachable_machine_lite import TeachableMachineLite

cap = cv.VideoCapture(0)
model = TeachableMachineLite(model_path="model.tflite", labels_file_path="labels.txt")

while True:
    ok, frame = cap.read()
    if not ok:
        break

    result, annotated = model.classify_and_show(frame)
    print("result:", result)

    cv.imshow("Camera", annotated)
    if cv.waitKey(1) == 27:  # Esc
        break

cap.release()
cv.destroyAllWindows()

Run it:

python app.py

Show your camera one of the things you trained the model on. The class name and confidence appear at the bottom of the video. To quit, click the video window and press Esc.

Using the Raspberry Pi camera module?

cv.VideoCapture(0) does not work with it on recent Raspberry Pi OS. Use the Raspberry Pi camera example instead.

What each part does

Code Purpose
TeachableMachineLite(...) Loads the model and its labels once.
cv.VideoCapture(0) Opens the first camera.
cap.read() Reads one frame. ok is False if that failed.
model.classify_and_show(frame) Classifies the frame and returns the result and an annotated copy.
cv.imshow(...) Shows the annotated frame.

Act on the result

The result is a dictionary. Check the confidence before you act on the label:

result = model.classify_image(frame)

if result["label"] == "Cat" and result["confidence"] > 80:
    print("There's a cat!")

confidence is a percentage from 0 to 100. See Results for every key.

Next steps