基于pytorch水果图像识别系统,数据集使用Fruits 360,并将训练好的模型应用到图片识别界面中,具体代码实现
时间: 2024-06-09 12:07:39 浏览: 199
好的,这里给出一个基于 PyTorch 的水果图像识别系统的代码实现,包含数据集的下载、数据预处理、模型训练和应用到图片识别界面中。代码中使用的数据集为 Fruits 360,模型为 ResNet18。
### 1. 下载数据集
```python
!wget https://github.com/Horea94/Fruit-Images-Dataset/archive/master.zip -O fruits.zip
!unzip fruits.zip
```
### 2. 数据预处理
```python
import os
from PIL import Image
from torchvision import transforms
data_dir = './Fruit-Images-Dataset-master/Training'
classes = os.listdir(data_dir)
num_classes = len(classes)
class FruitDataset(Dataset):
def __init__(self, data_dir, classes, transform=None):
self.data_dir = data_dir
self.classes = classes
self.transform = transform
self.images = []
self.labels = []
for i, cls in enumerate(classes):
cls_dir = os.path.join(data_dir, cls)
for img_name in os.listdir(cls_dir):
img_path = os.path.join(cls_dir, img_name)
self.images.append(img_path)
self.labels.append(i)
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
img_path = self.images[idx]
label = self.labels[idx]
img = Image.open(img_path)
if self.transform:
img = self.transform(img)
return img, label
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
train_dataset = FruitDataset(data_dir, classes, transform)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=4)
```
### 3. 模型训练
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.models import resnet18
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = resnet18(pretrained=True)
model.fc = nn.Linear(512, num_classes)
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
num_epochs = 10
for epoch in range(num_epochs):
running_loss = 0.0
for i, (inputs, labels) in enumerate(train_loader):
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
print('Finished Training')
```
### 4. 应用到图片识别界面中
```python
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
model.eval()
img_path = './Fruit-Images-Dataset-master/Test/Apple Braeburn/26_100.jpg'
img = Image.open(img_path)
img = transform(img).unsqueeze(0)
img = img.to(device)
with torch.no_grad():
outputs = model(img)
_, predicted = torch.max(outputs.data, 1)
plt.imshow(np.array(Image.open(img_path)))
plt.title(classes[predicted.item()])
plt.show()
```
以上就是一个基于 PyTorch 的水果图像识别系统的完整代码实现。注意,由于该数据集的类别较多,所以模型训练需要较长时间,可以根据自己的需求适当调整训练时的参数。
阅读全文