Skip to content

API Reference

Everything is in one class, imported from teachable_machine:

from teachable_machine import TeachableMachine

TeachableMachine

TeachableMachine(model_path='keras_model.h5', labels_file_path='labels.txt', model_type='h5')

Classify images with a Keras model exported from Google's Teachable Machine.

Load an exported Teachable Machine Keras model and its labels.

Parameters:

Name Type Description Default
model_path str

Path to the exported model file. Default is 'keras_model.h5'.

'keras_model.h5'
labels_file_path str

Path to the labels.txt file exported with the model. Default is 'labels.txt'.

'labels.txt'
model_type str

"h5" or "keras", in any letter case. Default is 'h5'.

'h5'

Raises:

Type Description
ValueError

If model_type is not supported.

OSError

If the model or labels file cannot be loaded. Some model errors raise its subclass FileNotFoundError, so catch OSError to handle both.

classify_image

classify_image(image_path: str)

Classify an image using the pre-trained model.

Parameters:

Name Type Description Default
image_path str

Path of the image to be classified.

required

Returns:

Type Description
dict

The classification results. "class_name" is the matching line of labels.txt, "class_index" is its position, "class_confidence" is a value from 0 to 1, and "predictions" holds one value per class.

Raises:

Type Description
FileNotFoundError

If the image file is not found.

TypeError

If the file cannot be opened as an image.

classify_and_show

classify_and_show(image_path: str, convert_to_bgr=True)

Classify an image and show the prediction results on the image.

Parameters:

Name Type Description Default
image_path str

Path of the input image to be classified.

required
convert_to_bgr bool

Whether to convert the image to BGR format for OpenCV. If False, the image is returned in RGB format. Default is True.

True

Returns:

Type Description
tuple

(classification_result, image_with_prediction), where classification_result is the dict returned by classify_image and image_with_prediction is the image with the results drawn on it (see show_prediction_on_image).

show_prediction_on_image

show_prediction_on_image(image_path: str, classification_result=None, convert_to_bgr=True)

Show the prediction results on the image and return the modified image.

Parameters:

Name Type Description Default
image_path str

Path of the input image.

required
classification_result dict

Pre-computed classification result. If not provided, the method classifies the image.

None
convert_to_bgr bool

Whether to convert the image to BGR format for OpenCV. If False, the image is returned in RGB format. Default is True.

True

Returns:

Type Description
ndarray or Image

The image with the prediction results drawn on it: a NumPy array in BGR format if convert_to_bgr is True, otherwise a PIL image in RGB format.