把网络模型单独拎出来了,方便解耦。下一步准备把重要的配置全部拎出来。
This commit is contained in:
@@ -13,66 +13,14 @@ from typing import List, Optional, Tuple
|
||||
from tkinterdnd2 import DND_FILES, TkinterDnD
|
||||
import threading
|
||||
import time
|
||||
from net import create_food_cnn
|
||||
|
||||
# 设置customtkinter的外观
|
||||
ctk.set_appearance_mode("System")
|
||||
ctk.set_default_color_theme("blue")
|
||||
|
||||
# 定义CNN模型(与训练代码中的结构相同)
|
||||
class FoodCNN(nn.Module):
|
||||
def __init__(self):
|
||||
super(FoodCNN, self).__init__()
|
||||
# 第一个卷积块
|
||||
self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
|
||||
self.conv2 = nn.Conv2d(32, 32, 3, padding=1)
|
||||
self.pool1 = nn.MaxPool2d(2, 2)
|
||||
self.dropout1 = nn.Dropout2d(0.25)
|
||||
|
||||
# 第二个卷积块
|
||||
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
|
||||
self.conv4 = nn.Conv2d(64, 64, 3, padding=1)
|
||||
self.pool2 = nn.MaxPool2d(2, 2)
|
||||
self.dropout2 = nn.Dropout2d(0.25)
|
||||
|
||||
# 第三个卷积块
|
||||
self.conv5 = nn.Conv2d(64, 128, 3, padding=1)
|
||||
self.conv6 = nn.Conv2d(128, 128, 3, padding=1)
|
||||
self.pool3 = nn.MaxPool2d(2, 2)
|
||||
self.dropout3 = nn.Dropout2d(0.25)
|
||||
|
||||
# 全连接层
|
||||
self.fc1 = nn.Linear(128 * 4 * 4, 512)
|
||||
self.dropout4 = nn.Dropout(0.5)
|
||||
self.fc2 = nn.Linear(512, 2) # 2分类
|
||||
|
||||
def forward(self, x):
|
||||
# 第一个卷积块
|
||||
x = F.relu(self.conv1(x))
|
||||
x = F.relu(self.conv2(x))
|
||||
x = self.pool1(x)
|
||||
x = self.dropout1(x)
|
||||
|
||||
# 第二个卷积块
|
||||
x = F.relu(self.conv3(x))
|
||||
x = F.relu(self.conv4(x))
|
||||
x = self.pool2(x)
|
||||
x = self.dropout2(x)
|
||||
|
||||
# 第三个卷积块
|
||||
x = F.relu(self.conv5(x))
|
||||
x = F.relu(self.conv6(x))
|
||||
x = self.pool3(x)
|
||||
x = self.dropout3(x)
|
||||
|
||||
# 展平
|
||||
x = x.view(-1, 128 * 4 * 4)
|
||||
|
||||
# 全连接层
|
||||
x = F.relu(self.fc1(x))
|
||||
x = self.dropout4(x)
|
||||
x = self.fc2(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
|
||||
class FoodClassifierApp:
|
||||
def __init__(self, root):
|
||||
@@ -81,7 +29,7 @@ class FoodClassifierApp:
|
||||
self.root.geometry("1400x800")
|
||||
|
||||
# 食物类别(根据您的数据集)
|
||||
self.food_classes = ["回锅肉", "西红柿鸡蛋"]
|
||||
self.food_classes = ["回锅肉", "西红柿鸡蛋","麻辣小面"]
|
||||
|
||||
# 设备设置
|
||||
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
@@ -106,10 +54,10 @@ class FoodClassifierApp:
|
||||
def load_model(self):
|
||||
"""加载训练好的PyTorch模型"""
|
||||
try:
|
||||
model_path = "../model/01/best_food_model.pth"
|
||||
model_path = "../model/02/best_food_model.pth"
|
||||
if os.path.exists(model_path):
|
||||
# 创建模型实例
|
||||
self.model = FoodCNN()
|
||||
self.model = create_food_cnn()
|
||||
# 加载模型权重
|
||||
self.model.load_state_dict(torch.load(model_path, map_location=self.device))
|
||||
self.model.to(self.device)
|
||||
|
||||
Reference in New Issue
Block a user