The Wayback Machine - https://web.archive.org/web/20241007131224/https://www.geeksforgeeks.org/flower-recognition-using-convolutional-neural-network/
Open In App

Flower Recognition Using Convolutional Neural Network

Last Updated : 24 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will use Convolutional Neural Network to solve a Supervised Image 

Classification problem of recognizing the flower types – rose, chamomile, dandelion, sunflower, & tulip. Understanding the concept of a Convolutional Neural Network refers to this.

Once, understand the concept of CNN we can start with the project.

Steps to be followed 

The steps followed in this article are listed here :

  1. Importing modules
  2. Importing Dataset 
  3. Image Data Generator
  4. Model Development 
  5. Model Evaluation and Prediction

Importing modules

  • Pandas – This library helps to load the data frame in a 2D array format.
  • Numpy – Numpy arrays are very fast and can perform large computations.
  • Matplotlib – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.
  • OpenCV – This library focuses on image processing and handling.
  • Tensorflow – It has a range of functions to achieve complex functionalities with single lines of code.

Python3




import numpy as np 
import pandas as pd
import cv2
import matplotlib.pyplot as plt
from PIL import Image
from tensorflow.keras import layers
from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense
from tensorflow.keras.optimizers import Adam
import tensorflow as tf
import os


Importing Dataset and Preprocessing

You can download the dataset from the link.

Once download the data, image resize is needed to be done. To specify the size of the image use below code. 

Python3




base_dir = '/flowers/'
  
img_size = 224
batch = 64


Image Data Generator

For image data generator, follow the code given below.

Python3




# Create a data augmentor
train_datagen = ImageDataGenerator(rescale=1. / 255, shear_range=0.2, 
                                   zoom_range=0.2, horizontal_flip=True,
                                   validation_split=0.2)
  
test_datagen = ImageDataGenerator(rescale=1. / 255,
                                  validation_split=0.2)
  
# Create datasets
train_datagen = train_datagen.flow_from_directory(base_dir,
                                                  target_size=(
                                                      img_size, img_size),
                                                  subset='training',
                                                  batch_size=batch)
test_datagen = test_datagen.flow_from_directory(base_dir,
                                                target_size=(
                                                    img_size, img_size),
                                                subset='validation',
                                                batch_size=batch)


Output : 

Found 3121 images belonging to 5 classes.
Found 776 images belonging to 5 classes.

Model Development 

From here we will use the we creating CNN model with the help of tensorflow library as it contains all the functionalities that one may need to define the architecture of a Convolutional Neural Network and train it on the data.

Python3




# # modelling starts using a CNN.
  
