Python Central HubSign in

Python Projects / Advanced

Deep Learning Image Classifier

A Python application for image classification using deep learning, featuring data preprocessing, model training, and evaluation.

Abstract

Deep Learning Image Classifier is a Python project that uses deep learning to classify images. The application features data preprocessing, model training, and evaluation, demonstrating best practices in computer vision and AI.

Prerequisites

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of deep learning and computer vision
  • Required libraries: tensorflow, keras, numpy, matplotlib

Before you Start

Install Python and the required libraries:

Shell
pip install tensorflow keras numpy matplotlib

Getting Started

Create a Project

  1. Create a folder named deep-learning-image-classifier.
  2. Open the folder in your code editor or IDE.
  3. Create a file named deep_learning_image_classifier.py.
  4. Copy the code below into your file.

Write the Code

Deep Learning Image ClassifierSource
Deep Learning Image Classifier
"""
Deep Learning Image Classifier

Features:
- Image classification using deep learning
- Training and prediction modules
- Modular design
- CLI interface
- Error handling
"""
import sys
import os
import numpy as np
try:
    import tensorflow as tf
    from tensorflow.keras import layers, models
except ImportError:
    tf = None
    layers = None
    models = None

class ImageClassifier:
    def __init__(self, input_shape=(64,64,3), num_classes=2):
        self.model = models.Sequential([
            layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
            layers.MaxPooling2D(2,2),
            layers.Conv2D(64, (3,3), activation='relu'),
            layers.MaxPooling2D(2,2),
            layers.Flatten(),
            layers.Dense(128, activation='relu'),
            layers.Dense(num_classes, activation='softmax')
        ]) if models else None
        if self.model:
            self.model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
    def train(self, train_dir, epochs=5):
        if self.model:
            datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
            train_data = datagen.flow_from_directory(train_dir, target_size=(64,64), batch_size=32, class_mode='categorical')
            self.model.fit(train_data, epochs=epochs)
            self.model.save('image_classifier.h5')
    def predict(self, img_path):
        if self.model:
            img = tf.keras.preprocessing.image.load_img(img_path, target_size=(64,64))
            x = tf.keras.preprocessing.image.img_to_array(img)/255.0
            x = np.expand_dims(x, axis=0)
            preds = self.model.predict(x)
            return np.argmax(preds)
        return None

class CLI:
    @staticmethod
    def run():
        print("Deep Learning Image Classifier")
        while True:
            cmd = input('> ')
            if cmd.startswith('train'):
                parts = cmd.split()
                if len(parts) < 2:
                    print("Usage: train <train_dir>")
                    continue
                clf = ImageClassifier()
                clf.train(parts[1])
            elif cmd.startswith('predict'):
                parts = cmd.split()
                if len(parts) < 2:
                    print("Usage: predict <img_path>")
                    continue
                clf = ImageClassifier()
                clf.model.load_weights('image_classifier.h5')
                label = clf.predict(parts[1])
                print(f"Predicted class: {label}")
            elif cmd == 'exit':
                break
            else:
                print("Unknown command")

if __name__ == "__main__":
    try:
        CLI.run()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

Example Usage

Shell
python deep_learning_image_classifier.py

How it fits together

Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.

diagram Diagram mermaid

Explanation

Key Features

  • Data Preprocessing: Prepares image data for training.
  • Model Training: Trains a deep learning model to classify images.
  • Evaluation: Assesses model performance.
  • Error Handling: Validates inputs and manages exceptions.

Code Breakdown

  1. What it imports (lines 11–13)
Python
import sys
import os
import numpy as np
  1. ImageClassifier — the class (lines 22–48)
Python
class ImageClassifier:
    def __init__(self, input_shape=(64,64,3), num_classes=2):
        self.model = models.Sequential([
            layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
            layers.MaxPooling2D(2,2),
            layers.Conv2D(64, (3,3), activation='relu'),
            layers.MaxPooling2D(2,2),
            layers.Flatten(),
            layers.Dense(128, activation='relu'),
            layers.Dense(num_classes, activation='softmax')
        ]) if models else None
        if self.model:
            self.model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
    def train(self, train_dir, epochs=5):
        if self.model:
            datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
            train_data = datagen.flow_from_directory(train_dir, target_size=(64,64), batch_size=32, class_mode='categorical')
            self.model.fit(train_data, epochs=epochs)
            # ... 3 more lines in the file ...
            img = tf.keras.preprocessing.image.load_img(img_path, target_size=(64,64))
            x = tf.keras.preprocessing.image.img_to_array(img)/255.0
            x = np.expand_dims(x, axis=0)
            preds = self.model.predict(x)
            return np.argmax(preds)
        return None
  1. CLI — the class (lines 50–75)
Python
class CLI:
    @staticmethod
    def run():
        print("Deep Learning Image Classifier")
        while True:
            cmd = input('> ')
            if cmd.startswith('train'):
                parts = cmd.split()
                if len(parts) < 2:
                    print("Usage: train <train_dir>")
                    continue
                clf = ImageClassifier()
                clf.train(parts[1])
            elif cmd.startswith('predict'):
                parts = cmd.split()
                if len(parts) < 2:
                    print("Usage: predict <img_path>")
                    continue
                clf = ImageClassifier()
                clf.model.load_weights('image_classifier.h5')
                label = clf.predict(parts[1])
                print(f"Predicted class: {label}")
            elif cmd == 'exit':
                break
            else:
                print("Unknown command")

The file defines 2 top-level symbols in all; the whole thing is above under Write the Code.

Features

  • Image Classification: Data preprocessing, model training, and evaluation
  • Modular Design: Separate functions for each task
  • Error Handling: Manages invalid inputs and exceptions
  • Production-Ready: Scalable and maintainable code

Next Steps

Enhance the project by:

  • Integrating with real image datasets
  • Supporting advanced deep learning architectures
  • Creating a GUI for classification
  • Adding real-time prediction
  • Unit testing for reliability

Educational Value

This project teaches:

  • Computer Vision: Image classification and deep learning
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Medical Imaging
  • Security Systems
  • AI Platforms

Checkpoint exercise

This exercise practises one convolution, ReLU and max-pool step on a small image, the building block of a CNN.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Conclusion

Deep Learning Image Classifier demonstrates how to build a scalable and accurate image classification tool using Python. With modular design and extensibility, this project can be adapted for real-world applications in AI, healthcare, and more. For more advanced projects, visit Python Central Hub.

Was this page helpful?

Let us know how we did