import os
import cv2
import numpy as np
import matplotlib
matplotlib.use('TkAgg') # Use a GUI backend for matplotlib
import matplotlib.backends.backend_agg as agg
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
# Config
IMG_SIZE = 100
DATASET_PATH = "corn_dataset" # Folder containing subfolders: 'blight', 'rust',
etc.
# Load Dataset
print("[INFO] Loading images...")
images = []
labels = []
classes = os.listdir(DATASET_PATH)
print(f"[INFO] Classes found: {classes}")
for label in classes:
folder = os.path.join(DATASET_PATH, label)
for file in os.listdir(folder):
path = os.path.join(folder, file)
img = cv2.imread(path)
if img is not None:
img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
flat = gray.flatten() / 255.0
images.append(flat)
labels.append(label)
images = np.array(images)
labels = np.array(labels)
print(f"[INFO] Loaded {len(images)} images.")
# Train Model
X_train, X_test, y_train, y_test = train_test_split(images, labels, test_size=0.2,
random_state=42)
knn = KNeighborsClassifier(n_neighbors=3)
print("[INFO] Training model...")
knn.fit(X_train, y_train)
print("[INFO] Model trained.")
# Evaluate
print("\n[INFO] Evaluating model:")
y_pred = knn.predict(X_test)
print(classification_report(y_test, y_pred))
# Predict Single Image
def predict_image(image_path):
try:
if not os.path.exists(image_path):
raise FileNotFoundError(f"Image not found: {image_path}")
img = cv2.imread(image_path)
if img is None:
raise ValueError("Image is unreadable or corrupted.")
img_resized = cv2.resize(img, (IMG_SIZE, IMG_SIZE))
gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY)
flat = gray.flatten() / 255.0
prediction = knn.predict([flat])[0]
# Display the image and prediction
try:
plt.figure()
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title(f"Predicted: {prediction}")
plt.axis("off")
plt.show()
except Exception as e:
print(f"[WARNING] GUI backend failed, saving image instead: {e}")
output_path = "prediction_output.png"
plt.savefig(output_path)
print(f"[INFO] Prediction saved to: {output_path}")
print(f"[RESULT] The image is predicted as: {prediction}")
except Exception as e:
print(f"[ERROR] Couldn't predict image: {e}")