Skip to main content

Featured Post

Personal Portfolio Website | HTML | CSS | JavaScript

General Portfolio Details:      A personal portfolio website is an online platform where individuals showcase their skills, experiences, projects, and accomplishments. It serves as a digital resume and a creative outlet, allowing you to present yourself professionally to potential clients, employers, or collaborators. Here's a breakdown of what a personal portfolio website typically includes: 1.  Introduction/About Me:  A brief yet engaging introduction that highlights your expertise, passion, and professional background. It sets the tone for visitors to understand who you are and what you do. 2.  Portfolio/Projects:  Showcase your best work prominently. This could include case studies, descriptions, images, or videos of projects you've completed. Highlighting diverse skills and accomplishments can demonstrate your versatility. 3.  Services/Skills:  A section detailing the services you offer or the skills you possess. Use this area to elaborate on your expertise and what sets y

Leaf Disease Detection | Python | OpenCV




Steps:

1. Image Acquisition: Obtain images of plant leaves using cameras or smartphones. Ensure the images are clear and properly oriented for accurate analysis.

2. Preprocessing:
   - Image Cleaning: Use OpenCV to clean up the images by removing noise, adjusting brightness/contrast, and enhancing the overall quality.
   - **Image Segmentation**: Employ techniques such as thresholding or edge detection to separate the leaf from the background, ensuring the focus is solely on the leaf area.

3. Feature Extraction:
   - Utilize OpenCV to extract relevant features from the preprocessed images, such as texture, color, and shape characteristics.
   - Optionally, apply SciPy for additional feature extraction techniques like statistical analysis or frequency domain transformations.

4. Model Training:
   - Prepare a dataset consisting of labeled images of healthy and diseased leaves.
   - Use TensorFlow and Keras to design and train a convolutional neural network (CNN) architecture suitable for leaf disease classification.
   - Split the dataset into training, validation, and testing sets to evaluate the model's performance accurately.
   - Train the model on the training set, adjusting hyperparameters as needed to optimize performance.

5. Model Evaluation:
   - Assess the trained model's performance using the validation set, evaluating metrics such as accuracy, precision, recall, and F1-score.
   - Fine-tune the model based on validation results to improve its accuracy and generalization capabilities.

6. Deployment:
   - Once satisfied with the model's performance, deploy it for real-time or batch processing of leaf images.
   - Integrate the trained model into a user-friendly application or system, allowing farmers or users to upload leaf images and receive disease diagnosis promptly.

7. Monitoring and Maintenance:
   - Continuously monitor the system's performance and collect feedback to identify areas for improvement.
   - Periodically retrain the model with new data to adapt to evolving disease patterns and maintain optimal accuracy.

Description:

In our Leaf Disease Detection project, we leverage a powerful combination of OpenCV, TensorFlow, Keras, and SciPy to develop an intelligent and robust system. OpenCV facilitates image processing and manipulation, enabling us to extract meaningful features from leaf images. TensorFlow and Keras are employed for the implementation of deep learning models, allowing us to train and deploy neural networks that excel at recognizing patterns associated with various leaf diseases. Additionally, SciPy is utilized for scientific computing tasks, enhancing the overall efficiency and accuracy of our disease detection algorithms. This integration of cutting-edge technologies ensures a comprehensive solution for early detection and classification of plant diseases, empowering farmers with timely insights to protect their crops.


Suggestion:

Use Python 3.7 and install the imported packages then run the program.


Source Code Link:

https://github.com/vsmidhun21/Leaf-Disease-Detection


model_check.py



import os
import mahotas as mt
import cv2 as cv
import glob
import numpy as np
import csv
import re
import count_train
import count_test
from PIL import ImageTk, Image
import matplotlib.pyplot as plt
from scipy import stats
import pickle
import tkinter as tk
from tkinter import filedialog
import sklearn

