| import torch
|
| import torch.nn as nn
|
| import torchvision.transforms as transforms
|
| from PIL import Image
|
| import cv2
|
| import os
|
|
|
|
|
| class LeNet5(nn.Module):
|
| def __init__(self):
|
| super(LeNet5, self).__init__()
|
| self.conv1 = nn.Conv2d(1, 6, kernel_size=5, stride=1, padding=2)
|
| self.relu = nn.ReLU()
|
| self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
|
| self.conv2 = nn.Conv2d(6, 16, kernel_size=5, stride=1)
|
| self.fc1 = nn.Linear(16 * 5 * 5, 120)
|
| self.fc2 = nn.Linear(120, 84)
|
| self.fc3 = nn.Linear(84, 10)
|
|
|
| def forward(self, x):
|
| x = self.pool(self.relu(self.conv1(x)))
|
| x = self.pool(self.relu(self.conv2(x)))
|
| x = x.view(-1, 16 * 5 * 5)
|
| x = self.relu(self.fc1(x))
|
| x = self.relu(self.fc2(x))
|
| x = self.fc3(x)
|
| return x
|
|
|
|
|
| class ImageClassifier:
|
| def __init__(self, model_path):
|
| self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| self.model = LeNet5().to(self.device)
|
| self.model.load_state_dict(torch.load(model_path, map_location=self.device))
|
| self.model.eval()
|
|
|
| self.transform = transforms.Compose([
|
| transforms.Grayscale(num_output_channels=1),
|
| transforms.Resize((28, 28)),
|
| transforms.ToTensor(),
|
| transforms.Normalize((0.5,), (0.5,))
|
| ])
|
|
|
| def preprocess_image(self, image_path):
|
| image = Image.open(image_path).convert("RGB")
|
| image = self.transform(image)
|
| image = image.unsqueeze(0)
|
| return image.to(self.device)
|
|
|
| def predict(self, image_path):
|
| image_tensor = self.preprocess_image(image_path)
|
| with torch.no_grad():
|
| output = self.model(image_tensor)
|
| _, predicted = output.max(1)
|
| return predicted.item(), image_path
|
|
|