Users Online

· Guests Online: 36

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Python Project - Image Classification - Deep Learning Project in Python with Keras

Python Project - Image Classification - Deep Learning Project in Python with Keras

Image classification is a fascinating deep learning project. Specifically, image classification comes under the computer vision project category.

In this project, we will build a convolution neural network in Keras with python on a CIFAR-10 dataset. First, we will explore our dataset, and then we will train our neural network using python and Keras.

Image classification project

What is Image Classification

  • The classification problem is to categorize all the pixels of a digital image into one of the defined classes.
  • Image classification is the most critical use case in digital image analysis.
  • Image classification is an application of both supervised classification and unsupervised classification.
    • In supervised classification, we select samples for each target class. We train our neural network on these target class samples and then classify new samples.
    • In unsupervised classification, we group the sample images into clusters of images having similar properties. Then, we classify each cluster into our intended classes.

About Image Classification Dataset

CIFAR-10 is a very popular computer vision dataset. This dataset is well studied in many types of deep learning research for object recognition.

This dataset consists of 60,000 images divided into 10 target classes, with each category containing 6000 images of shape 32*32. This dataset contains images of low resolution (32*32), which allows researchers to try new algorithms. The 10 different classes of this dataset are:

  1. Airplane
  2. Car
  3. Bird
  4. Cat
  5. Deer
  6. Dog
  7. Frog
  8. Horse
  9. Ship
  10. Truck

CIFAR-10 dataset is already available in the datasets module of Keras. We do not need to download it; we can directly import it from keras.datasets.

Project Prerequisites:

The prerequisite to develop and execute image classification project is Keras and Tensorflow installation.

Steps for image classification on CIFAR-10:

1. Load the dataset from keras datasets module

  1. from keras.datasets import cifar10
  2. import matplotlib.pyplot as plt 
  3.  (train_X,train_Y),(test_X,test_Y)=cifar10.load_data()

2. Plot some images from the dataset to visualize the dataset

  1. n=6 
  2. plt.figure(figsize=(20,10)) 
  3. for i in range(n):
  4. plt.subplot(330+1+i) 
  5. plt.imshow(train_X[i]) 
  6. plt.show()

image classification dataset

3. Import the required layers and modules to create our convolution neural net architecture

  1. from keras.models import Sequential
  2. from keras.layers import Dense
  3. from keras.layers import Dropout
  4. from keras.layers import Flatten
  5. from keras.constraints import maxnorm
  6. from keras.optimizers import SGD
  7. from keras.layers.convolutional import Conv2D
  8. from keras.layers.convolutional import MaxPooling2D
  9. from keras.utils import np_utils

4. Convert the pixel values of the dataset to float type and then normalize the dataset

  1. train_x=train_X.astype('float32') 
  2. test_X=test_X.astype('float32')
  3. train_X=train_X/255.0
  4. test_X=test_X/255.0

5. Now perform the one-hot encoding for target classes

  1. train_Y=np_utils.to_categorical(train_Y)
  2. test_Y=np_utils.to_categorical(test_Y)
  3. num_classes=test_Y.shape[1]

6. Create the sequential model and add the layers

  1. model=Sequential()
  2. model.add(Conv2D(32,(3,3),input_shape=(32,32,3),
  3. padding='same',activation='relu',
  4. kernel_constraint=maxnorm(3)))
  5. model.add(Dropout(0.2))
  6. model.add(Conv2D(32,(3,3),activation='relu',padding='same',kernel_constraint=maxnorm(3)))
  7. model.add(MaxPooling2D(pool_size=(2,2)))
  8. model.add(Flatten())
  9. model.add(Dense(512,activation='relu',kernel_constraint=maxnorm(3)))
  10. model.add(Dropout(0.5))
  11. model.add(Dense(num_classes, activation='softmax'))

model architecture

7. Configure the optimizer and compile the model

  1. sgd=SGD(lr=0.01,momentum=0.9,decay=(0.01/25),nesterov=Fals)
  2. model.compile(loss='categorical_crossentropy',
  3. optimizer=sgd,
  4. metrics=['accuracy'])

8. View the model summary for better understanding of model architecture

  1. model.summary()

model summary

9. Train the model

  1. model.fit(train_X,train_Y,
  2. validation_data=(test_X,test_Y),
  3. epochs=10,batch_size=32)

train model

10. Calculate its accuracy on testing data

  1. _,acc=model.evaluate(test_X,test_Y)
  2. print(acc*100)

11. Save the model

  1. model.save("model1_cifar_10epoch.h5")

