DEV Community

Olaoyo Michael
Olaoyo Michael

Posted on

Flower Recognition with Python

The edge and color properties of flower photos are used in flower recognition to categorize flowers. I'll introduce you to a Python machine learning project that focuses on flower detection in this article.

What is Flower Recognition?

The planet is home to numerous flower species. Some species, like roses, have a variety of hues. The names and details of every flower are tough to recall. Additionally, people could mistakenly identify similar floral species.
For instance, although having similar names and flower forms, white champaka and champak have different colors and petal lengths.

Currently, the only way to identify any specific flower or flower species is to search for information based on one's own knowledge and professional experience. The availability of such expertise may provide a challenge in this investigation.
Today, the only real options for finding such content online are keyword searches and word processors. The problem is that even then, the searcher would still need to come up with suitably relevant keywords, which they are unable to do.

This post will demonstrate how to use Python to recognize flowers using machine learning.

Machine Learning Project on Flower Recognition with Python

4242 flower photos make up the dataset I'm utilizing for this job of flower recognition. Data is gathered using photos from Yandex, Google, and Flickr. This data collection can be used to identify the flowers in the image.

Five categories—chamomile, tulip, rose, sunflower, and dandelion—are used to categorize the photographs. There are around 800 images for each class. The images have a resolution of just 320 x 240 pixels, which is not very great. Photos have varying proportions and are not scaled down to one size.
Let's import the required Python libraries now to begin the Python work of flower recognition: Download Dataset

import os
import cv2
import numpy as np

#Encoding and Split data into Train/Test Sets
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split

#Tensorflow Keras CNN Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Activation, Conv2D, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam,SGD,Adagrad,Adadelta,RMSprop

#Plot Images
import matplotlib.pyplot as plt


folder_dir = 'dataset path' # Choose your path
Enter fullscreen mode Exit fullscreen mode

Now the next step is to read each image in the data and create a label for each with the name of the folder:

data = []
label = []

SIZE = 128 #Crop the image to 128x128

for folder in os.listdir(folder_dir):
    for file in os.listdir(os.path.join(folder_dir, folder)):
        if file.endswith("jpg"):
            label.append(folder)
            img = cv2.imread(os.path.join(folder_dir, folder, 
                                                            file))
            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            im = cv2.resize(img_rgb, (SIZE,SIZE))
            data.append(im)
        else:
            continue
Enter fullscreen mode Exit fullscreen mode

Now let’s convert the data into numerical values:

data_arr = np.array(data)
label_arr = np.array(label)
Enter fullscreen mode Exit fullscreen mode

Now let’s use the Label encoder and normalize the data:

encoder = LabelEncoder()
y = encoder.fit_transform(label_arr)
y = to_categorical(y,5)
X = data_arr/255
Enter fullscreen mode Exit fullscreen mode

The next step is to split the dataset into 80% training and 20% test sets:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=10)
Enter fullscreen mode Exit fullscreen mode

Now let’s build a neural network model for the task of Flower Recognition:

model = Sequential()
model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same',activation ='relu', input_shape = (SIZE,SIZE,3)))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same',activation ='relu'))
model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same',activation ='relu'))
model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = 'Same',activation ='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(5, activation = "softmax"))
Enter fullscreen mode Exit fullscreen mode

Before compiling the model we need to create more training images to prevent overfitting:

datagen = ImageDataGenerator(
        rotation_range=20,
        zoom_range = 0.20,
        width_shift_range=0.3,
        height_shift_range=0.3,
        horizontal_flip=True,
        vertical_flip=True)

datagen.fit(X_train)
Enter fullscreen mode Exit fullscreen mode

Now let’s compile the neural network model:

model.compile(optimizer=Adam(lr=0.0001),loss='categorical_crossentropy',metrics=['accuracy'])
batch_size=32
epochs=64
history = model.fit_generator(datagen.flow(X_train,y_train, batch_size=batch_size),
                              epochs = epochs,
                              validation_data = (X_test,y_test),
                              verbose = 1)
Enter fullscreen mode Exit fullscreen mode

Now let’s let the model if it recognize flowers properly:

categories = np.sort(os.listdir(folder_dir))
fig, ax = plt.subplots(6,6, figsize=(25, 40))

for i in range(6):
    for j in range(6):
        k = int(np.random.random_sample() * len(X_test))
        if(categories[np.argmax(y_test[k])] == categories[np.argmax(model.predict(X_test)[k])]):
            ax[i,j].set_title("TRUE: " + categories[np.argmax(y_test[k])], color='green')
            ax[i,j].set_xlabel("PREDICTED: " + categories[np.argmax(model.predict(X_test)[k])], color='green')
            ax[i,j].imshow(np.array(X_test)[k].reshape(SIZE, SIZE, 3), cmap='gray')
        else:
            ax[i,j].set_title("TRUE: " + categories[np.argmax(y_test[k])], color='red')
            ax[i,j].set_xlabel("PREDICTED: " + categories[np.argmax(model.predict(X_test)[k])], color='red')
            ax[i,j].imshow(np.array(X_test)[k].reshape(SIZE, SIZE, 3), cmap='gray')
Enter fullscreen mode Exit fullscreen mode

Image description

I hope you liked this article on Machine Learning Project on Flower Recognition with Python programming language. Check out the full code and results on my GitHub account

Top comments (0)