🌼 Image Classification with TensorFlow: Predicting Flowers from Photos
Have you ever wondered how machines recognize images? Whether it's identifying flowers, animals, or handwritten digits, image classification is one of the most exciting applications of deep learning. In this post, I’ll walk you through a simple image classification project I built using TensorFlow and Keras.
We’ll load a trained model, preprocess an image, make predictions, and visualize the result—all in just a few lines of Python.
🧠 What This Project Does
Loads a flower image from disk.
Preprocesses it to match the model’s input format.
Uses a trained neural network to predict the flower type.
Displays the image along with the predicted label and confidence score.
🛠️ Tools and Libraries Used
TensorFlow/Keras: For loading the model and making predictions.
Matplotlib: To visualize the image and prediction.
NumPy: For numerical operations.
Keras Preprocessing: For image loading and transformation.
📸 Step 1: Load and Preprocess the Image
We start by loading the image and resizing it to the dimensions expected by the model (180×180 pixels). Then we normalize the pixel values and reshape the array to match the input shape.
from tensorflow.keras.preprocessing import image
import numpy as np
import os
file_path = os.path.join(os.path.dirname(__file__), '', 'download.jpg')
img = image.load_img(file_path, target_size=(180, 180))
img_array = image.img_to_array(img)
img_array = img_array / 255.0 # Normalize
img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
🧠 Step 2: Load the Trained Model
We load a pre-trained model (imageRecongnize.h5
) that was trained to classify five types of flowers.
from tensorflow.keras.models import load_model
model = load_model('imageRecongnize.h5')
🔍 Step 3: Make Predictions
We pass the image to the model and use softmax
to interpret the output as probabilities. The class with the highest score is selected as the prediction.
import tensorflow as tf
class_names = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
predictions = model.predict(img_array)
predicted_class = np.argmax(predictions)
confidence = tf.nn.softmax(predictions[0])[predicted_class].numpy()
for i, score in enumerate(tf.nn.softmax(predictions[0]).numpy()):
print(f"{class_names[i]}: {score:.2f}")
print(f"Predicted class: {class_names[predicted_class]}")
print(f"Confidence: {confidence:.2f}")
🎨 Step 4: Visualize the Result
Finally, we display the image using Matplotlib and annotate it with the predicted label and confidence score.
import matplotlib.pyplot as plt
plt.imshow(img)
plt.title(f"Prediction: {class_names[predicted_class]} ({confidence:.2f})")
plt.axis('off')
plt.show()
✅ Final Thoughts
This project is a great example of how deep learning can be applied to real-world tasks like image recognition. You can easily extend it by:
Training your own model on custom images.
Deploying it as a web app using Flask or Streamlit.
Adding support for more classes or higher-resolution images.
Thanks for reading! If you enjoyed this post or have questions about building your own image classifier, feel free to reach out or leave a comment.
testRecongize.py
ImageRecognizeTraining.py
Comments
Post a Comment