12. Make a dictionary to map to the output classes and make predictions from the model

  1. results={
  2. 0:'aeroplane',
  3. 1:'automobile',
  4. 2:'bird',
  5. 3:'cat',
  6. 4:'deer',
  7. 5:'dog',
  8. 6:'frog',
  9. 7:'horse',
  10. 8:'ship',
  11. 9:'truck'
  12. }
  13. from PIL import Image
  14. import numpy as np
  15. im=Image.open("__image_path__")
  16. # the input image is required to be in the shape of dataset, i.e (32,32,3)
  17. im=im.resize((32,32))
  18. im=np.expand_dims(im,axis=0)
  19. im=np.array(im)
  20. pred=model.predict_classes([im])[0]
  21. print(pred,results[pred])

model prediction

You can test the result on your custom image input. To improve accuracy, try increasing the epoch count to 25 for training.

Image Classification Project GUI

Here, we will build a graphical user interface for our image classifier. We will build this GUI using Tkinter python library. To install Tkinker:

  1. sudo apt-get install python3-tk

To make the GUI make a new file gui.py and copy our model (“model1_cifar_10epoch.h5”) to this directory.

Now paste the below code into the gui.py file:

  1. import tkinter as tk
  2. from tkinter import filedialog
  3. from tkinter import *
  4. from PIL import ImageTk, Image
  5. import numpy
  6. #load the trained model to classify the images
  7. from keras.models import load_model
  8. model = load_model('model1_cifar_10epoch.h5')
  9. #dictionary to label all the CIFAR-10 dataset classes.
  10. classes = {
  11. 0:'aeroplane',
  12. 1:'automobile',
  13. 2:'bird',
  14. 3:'cat',
  15. 4:'deer',
  16. 5:'dog',
  17. 6:'frog',
  18. 7:'horse',
  19. 8:'ship',
  20. 9:'truck'
  21. }
  22. #initialise GUI
  23. top=tk.Tk()
  24. top.geometry('800x600')
  25. top.title('Image Classification CIFAR10')
  26. top.configure(background='#CDCDCD')
  27. label=Label(top,background='#CDCDCD', font=('arial',15,'bold'))
  28. sign_image = Label(top)
  29. def classify(file_path):
  30. global label_packed
  31. image = Image.open(file_path)
  32. image = image.resize((32,32))
  33. image = numpy.expand_dims(image, axis=0)
  34. image = numpy.array(image)
  35. pred = model.predict_classes([image])[0]
  36. sign = classes[pred]
  37. print(sign)
  38. label.configure(foreground='#011638', text=sign)
  39. def show_classify_button(file_path):
  40. classify_b=Button(top,text="Classify Image",
  41. command=lambda: classify(file_path),padx=10,pady=5)
  42. classify_b.configure(background='#364156', foreground='white',
  43. font=('arial',10,'bold'))
  44. classify_b.place(relx=0.79,rely=0.46)
  45. def upload_image():
  46. try:
  47. file_path=filedialog.askopenfilename()
  48. uploaded=Image.open(file_path)
  49. uploaded.thumbnail(((top.winfo_width()/2.25),
  50. (top.winfo_height()/2.25)))
  51. im=ImageTk.PhotoImage(uploaded)
  52. sign_image.configure(image=im)
  53. sign_image.image=im
  54. label.configure(text='')
  55. show_classify_button(file_path)
  56. except:
  57. pass
  58. upload=Button(top,text="Upload an image",command=upload_image,
  59. padx=10,pady=5)
  60. upload.configure(background='#364156', foreground='white',
  61. font=('arial',10,'bold'))
  62. upload.pack(side=BOTTOM,pady=50)
  63. sign_image.pack(side=BOTTOM,expand=True)
  64. label.pack(side=BOTTOM,expand=True)
  65. heading = Label(top, text="Image Classification CIFAR10",pady=20, font=('arial',20,'bold'))
  66. heading.configure(background='#CDCDCD',foreground='#364156')
  67. heading.pack()
  68. top.mainloop()

Now run the python file gui.py to execute image classification project:

  1. python3 gui.py

Image classification project

Summary:

The objective of the image classification project was to enable the beginners to start working with Keras to solve real-time deep learning problems.

In this keras deep learning Project, we talked about the image classification paradigm for digital image analysis. We discuss supervised and unsupervised image classifications.
Then it explains the CIFAR-10 dataset and its classes. Finally, we saw how to build a convolution neural network for image classification on the CIFAR-10 dataset.


Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.71 seconds
10,820,413 unique visits