model = Sequential()
model.add(Conv2D(filters=64, kernel_size=(5, 5), padding='same',
                 activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
  
  
model.add(Conv2D(filters=64, kernel_size=(3, 3),
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  
  
model.add(Conv2D(filters=64, kernel_size=(3, 3),
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  
model.add(Conv2D(filters=64, kernel_size=(3, 3),
                 padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
  
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dense(5, activation="softmax"))


Summary of the model

Python3




model.summary()


Output : 

Model Summary

 

Python3




keras.utils.plot_model(
    model,
    show_shapes = True,
    show_dtype = True,
    show_layer_activations = True
)


Output:

Mdoel Structure

 

Compiling 

Python3




model.compile(optimizer=tf.keras.optimizers.Adam(),
              loss='categorical_crossentropy', metrics=['accuracy'])


Fitting

Model Fitting will take some time.

Python3




epochs=30
model.fit(train_datagen,epochs=epochs,validation_data=test_datagen)


Output:

Model Fitting

 

Saving and Loading model

For more information regarding saving and loading models refer this. 

Python3




from tensorflow.keras.models import load_model
model.save('Model.h5')
   
# load model
savedModel=load_model('Model.h5')


Once you saved the model, you can use it anytime without training again and again.

Model Evaluation and Prediction

Evaluation includes the hyperparameter tuning if the model is not giving good results. You can also play with different parameters for better predictions.

Python3




train_datagen.class_indices


Output :

 {'daisy': 0, 'dandelion': 1, 'rose': 2, 'sunflower': 3, 'tulip': 4}

Python3




from keras.preprocessing import image
  
#Creating list for mapping
list_ = ['Daisy','Danelion','Rose','sunflower', 'tulip']
  
#Input image
test_image = image.load_img('img.jpg',target_size=(224,224))
  
#For show image
plt.imshow(test_image)
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
  
# Result array
result = savedModel.predict(test_image)
print(result)
  
#Mapping result array with the main name list
i=0
for i in range(len(result[0])):
  if(result[0][i]==1):
    print(list_[i])
    break


Output:

Output1

 

Python3




#Input image
test_image = image.load_img('img2.jpg',target_size=(224,224))
  
#For show image
plt.imshow(test_image)
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
  
# Result array
result = savedModel.predict(test_image)
print(result)
  
#Mapping result array with the main name list
i=0
for i in range(len(result[0])):
  if(result[0][i]==1):
    print(list_[i])
    break


Output:

Output2

 

Conclusion

We can improve the results by using Transfer Learning like Resnet50.



Previous Article
Next Article

Similar Reads

Lung Cancer Detection using Convolutional Neural Network (CNN)
Computer Vision is one of the applications of deep neural networks that enables us to automate tasks that earlier required years of expertise and one such use in predicting the presence of cancerous cells. In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify normal lung tissues from c
8 min read
Building a Convolutional Neural Network using PyTorch
Building a Convolutional Neural Network (CNN) using PyTorch involves several steps, including defining the architecture of the network, preparing the data, training the model, and evaluating its performance. In this article, we will see how we can build a CNN network in PyTorch. Table of Content What are Convolutional Neural Networks?Code Implement
8 min read
Cat & Dog Classification using Convolutional Neural Network in Python
Image Classification is one of the most interesting and useful applications of Deep neural networks and Convolutional Neural Networks that enables us to automate the task of assembling similar images and arranging data without the supervision of real humans. Cat & Dog Classification using Convolutional Neural Network in PythonIn this article, w
5 min read
Importance of Convolutional Neural Network | ML
Convolutional Neural Network as the name suggests is a neural network that makes use of convolution operation to classify and predict. Let's analyze the use cases and advantages of a convolutional neural network over a simple deep learning network. Weight sharing: It makes use of Local Spatial coherence that provides same weights to some of the edg
2 min read
Deep parametric Continuous Convolutional Neural Network
Deep Parametric Continuous Kernel convolution was proposed by researchers at Uber Advanced Technologies Group. The motivation behind this paper is that the simple CNN architecture assumes a grid-like architecture and uses discrete convolution as its fundamental block. This inhibits their ability to perform accurate convolution to many real-world ap
6 min read
Convolutional Neural Network (CNN) Architectures
Convolutional Neural Network(CNN) is a neural network architecture in Deep Learning, used to recognize the pattern from structured arrays. However, over many years, CNN architectures have evolved. Many variants of the fundamental CNN Architecture This been developed, leading to amazing advances in the growing deep-learning field. Let's discuss, How
11 min read
Training of Convolutional Neural Network (CNN) in TensorFlow
In this article, we are going to implement and train a convolutional neural network CNN using TensorFlow a massive machine learning library. Now in this article, we are going to work on a dataset called 'rock_paper_sissors' where we need to simply classify the hand signs as rock paper or scissors. Stepwise ImplementationStep 1: Importing the librar
5 min read
Working of Convolutional Neural Network (CNN) in Tensorflow
In this article, we are going to see the working of convolution neural networks with TensorFlow a powerful machine learning library to create neural networks. Now to know, how a convolution neural network lets break it into parts. the 3 most important parts of this convolution neural networks are, ConvolutionPoolingFlattening These 3 actions are th
5 min read
Convolutional Neural Network (CNN) in Tensorflow
It is assumed that the reader knows the concepts of Neural Networks and Convolutional Neural Networks. If you are sure about the topics please refer to Neural Networks and Convolutional Neural Networks. Building Blocks of CNN: Convolutional Neural Networks are mainly made up of three types of layers: Convolutional Layer: It is the main building blo
4 min read
How to Define a Simple Convolutional Neural Network in PyTorch?
In this article, we are going to see how to Define a Simple Convolutional Neural Network in PyTorch using Python. Convolutional Neural Networks(CNN) is a type of Deep Learning algorithm which is highly instrumental in learning patterns and features in images. CNN has a unique trait which is its ability to process data with a grid-like topology wher
5 min read
Convolutional Neural Network (CNN) in Machine Learning
Convolutional Neural Networks (CNNs) are a powerful tool for machine learning, especially in tasks related to computer vision. Convolutional Neural Networks, or CNNs, are a specialized class of neural networks designed to effectively process grid-like data, such as images. In this article, we are going to discuss convolutional neural networks (CNN)
13 min read
Kernels (Filters) in convolutional neural network
Convolutional Neural Networks (CNNs) are a category of neural networks designed specifically for processing structured arrays of data such as images. Essential to the functionality of CNNs are components known as kernels or filters. These are small, square matrices that perform convolution operations on the input data, facilitating the extraction o
8 min read
Video Classification with a 3D Convolutional Neural Network
Video classification is a highly important technology for analyzing digital content. It finds applications in various industries, such as security surveillance, media entertainment, and automotive safety. Central to this technology are 3D Convolutional Neural Networks (CNNs), which significantly enhance the accuracy and efficiency of video classifi
15+ min read
Applying Convolutional Neural Network on mnist dataset
CNN is a model known to be a Convolutional Neural Network and in recent times it has gained a lot of popularity because of its usefulness. CNN uses multilayer perceptrons to do computational work. CNN uses relatively little pre-processing compared to other image classification algorithms. This means the network learns through filters that in tradit
6 min read
Project Idea | (Dynamic Hand Gesture Recognition using neural network)
Introduction Hand gesture recognition system is used for interfacing between computer and human using hand gesture. We wish to make a windows-based application for live motion gesture recognition using webcam input in C++. This project is a combination of live motion detection and gesture identification. This application uses the webcam to detect g
3 min read
Handwritten Digit Recognition using Neural Network
Introduction:Handwritten digit recognition using MNIST dataset is a major project made with the help of Neural Network. It basically detects the scanned images of handwritten digits. We have taken this a step further where our handwritten digit recognition system not only detects scanned images of handwritten digits but also allows writing digits o
9 min read
Convolutional Block for Image Recognition
INTRODUCTION: The basic neural network design i.e. an input layer, few dense layers, and an output layer does not work well for the image recognition system because objects can appear in lots of different places in an image. So the solution is to add one or more convolutional layers. A convolutional block is a building block used in a convolutional
5 min read
Emotion Detection Using Convolutional Neural Networks (CNNs)
Emotion detection, also known as facial emotion recognition, is a fascinating field within the realm of artificial intelligence and computer vision. It involves the identification and interpretation of human emotions from facial expressions. Accurate emotion detection has numerous practical applications, including human-computer interaction, custom
15+ min read
Depth wise Separable Convolutional Neural Networks
Convolution is a very important mathematical operation in artificial neural networks(ANN's). Convolutional neural networks (CNN's) can be used to learn features as well as classify data with the help of image frames. There are many types of CNN's. One class of CNN's are depth wise separable convolutional neural networks. These type of CNN's are wid
4 min read
ML | Transfer Learning with Convolutional Neural Networks
Transfer learning as a general term refers to reusing the knowledge learned from one task for another. Specifically for convolutional neural networks (CNNs), many image features are common to a variety of datasets (e.g. lines, edges are seen in almost every image). It is for this reason that, especially for large structures, CNNs are very rarely tr
7 min read
Convolutional Neural Networks (CNN) for Sentence Classification
Sentence classification is the task of automatically assigning categories to sentences based on their content. This has broad applications like identifying spam emails, classifying customer feedback, or determining the topic of a news article. Convolutional Neural Networks (CNNs) have proven remarkably successful for this task. In this article, we
5 min read
How do convolutional neural networks (CNNs) work?
Convolutional Neural Networks (CNNs) have transformed computer vision by allowing machines to achieve unprecedented accuracy in tasks like image classification, object detection, and segmentation. CNNs, which originated with Yann LeCun's work in the late 1980s, are inspired by the human visual system and process visual data using a hierarchical str
7 min read
Convolutional Neural Networks (CNNs) in R
Convolutional Neural Networks (CNNs) are a specialized type of neural network designed to process and analyze visual data. They are particularly effective for tasks involving image recognition and classification due to their ability to automatically and adaptively learn spatial hierarchies of features. CNN Architecture ComponentsHere are the main C
11 min read
Math Behind Convolutional Neural Networks
Convolutional Neural Networks (CNNs) are designed to process data that has a known grid-like topology, such as images (which can be seen as 2D grids of pixels). The key components of a CNN include convolutional layers, pooling layers, activation functions, and fully connected layers. Each of these components relies on specific mathematical operatio
8 min read
Backpropagation in Convolutional Neural Networks
Convolutional Neural Networks (CNNs) have become the backbone of many modern image processing systems. Their ability to learn hierarchical representations of visual data makes them exceptionally powerful. A critical component of training CNNs is backpropagation, the algorithm used for effectively updating the network's weights. This article delves
4 min read
Convolutional Neural Networks with Microsoft Cognitive Toolkit (CNTK)
Convolutional Neural Networks (CNNs) are a type of neural network commonly used for image and video identification tasks. They excel at recognizing patterns such as edges, textures, and objects in images, making them ideal for tasks involving computer vision. CNNs leverage convolutional layers to analyze spatial structures in data, enhancing their
6 min read
Vision Transformers vs. Convolutional Neural Networks (CNNs)
In recent years, the landscape of computer vision has evolved significantly with the introduction of Vision Transformers (ViTs), which challenge the dominance of traditional Convolutional Neural Networks (CNNs). While CNNs have been the backbone of many state-of-the-art image classification models, Vision Transformers have garnered attention for th
5 min read
What is the difference between a region-based CNN (R-CNN) and a fully convolutional network (FCN)?
In computer vision, particularly in object detection and semantic segmentation, two prominent neural network architectures are frequently discussed: Region-based Convolutional Neural Networks (R-CNN) and Fully Convolutional Networks (FCN). Each of these architectures has distinct features and applications. This article will explore the differences
4 min read
Difference Between Feed-Forward Neural Networks and Recurrent Neural Networks
Pre-requisites: Artificial Neural Networks and its Applications Neural networks are artificial systems that were inspired by biological neural networks. These systems learn to perform tasks by being exposed to various datasets and examples without any task-specific rules. In this article, we will see the difference between Feed-Forward Neural Netwo
2 min read
Visualize the Flower Dataset using Tensorflow - Python
The Tensorflow flower dataset is a large dataset that consists of flower images. In this article, we are going to learn how we can visualize the flower dataset in python. For the purposes of this article, we will use tensorflow_datasets and Matplotlib library. Prerequisites If you don't have any of the libraries mentioned below, you can install the
2 min read