Google Colaboratory
This guide is broken into cells that you can run sequentially in Colab. It follows your description, focusing on installing the required libraries, uploading your trained model, and running predictions on test images using cvzone.
This notebook implements the prediction steps from your description. The initial training must be completed first on the Google Teachable Machine website.
As you described, you must first:
Go to Google Teachable Machine.
Create a "Standard Image Project."
Create your classes (e.g., 'Tomato_healthy', 'Tomato_virus', etc.).
Upload your training images for each class from the Kaggle dataset.
Click "Train Model" and wait for it to complete.
Click "Export Model", select the "TensorFlow" tab, and click "Download my model".
This will download a zip file, usually named converted_keras.zip. This file contains your Keras model.H5 and labels.txt.
# First, we need to install the cvzone and tensorflow libraries.
# Run this cell to install the necessary libraries
!pip install cvzone tensorflow
Run the cell below. It will open an "Upload" button. Select the converted_keras.zip file you downloaded from Teachable Machine.
# Run this cell to upload your model zip file
from google.colab import files
print("Please upload the 'converted_keras.zip' file downloaded from Teachable Machine.")
uploaded = files.upload()
# Get the name of the uploaded file
zip_name = list(uploaded.keys())[0]
print(f"Uploaded file: {zip_name}")
Now, let's unzip the file. This will extract the Keras model.H5 and labels.txt files into your Colab environment, just as you described.
Python
# Run this cell to unzip the model files
import os
# Unzip the file
!unzip -q "$zip_name"
# Verify that the files are extracted
if os.path.exists('Keras model.H5') and os.path.exists('labels.txt'):
print("Model files extracted successfully:")
!ls -l "Keras model.H5" labels.txt
else:
print("Error: Model files not found. Please ensure the zip file contains 'Keras model.H5' and 'labels.txt'.")
Note: Your Teachable Machine export must contain files with the exact names Keras model.H5 and labels.txt for the next step to work.
The script needs a folder of test images. We will create a folder named test_images and upload some samples.
For this demonstration, I'll download two sample images. When you run this on your own, you can use the files.upload() command from Step 3 to upload your own test images into this folder.
Python
# Create a directory for test images
!mkdir -p test_images
# Download a few demo images into the folder
# (In your real project, you would upload your own test images here)
!wget -q -O test_images/demo_apple_healthy.jpg "https://storage.googleapis.com/plantdata-test/demo_apple_healthy.jpg"
!wget -q -O test_images/demo_tomato_virus.jpg "https://storage.googleapis.com/plantdata-test/demo_tomato_virus.jpg"
print("Demo test images are ready in the 'test_images' folder:")
!ls test_images
This is the final Python script, adapted for Colab. It follows your description:
Imports cv2, glob, and Classifier from cvzone.
Imports cv2_imshow for displaying images in Colab.
Initializes the classifier with your model files.
Sets the path to the test_images folder.
Uses glob to find all images in the folder.
Loops through each image, running classifier.getPrediction().
Displays the image with the predicted label.
Python
import cv2
import glob
import os
from cvzone.ClassificationModule import Classifier
from google.colab.patches import cv2_imshow # Use cv2_imshow for Colab
print("Starting prediction script...")
# 1. Initialize the Classifier
# This loads your Keras model and labels
try:
classifier = Classifier('Keras model.H5', 'labels.txt')
print("Classifier loaded successfully.")
except Exception as e:
print(f"Error loading classifier: {e}")
print("Please ensure 'Keras model.H5' and 'labels.txt' exist in the environment.")
# 2. Define the path to your test images
# (This matches the folder we created in the previous step)
test_folder_path = 'test_images'
# 3. Use glob to get a list of all image files in the folder
# We use '*.*' to get .jpg, .png, etc.
image_files = glob.glob(f'{test_folder_path}/*.*')
print(f"Found {len(image_files)} images in '{test_folder_path}'.")
# 4. Loop through each image and get a prediction
for img_path in image_files:
try:
# Read the image
img = cv2.imread(img_path)
if img is None:
print(f"Could not read image: {img_path}")
continue
# Get the prediction
# The getPrediction function returns the prediction and the index
prediction, index = classifier.getPrediction(img)
# Get the human-readable label from the labels list
label = classifier.labels[index]
# 5. Display the result
print(f"\nFile: {os.path.basename(img_path)}")
print(f"Prediction: {label}")
# Draw the label on the image
cv2.putText(img, label, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Show the image in the Colab output
cv2_imshow(img)
print("-" * 30)
except Exception as e:
print(f"Error processing {img_path}: {e}")
print("Prediction script finished.")