import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import numpy as np
from keras.preprocessing import image as keras_image
from keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.applications import ResNet50
from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
import numpy as np
import matplotlib.pyplot as plt
import glob, os, random
# 创建 Tkinter 窗口
root = tk.Tk()
root.title("化妆品视频系统")
# 设置窗口大小和背景颜色
root.geometry("500x400")
root.configure(bg='white')
# 创建登录函数
def login():
username = username_entry.get()
password = password_entry.get()
# 这里可以添加验证用户名和密码的逻辑,这里简化为输出
print(f"用户名: {username}, 密码: {password}")
# 登录成功后跳转到上传图像页面
show_upload_page()
# 显示上传图像页面
def show_upload_page():
# 清空登录部分的控件
username_label.place_forget()
username_entry.place_forget()
password_label.place_forget()
password_entry.place_forget()
login_button.place_forget()
# 创建上传图像和识别按钮
upload_button.place(x=200, y=300)
classify_button.place(x=300, y=300)
# 创建用于显示图像的 Label
panel.place(x=50, y=50, width=400, height=200)
# 上传图像的函数
def upload_image():
file_path = filedialog.askopenfilename()
img = Image.open(file_path)
img.thumbnail((400, 200)) # 缩小图像以适应界面
img = ImageTk.PhotoImage(img)
panel.config(image=img)
panel.image = img
# 保存图像路径以备识别按钮使用
global uploaded_image_path
uploaded_image_path = file_path
# 识别图像的函数
def classify_image():
if uploaded_image_path:
img = Image.open(uploaded_image_path)
img = img.resize((100, 100),3) # 调整图像大小以符合模型输入要求
img = keras_image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
#--------------------------------------------------------------------
# 统一定义图像像素的宽度和高度
img_width, img_height = 100, 100
# 定义训练集、验证集的图形路径(文件夹路径即可)
train_data_dir = 'augmented/'
validation_data_dir = 'augmented/'
# 模型训练的参数设置
nb_train_samples = 275
nb_validation_samples = 200
epochs = 10 # 迭代次数
batch_size = 64 # 每个批量观测数
# 图像输入维度设置
if K.image_data_format() == 'channels_first':
input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)
from keras.models import load_model
model = Sequential()
#--------------------------------------------------------------------
# 输入层:第一层
# 添加第一个卷积层/最大池化层(必选)
model.add(Conv2D(filters=32, # 32 个过滤器
kernel_size=(3, 3), # 卷积核大小 3 x 3
input_shape=input_shape, # 图像输入维度
activation='relu')) # 'relu' 激活函数
model.add(MaxPooling2D(pool_size=(2, 2))) # 池化核大小 2 x 2
# ----------------------------------------------------
# 隐藏层:介于第一层和最后一层之间
# 添加第二个卷积层/最大池化层(可选)
model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 添加第三个卷积层/最大池化层(可选)
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# 由于卷积层是 2D 空间,训练时需要将数据展平为 1D 空间
model.add(Flatten()) # 添加展平层(必选)
model.add(Dense(units=64, activation='relu')) # 添加全连接层(必选) 64 个神经元
model.add(Dropout(0.5)) # 添加丢弃层,防止过拟合
# ---------------------------------------------------
# 输出层:最后一层,神经元控制输出的维度,并指定分类激活函数
model.add(Dense(units=2, activation='sigmoid')) # 指定分类激活函数
model = load_model('model.h5')
# 使用模型进行预测
predictions = model.predict(img)
# decoded_preds = decode_predictions(preds, top=1)[0] # 获取最高置信度的预测结果
# from keras.preprocessing import image
# model = load_model('model.h5')
# img_path = '测试1.jpg' # img_width, img_height = 100, 100
# img = image.load_img(img_path, target_size=(100, 100)) # 例如,针对VGG模型,resize图像为224x224
# x = image.img_to_array(img)
# x = np.expand_dims(x, axis=0)
# x = preprocess_input(x) # 预处理图像数据,例如针对VGG模型
# # 对测试图像进行预测
# predictions = model.predict(x)
print(predictions.shape)
print('predictions:', predictions)
predictions = predictions[0]
# 指定要列出子文件和子文件夹的目录路径
folder_path = 'augmented' # 替换为你要获取子文件和子文件夹的目录路径
# 获取指定路径下的所有文件和文件夹列表
contents = os.listdir(folder_path)
print('contents', contents)
max_indices = [i for i, value in enumerate(predictions) if value == max(predictions)][0]
print(contents[max_indices])
# 获取分类结果
# label = decoded_preds[0][1]
label=contents[max_indices]
result_text.delete(1.0, tk.END) # 清空文本框
result_text.insert(tk.END, f"类别: {label}")
else:
result_text.delete(1.0, tk.END)
result_text.insert(tk.END, "请先上传图像")
# 创建登录部分
username_label = tk.Label(root, text="用户名:", bg='white')
username_label.place(x=50, y=20)
username_entry = tk.Entry(root)
username_entry.place(x=150, y=20)
password_label = tk.Label(root, text="密码:", bg='white')
password_label.place(x=50, y=50)
password_entry = tk.Entry(root, show="*")
password_entry.place(x=150, y=50)
login_button = tk.Button(root, text="登录", command=login, bg='lightblue', padx=10, pady=5)
login_button.place(x=300, y=35)
# 创建上传图像和识别按钮
upload_button = tk.Button(root, text="上传图像", command=upload_image, bg='lightgreen', padx=10, pady=5)
classify_button = tk.Button(root, text="识别", command=classify_image, bg='lightyellow', padx=10, pady=5)
# 创建用于显示图像的 Label
panel = tk.Label(root, bg='white')
# 创建用于显示分类结果的文本框
result_text = tk.Text(root, height=2, width=30, bg='lightyellow')
result_text.place(x=150, y=350)
# 加载预训练模型(这里以 ResNet50 为例)
model = ResNet50(weights='imagenet')
root.mainloop()