Image Inference Example
What you'll need
Inference code
import json
import os
import numpy as np
from PIL import Image
import tensorflow as tf
# Load the model from Valohai inputs
model = tf.keras.models.load_model("/valohai/inputs/model/model.h5")
def load_image(image_path):
"""Load and preprocess an image for MNIST."""
image_name = os.path.basename(image_path)
image = Image.open(image_path)
image.load()
# Resize to 28x28 and convert to grayscale
image = image.resize((28, 28)).convert("L")
image_data = np.array(image).reshape(1, 28, 28)
image_data = image_data / 255.0 # Normalize
return (image_name, image_data)
def run_inference(image):
"""Run prediction and print as Valohai metadata."""
image_name, image_data = image
prediction = np.argmax(model.predict(image_data))
# Print as Valohai metadata for tracking
print(
json.dumps(
{
"image": image_name,
"inferred_digit": str(prediction),
},
),
)
return {
"image": image_name,
"inferred_digit": str(prediction),
}
# Process all images
results = []
for filename in os.listdir("/tmp/images/"):
filepath = os.path.join("/tmp/images/", filename)
results.append(run_inference(load_image(filepath)))
# Save aggregated results to Valohai outputs
with open("/valohai/outputs/results.json", "w") as f:
json.dump(results, f)Define the step
Run the inference
Check your results
Last updated
Was this helpful?
