India is a rapidly developing country; nearly 60% of its population is dependent on the Farming sector/ agriculture sector. As per the reports, there is a huge gap between technology used in the farming industry and the manufacturing industry. There is no technical support in traditional framing systems to detect crop disease associated with a particular genre of the crop; the rise of disease to crops decreases the farm’s overall productivity and is more frequent in the agriculture sector, which is why farmers are not interested in increasing their productivity nowadays.
Crop disease impacts the growth of the respective species; early detection of the disease is critical. Therefore, crop disease affects global food security, but it also harms small-scale farmers. The most prominent benefit of this Crop disease detection system is it can be monitored by detecting as soon they appeared on the crops. Additionally, it is possible to provide an effective solution to this problem.
These are some kinds of issues that need farmers to take preventative measures to increase their productivity. The advantages of Artificial Intelligence have made it possible to identify plant disease directly from raw images.
Many machine learning models have been used to address this kind of problem, but with the help of recent developments in deep learning, a subset of machine learning has shown its capability in image-oriented tasks. By leveraging Deep learning, OpenCV we can build a custom crop detection system based on our needs.
In this article, we will discuss one of the efforts taken to classify the disease on the cassava plant using the transfer learning method. This model is trained on the leaf image of the cassava plant, detecting whether it is healthy or has one of the four diseases usually seen on those plants. The dataset consists of 9430 labeled images, which are further split into a training set of 5656 images, a test set of 1885 images, and a validation set of 1889 images.
Without much further reading, let’s quickly check the code implementation. The following code implementation is in reference to the official implementation.
Code Implementation of CropNet
Import all dependencies:
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_hub as hub
Load the Cassavas dataset:
Be careful if you are running this code to the local machine; the dataset is weighed around 1.5GB.
dataset, info = tfds.load('cassava', with_info=True)
You can also check the information of the dataset, as I mentioned earlier, by running the info.
You can also use your dataset for the modeling to leverage the following code; for more detail on supported formats, check this link.
data_root_dir = tf.keras.utils.get_file( 'cassavaleafdata.zip', 'https://storage.googleapis.com/emcassavadata/cassavaleafdata.zip', extract=True) data_root_dir = os.path.splitext(data_root_dir)# Remove the .zip extension builder = tfds.ImageFolder(data_root_dir) info = builder.info train = builder.as_dataset(split='train', as_supervised=True) validation = builder.as_dataset(split='validation', as_supervised=True) test = builder.as_dataset(split='test', as_supervised=True)
The dataset has four distinct disease classes; we can make the model predict the six classes, namely those four diseases additional as unknown, to make the model robust if exposed to some different crops. It should return unknown, and the sixth class is healthy.
# Extend the cassava dataset classes with 'unknown' class_names = info.features['label'].names + ['unknown'] # Map the class names to human readable names name_map = dict( cmd='Mosaic Disease', cbb='Bacterial Blight', cgm='Green Mite', cbsd='Brown Streak Disease', healthy='Healthy', unknown='Unknown') print(len(class_names), 'classes:') print(class_names) print([name_map[name] for name in class_names])
6 classes: ['cbb', 'cbsd', 'cgm', 'cmd', 'healthy', 'unknown'] ['Bacterial Blight', 'Brown Streak Disease', 'Green Mite', 'Mosaic Disease', 'Healthy', 'Unknown']
We need to preprocess our data as a model except for the 224 * 224 images with three-channel format normalize between 0 to 1.
def preprocess_fn(data): image = data['image'] # Normalize [0, 255] to [0, 1] image = tf.cast(image, tf.float32) image = image / 255. # Resize the images to 224 x 224 image = tf.image.resize(image, (224, 224)) data['image'] = image return data
We are using the custom helper function to help see the images before prediction and after the prediction.
def plot(examples, predictions=None): # Get the images, labels, and optionally predictions images = examples['image'] labels = examples['label'] batch_size = len(images) if predictions is None: predictions = batch_size * [None] # Configure the layout of the grid x = np.ceil(np.sqrt(batch_size)) y = np.ceil(batch_size / x) fig = plt.figure(figsize=(x * 6, y * 7)) for i, (image, label, prediction) in enumerate(zip(images, labels, predictions)): # Render the image ax = fig.add_subplot(x, y, i+1) ax.imshow(image, aspect='auto') ax.grid(False) ax.set_xticks() ax.set_yticks() # Display the label and optionally prediction x_label = 'Label: ' + name_map[class_names[label]] if prediction is not None: x_label = 'Prediction: ' + name_map[class_names[prediction]] + '\n' + x_label ax.xaxis.label.set_color('green' if label == prediction else 'red') ax.set_xlabel(x_label) plt.show()
Check out few images.
batch = dataset['validation'].map(preprocess_fn).batch(25).as_numpy_iterator() examples = next(batch) plot(examples)
Load the pre train model from Tensorflow Hub for the prediction and check the prediction against above-shown samples-
classifier = hub.KerasLayer('https://tfhub.dev/google/cropnet/classifier/cassava_disease_V1/2') probabilities = classifier(examples['image']) predictions = tf.argmax(probabilities, axis=-1) plot(examples, predictions)
From this article, we have seen how we can leverage the transfer learning method to address problems related to agricultural fields that are dominant in various crops. With the help of Transfer Learning, we reduce the training time, and the most concerning metrics are also improved, i.e accuracy. Moreover, with such minimal code, we can expand this to any application and be directly applied to the android platform.