def extract_feature(image):
	
	##Color Feature
	(mean,std) = cv.meanStdDev(image)
	
	#print(len(mean), type(mean))
	
	#print(len(std), type(std))
	
	color_feature = np.array(mean)
	
	color_feature = np.concatenate([color_feature,std]).flatten()
	
	#print(len(color_feature))
	
	##Texture Feature
	gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
	
	textures = mt.features.haralick(gray)
	
	ht_mean = textures.mean(axis = 0)
	
	#print(len(ht_mean), type(ht_mean))
	
	
	## Shape Features
	ret,thresh = cv.threshold(gray,127,255,0)
	
	contours, hierarchy =   cv.findContours(thresh.copy(),1,2)
	
	cnt = contours[0]
	
	area = cv.contourArea(cnt)
	#print(type(area))
	
	perimeter = cv.arcLength(cnt,True)
	#print(type(perimeter))
	
	shape = np.array([])
	shape = np.append(shape,area)
	shape = np.append(shape,perimeter)
	#print(len(shape))
	
	
	#print(len(ht_mean) + len(std) + len(mean) + len(shape))
	
	ht_mean = np.concatenate([ht_mean,color_feature]).flatten()
	
	ht_mean = np.concatenate([ht_mean,shape]).flatten()
	
	#print(len(ht_mean),ht_mean.shape)
	
	return(ht_mean)


def recommendation_by_prediction(pic, model_svc,model_dtree,model_random,model_ada,min_element,max_element):
    
    ### Image Processing
    print(pic)
    pic = cv.imread(pic)
    dim = (512,512)
    r_img = cv.resize(pic,dim)
    
    ### Extract image features
    feature_list = extract_feature(pic).tolist()
    siz = len(feature_list)
    
    l1 = list(min_element)
    l2 = list(max_element)  
    
    l1.pop(5)
    l2.pop(6)
    
    l1.pop(5)
    l2.pop(6)
    
    # Scaling of relevent feature and removal of irrelevent features
    j=0
    for i in range(siz):
        if(i == 2 or i == 6 or i == 8 or i == 11 or i == 12 or i == 19 or i == 20):
            pass
        else:
            feature_list[i] = (feature_list[i] - l1[j]) /(l2[j] - l1[j])    
            j = j + 1
    
    feature_list.pop(2)
    feature_list.pop(5)
    feature_list.pop(6)
    feature_list.pop(8)
    feature_list.pop(8)
    feature_list.pop(14)
    feature_list.pop(14)
    
    feature_list = [feature_list]
        
    ### Individual prediction result from each model
    pred_1 =  model_svc.predict(feature_list)
    pred_2 =  model_dtree.predict(feature_list)
    pred_3 =  model_random.predict(feature_list)
    pred_4 =  model_ada.predict(feature_list)
    
    
    ### Final class of the leaf
    final = np.array([])
    final = np.append(final,stats.mode([pred_1,pred_2,pred_3,pred_4]))
    final = final.tolist()
    #print(len(final))
    disease_label = {0:'Healthy Leaf',1:'Algal Leaf Spot',2:'Blister Blight',3:'Grey Spot'}
    #final = final[0:len(prediction)-1:2]
    
    return(disease_label[int(final[0])])

f = open('list_val.txt','r')
x = f.readlines()
f.close()

min_string = x[0]
max_string = x[1]

min_list = min_string.split(' ')
max_list = max_string.split(' ')

min_list = list(map(float,min_list[:-1]))
max_list = list(map(float,max_list[:-1]))
print()
print(" Min_list: ", min_list)
print()
print(" Max_list: ", max_list)

model_svc = pickle.load(open('final_svm.sav','rb'))
model_dtree = pickle.load(open('final_dtree.sav','rb'))
model_random = pickle.load(open('final_random.sav','rb'))
model_ada = pickle.load(open('final_ada.sav','rb'))


root = tk.Tk()
file_path = filedialog.askopenfilename()


typo = recommendation_by_prediction(file_path,model_svc,model_dtree,model_random,model_ada,min_list,max_list)

img = ImageTk.PhotoImage(Image.open(file_path))
w1 = tk.Label(root, justify=tk.CENTER, width = 400, height = 400, image = img).pack(side="top")
explanation = "Tea Leaf Class: " + typo
w2 = tk.Label(root, justify=tk.CENTER, padx=10,fg = "Red", bg = "light green", text=explanation, font = "Helvetica 16 bold italic").pack(side="bottom")
root.mainloop()

Final Output Video:



Regards

Coder21


Comments

Popular Post