Teachable Machine Community Libraries

repository·master·Indexed 23 days ago

https://github.com/googlecreativelab/teachablemachine-community

Libraries and implementation snippets for using exported Teachable Machine machine learning models (image, audio, and pose) in projects via TensorFlow.js. Includes @teachablemachine/image (v0.8.5-alpha2), @teachablemachine/pose, and audio support libraries for loading models from URLs or local files, performing predictions, and managing webcam input.

Tokens
16K
Snippets
28
Records
94
Agent score
81%

What's inside teachablemachine-community

  1. Overview of Teachable Machine Community

    master

    The Teachable Machine Community repository provides the core machine learning libraries and code snippets used by the Teachable Machine web tool. It is designed to help developers integrate pre-trained machine learning models into their own web, mobile, or desktop applications.

    The repository is divided into two main parts:

    1. Libraries: Contains the machine learning code powered by TensorFlow.js. It includes helper libraries for image, audio, and pose recognition to simplify using exported models in JavaScript environments.
    2. Snippets: Contains markdown-based code snippets and instructions used in the Teachable Machine export panel. These snippets provide implementation guidance for various languages, including JavaScript, Java, and Python.
  2. Understand Teachable Machine export snippets

    master

    This repository contains the markdown snippets used in the Teachable Machine export panel. These snippets provide code examples and instructions for deploying exported models in various languages, including Javascript, Java, and Python.

    Snippets are organized by model type and export format:

    • Model Types: image, pose, and audio.
    • Export Formats: e.g., tensorflow js, tflite.

    Developers can use these snippets as a reference for integrating Teachable Machine models into their own applications.

  3. Perform pose estimation and classification

    master

    To get a prediction, you must run the input through a two-step process: first through the PoseNet model to estimate keypoints, and then through the Teachable Machine classification model.

    Step 1: Estimate Pose

    Use model.estimatePose() to get keypoints and the raw output required for classification.

    // Returns { pose, posenetOutput }
    const { pose, posenetOutput } = await model.estimatePose(webcamElement, flipHorizontal);

    Step 2: Classify Pose

    Pass the posenetOutput from the first step into model.predict() or model.predictTopK() to get the class probabilities.

    // Standard prediction
    const prediction = await model.predict(posenetOutput);
    
    // Get top K predictions
    const maxPredictions = model.getTotalClasses();
    const prediction = await model.predictTopK(posenetOutput, maxPredictions);
  4. Access Teachable Machine audio model checkpoints

    master

    When you export an audio model from Teachable Machine, you are provided with a unique model URL in the format: https://teachablemachine.withgoogle.com/models/MODEL_ID/

    You can use this base URL to access specific model files required for the library:

    • Model Topology: https://teachablemachine.withgoogle.com/models/MODEL_ID/model.json
    • Model Metadata: https://teachablemachine.withgoogle.com/models/MODEL_ID/metadata.json
  5. Connect OV7670 Camera to Arduino Nano 33 BLE

    master

    Use female-to-female leads to connect the pins according to the following mapping. Note that pin labels on your specific OV7670 variant may vary slightly, but the layout remains the same.

    OV7670 Camera PinArduino Pin
    3.3v3.3v
    GNDGND
    SCL/SIOCA5
    SDA/SIODA4
    VS/VSYNCD8
    HS/HREFA1
    PCLKA0
    MCLK/XCLKD9
    D7D4
    D6D6
    D5D5
    D4D3
    D3D2
    D2D0 / RX
    D1D1 / TX
    D0D10

    Leave any remaining pins on the OV7670 disconnected.

  6. How to load a Teachable Machine Pose model

    master

    There are two ways to load a model depending on whether you are using remote URLs or local files.

    Loading from URLs

    Use tmPose.load() to load a model from a Teachable Machine checkpoint URL. The checkpoint URL should point to the directory containing model.json and metadata.json.

    // Example: URL is the link provided by Teachable Machine export panel
    const modelURL = 'https://teachablemachine.withgoogle.com/models/MODEL_ID/model.json';
    const metadataURL = 'https://teachablemachine.withgoogle.com/models/MODEL_ID/metadata.json';
    const model = await tmPose.load(modelURL, metadataURL);

    Loading from local files

    Use tmPose.loadFromFiles() to load model files directly from a user's local device (e.g., via a file picker). This requires three File objects.

    // model, weights, and metadata must be File objects from an <input type='file'>
    model = await tmPose.loadFromFiles(uploadModel.files[0], uploadWeights.files[0], uploadMetadata.files[0]);
  7. Run Teachable Machine image models in Python using Keras and OpenCV

    master

    You can use a Teachable Machine exported Keras model (.h5) and labels (labels.txt) in a Python environment by combining tensorflow/keras, opencv-python, and numpy.

    Prerequisites

    • TensorFlow/Keras: Required to load and run the .h5 model.
    • OpenCV (opencv-python): Used for camera access and image processing.
    • NumPy: Used for array manipulation and normalization.

    Implementation Workflow

    1. Load Assets: Use keras.models.load_model for the model and standard file I/O for the labels.txt file.
    2. Capture Video: Initialize cv2.VideoCapture(0) to access the webcam.
    3. Pre-process Image:
      • Resize the frame to (224, 224) using cv2.resize.
      • Convert the image to a NumPy array with dtype=np.float32.
      • Reshape the array to (1, 224, 224, 3) to match the model's expected input shape.
      • Normalize: Scale the pixel values using the formula (image / 127.5) - 1.
    4. Inference: Call model.predict(image) to get confidence scores, then use np.argmax() to find the predicted class index.
    5. Cleanup: Release the camera and close windows using camera.release() and cv2.destroyAllWindows().
    from keras.models import load_model  # TensorFlow is required for Keras to work
    import cv2  # Install opencv-python
    import numpy as np
    
    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)
    
    # Load the model
    model = load_model("keras_Model.h5", compile=False)
    
    # Load the labels
    class_names = open("labels.txt", "r").readlines()
    
    # CAMERA can be 0 or 1 based on default camera of your computer
    camera = cv2.VideoCapture(0)
    
    while True:
        # Grab the webcamera's image.
        ret, image = camera.read()
    
        # Resize the raw image into (224-height,224-width) pixels
        image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)
    
        # Show the image in a window
        cv2.imshow("Webcam Image", image)
    
        # Make the image a numpy array and reshape it to the models input shape.
        image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)
    
        # Normalize the image array
        image = (image / 127.5) - 1
    
        # Predicts the model
        prediction = model.predict(image)
        index = np.argmax(prediction)
        class_name = class_names[index]
        confidence_score = prediction[0][index]
    
        # Print prediction and confidence score
        print("Class:", class_name[2:], end="")
        print("Confidence Score:", str(np.round(confidence_score * 100))[:-2], "%")
    
        # Listen to the keyboard for presses.
        keyboard_input = cv2.waitKey(1)
    
        # 27 is the ASCII for the esc key on your keyboard.
        if keyboard_input == 27:
            break
    
    camera.release()
    cv2.destroyAllWindows()
  8. Install requirements for Coral Edge TPU

    master

    To use Teachable Machine models with a Coral Edge TPU, you must install the Edge TPU Runtime library and the PyCoral API along with necessary image processing packages.

    1. Install the Edge TPU Runtime library.
    2. Install the PyCoral API and dependencies using pip:
    python3 -m pip install --extra-index-url https://google-coral.github.io/py-repo/ pycoral~=2.0 Pillow opencv-python opencv-contrib-python
  9. Install the Teachable Machine Image library

    master

    You can use the @teachablemachine/image library in two ways:

    Via Script Tag

    Include TensorFlow.js and the Teachable Machine Image library in your HTML:

    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.3.1/dist/tf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@0.8.3/dist/teachablemachine-image.min.js"></script>

    Via NPM

    Install both dependencies using npm:

    npm i @tensorflow/tfjs
    npm i @teachablemachine/image

    Then import them in your JavaScript/TypeScript files:

    import * as tf from '@tensorflow/tfjs';
    import * as tmImage from '@teachablemachine/image';
  10. Train and Export the Embedded Model

    master

    1. Collect Data

    Position the camera approximately one foot from your target objects. Use the 'Record' button in Teachable Machine to collect samples for each class. Ensure samples reflect real-world lighting conditions.

    2. Train

    Click Train. Do not switch browser tabs while the model is training.

    3. Test

    In the preview window, select Device from the input dropdown to see real-time classification from your OV7670 camera.

    4. Export to Arduino

    1. Click Export model.
    2. Select Tensorflow Lite -> Tensorflow Lite for Microcontrollers.
    3. Click 'Download my Model'. This downloads a .zip containing an Arduino sketch with your model pre-loaded.
    4. Close any running Processing sketches.
    5. Upload the downloaded sketch to your Arduino.
    6. Open the Serial Monitor to see class names and confidence scores (ranging from -128 to 127).
  11. Run Teachable Machine image model inference with Keras and Python

    master

    To use a Teachable Machine image model in a Python environment, you can use keras.models.load_model to load the exported .h5 file and PIL (Pillow) for image preprocessing.

    Preprocessing Requirements

    1. Image Resizing: The image must be resized to at least 224x224 and center-cropped. Using ImageOps.fit with Image.Resampling.LANCZOS is recommended.
    2. Normalization: Convert the image to a NumPy array and normalize the pixel values to a range of [-1, 1] using the formula: (image_array.astype(np.float32) / 127.5) - 1.
    3. Data Shape: The model expects a 4D NumPy array with the shape (1, 224, 224, 3), where 1 represents the batch size (number of images).

    Dependencies

    • tensorflow (required for Keras)
    • keras
    • pillow (for image processing)
    • numpy
    from keras.models import load_model  # TensorFlow is required for Keras to work
    from PIL import Image, ImageOps  # Install pillow instead of PIL
    import numpy as np
    
    # Disable scientific notation for clarity
    np.set_printoptions(suppress=True)
    
    # Load the model
    model = load_model("keras_Model.h5", compile=False)
    
    # Load the labels
    class_names = open("labels.txt", "r").readlines()
    
    # Create the array of the right shape to feed into the keras model
    # The 'length' or number of images you can put into the array is
    # determined by the first position in the shape tuple, in this case 1
    data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
    
    # Replace this with the path to your image
    image = Image.open("<IMAGE_PATH>").convert("RGB")
    
    # resizing the image to be at least 224x224 and then cropping from the center
    size = (224, 224)
    image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
    
    # turn the image into a numpy array
    image_array = np.asarray(image)
    
    # Normalize the image
    normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
    
    # Load the image into the array
    data[0] = normalized_image_array
    
    # Predicts the model
    prediction = model.predict(data)
    index = np.argmax(prediction)
    class_name = class_names[index]
    confidence_score = prediction[0][index]
    
    # Print prediction and confidence score
    print("Class:", class_name[2:], end="")
    print("Confidence Score:", confidence_score)