AI & Computer VisionEngineer

Plant Disease Classifier with a TensorFlow Lite Model

Point the camera at a leaf and an image-classification model tells you if it looks healthy or shows signs of a common disease.

LevelEngineer
Time3 h
Est. cost~$147
Steps5

Image classifiers learn from thousands of labeled photos. You train a small model on a public leaf-disease dataset on your computer or in a free notebook, export it as a .tflite file, and the Pi runs it locally with LiteRT in a fraction of a second.

Mission steps

  1. Train a model

    Train an image classifier on a public dataset such as PlantVillage (or your own labeled leaf photos) and export it to TensorFlow Lite with a labels.txt file.

  2. Install the runtime

    In a venv created with --system-site-packages, run pip install ai-edge-litert numpy.

  3. Copy the files

    Put plant_model.tflite and labels.txt next to the script on the Pi.

  4. Classify a leaf

    Fill the frame with one leaf on a plain background in daylight and run the script.

  5. Check the result

    Treat low-confidence answers as 'unknown' and confirm any disease with a local extension service.

Code

import numpy as np
from picamera2 import Picamera2
from ai_edge_litert.interpreter import Interpreter

labels = [l.strip() for l in open('labels.txt')]
interp = Interpreter(model_path='plant_model.tflite')
interp.allocate_tensors()
inp, out = interp.get_input_details()[0], interp.get_output_details()[0]
h, w = inp['shape'][1:3]

cam = Picamera2()
cam.configure(cam.create_still_configuration(main={'size': (int(w), int(h)), 'format': 'RGB888'}))
cam.start()
img = cam.capture_array()[..., ::-1]               # BGR -> RGB

x = np.expand_dims(img, 0)
if inp['dtype'] == np.float32:
    x = x.astype(np.float32) / 127.5 - 1.0         # match how your model was trained
else:
    x = x.astype(inp['dtype'])
interp.set_tensor(inp['index'], x)
interp.invoke()
scores = interp.get_tensor(out['index'])[0].astype(float)
best = int(np.argmax(scores))
print(f"{labels[best]}  ({scores[best] / scores.sum():.0%})")

Tip: test every script on the bench before installing it in a moving machine.

Questions

It works on dataset photos but not on my plants.

Lab photos have plain backgrounds and even light. Add 50–100 photos of your own plants per class and retrain — that usually fixes it.