Image Classification with TensorFlow: Predicting Flowers from Photos

 

🌼 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.

python
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.

python
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.

python
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.

python
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

from tensorflow.keras.preprocessing import image
import numpy as np
import tensorflow as tf
import os
from tensorflow.keras.models import load_model
import matplotlib.pyplot as plt
file_path = os.path.join(os.path.dirname(__file__), '', 'download.jpg')


img = image.load_img(file_path, target_size=(180, 180))  # Resize to match training
img_array = image.img_to_array(img)
img_array = img_array / 255.0  # Normalize pixel values
img_array = np.expand_dims(img_array, axis=0)


model = load_model('imageRecongnize.h5')

predictions = model.predict(img_array)
predicted_class = np.argmax(predictions)
class_names = ['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']
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}")

plt.imshow(img)
plt.title(f"Prediction: {class_names[predicted_class]} ({confidence:.2f})")
plt.axis('off')
plt.show()



ImageRecognizeTraining.py

import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing import image
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
data_dir = data_dir / "flower_photos"
if not os.path.exists(data_dir):
    raise FileNotFoundError(f"Dataset directory not found at: {data_dir}")
image_count = len(list(data_dir.glob('*/*.jpg')))
print(f"Total images found: {image_count}")
if image_count == 0:
    print("Warning: No images found. Check your dataset path and format.")
    all_files = list(data_dir.glob('*/*'))
    print(f"Found files (first 5): {[str(f) for f in all_files[:5]]}")
train_ds = tf.keras.utils.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=(180, 180),
    batch_size=32)
val_ds = tf.keras.utils.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="validation",
    seed=123,
    image_size=(180,180),
    batch_size=32)
class_names = train_ds.class_names


num_classes = len(class_names)
model = Sequential([
    layers.Rescaling(1./255, input_shape=(180,180, 3)),
    layers.Conv2D(16, 3, padding='same', activation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(32, 3, padding='same', activation='relu'),
    layers.MaxPooling2D(),
    layers.Conv2D(64, 3, padding='same', activation='relu'),
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(num_classes)
])
model.compile(optimizer='adam',
            loss=tf.keras.losses.SparseCategoricalCrossentropy(
                from_logits=True),
            metrics=['accuracy'])
model.summary()
epochs=10
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)

# saving the model
model.save("imageRecongnize.h5", history)

Comments