rld-v3 / models /rice_leaf_validator.py
zynt31's picture
Upload 15 files
a68b822 verified
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from PIL import Image
class RiceLeafValidator(nn.Module):
"""
CNN model for rice leaf validation using BINARY CLASSIFICATION.
Trained on two classes: rice_leaf (0) and not_rice_leaf (1).
"""
def __init__(self):
super(RiceLeafValidator, self).__init__()
# Convolutional layers
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
# Fully connected layers
self.fc1 = nn.Linear(64 * 28 * 28, 128)
self.fc2 = nn.Linear(128, 2) # 2 classes: rice_leaf and not_rice_leaf
self.dropout = nn.Dropout(0.5)
def forward(self, x):
# Convolutional layers with pooling
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
# Flatten and fully connected layers
x = x.view(-1, 64 * 28 * 28)
x = F.relu(self.fc1(x))
x = self.dropout(x)
x = self.fc2(x)
return x
# Preprocessing pipeline
data_transforms = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def is_rice_leaf(image_path, model, device, threshold=0.5):
"""
Determines if an image contains a rice leaf using BINARY classification.
Args:
image_path: Path to the image file
model: Trained binary RiceLeafValidator model
device: torch device (cpu or cuda)
threshold: Probability threshold for rice_leaf class (default: 0.5)
Returns:
(is_rice_leaf, confidence): Tuple of boolean result and confidence score (0-1)
"""
model.eval()
image = Image.open(image_path).convert('RGB')
image_tensor = data_transforms(image).unsqueeze(0).to(device)
with torch.no_grad():
outputs = model(image_tensor)
probabilities = F.softmax(outputs, dim=1)
rice_leaf_prob = probabilities[0][0].item() # Probability for rice_leaf class (index 0)
is_rice = rice_leaf_prob >= threshold
return is_rice, rice_leaf_prob