Skip to content

Quick Start

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

Before you start

Your folder should look like this:

my-project/
├── keras_model.h5
├── 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 import TeachableMachine

cap = cv.VideoCapture(0)
model = TeachableMachine(model_path="keras_model.h5", labels_file_path="labels.txt")

image_path = "screenshot.jpg"

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

    cv.imwrite(image_path, frame)  # the package reads images from files

    result, annotated = model.classify_and_show(image_path)

    print("class_index:", result["class_index"])
    print("class_name:", result["class_name"])
    print("class_confidence:", result["class_confidence"])
    print("predictions:", result["predictions"])

    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.

What each part does

Code Purpose
TeachableMachine(...) Loads the model and its labels once.
cv.VideoCapture(0) Opens the first camera.
cv.imwrite(image_path, frame) Saves the frame, because the package reads images from files.
model.classify_and_show(image_path) Classifies the image and returns the result and an annotated copy.
cv.imshow(...) Shows the annotated image.

Act on the result

class_confidence goes from 0 to 1, so 80% is 0.8:

result = model.classify_image("photo.jpg")
label = result["class_name"].split(maxsplit=1)[-1]

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

Next steps