MJRoBot (Marcelo Rovai)
Published © Apache-2.0

Mug, or not Mug, that is the question!

EdgeAI made simple - Exploring Image Processing (Image Classification) on microcontrollers with Arduino Portenta, Edge Impulse, and OpenMV.

IntermediateFull instructions provided8 hours4,310
Mug, or not Mug, that is the question!

Things used in this project

Hardware components

Arduino Portenta H7
Arduino Portenta H7
×1
Arduino Portenta Vision Shield - Ethernet
Arduino Portenta Vision Shield - Ethernet
×1

Software apps and online services

Arduino IDE
Arduino IDE
Edge Impulse Studio
Edge Impulse Studio
OpenMV IDE

Story

Read more

Code

main.py

MicroPython
"""
OpenMV Live Image Inference
Continuously captures images and performs image using provided TFLite model
file. Outputs probabilities in console.
Author: EdgeImpulse, Inc.
Date: June 24, 2021
License: Apache-2.0 (apache.org/licenses/LICENSE-2.0)

Modified by MJRovai
MCU: Arduino Portenta H7
Date: March 18, 2022
"""

import sensor, image, time, tf, pyb

#  initializing the LEDs
ledRed = pyb.LED(1)   # Initiates the red led
ledGreen = pyb.LED(2) # Initiates the green led

# Location of TFLite model file and Labels list
model_file = "ei-mug_or_not_mug-transfer-learning-tensorflow-lite-int8-quantized-model.lite"           
labels = ["mug", "no_mug"]              

# Configure camera
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)  # Set pixel format to GRAYSCALE
sensor.set_framesize(sensor.QVGA)       # Set frame size to QVGA (320x240)
sensor.set_windowing((96, 96))          # Crop sensor frame to model resolution
sensor.skip_frames(time = 2000)         # Let the camera adjust

# Start clock (for measureing FPS)
clock = time.clock()

# Main while loop
while(True):

    # Update timer
    clock.tick()

    # Get image from camera
    img = sensor.snapshot()
    img.set(h_mirror=True)

    # Do inference and get predictions
    objs = tf.classify(model_file, img)
    predictions = objs[0].output()

    # Find label with the highest probability
    max_val = max(predictions)
    max_idx = predictions.index(max_val)
    
    if max_idx == 0:    # turn on red led
        ledRed.off()
        ledGreen.on()
    else:               # turn on green led
        ledRed.on() 
        ledGreen.off()

    # Draw label with highest probability to image viewer
    img.draw_string(
        0, 0, 
        labels[max_idx] + "\n{:.2f}".format(round(max_val, 2)), 
        mono_space = False,  
        scale=1
        )
        
    #Print all the probabilities
    print("-----")
    for i, label in enumerate(labels):
        print(str(label) + ": " + str(predictions[i]))
    print("FPS:", clock.fps())

Credits

MJRoBot (Marcelo Rovai)

MJRoBot (Marcelo Rovai)

60 projects • 913 followers
Professor, Engineer, MBA, Master in Data Science. Writes about Electronics with a focus on Physical Computing, IoT, ML, TinyML and Robotics.

Comments