使用Keras+Tkinter進行深度學習瑕疵檢測GUI應用程式開發(Google Colab)
Industrial Desktop Deep Learning Application with Keras and Tkinter
10 min readJul 18, 2020
參考資料:
Colab連結
取得資料集
本次範例的資料來自於Kaggle上,可透過該文章學習如何直接在Colab上下載資料
https://www.kaggle.com/ravirajsinh45/real-life-industrial-dataset-of-casting-product/download
串連Colab和Google Drive
from google.colab import drivedrive.mount('/content/drive',force_remount=True)#此時會跳出需要授權,請透過連結網址得到授權碼
訓練並下載模型
採用了VGG16來訓練鑄件瑕疵檢測模型
請根據自己dataset的路徑位置作路徑修改,並且把完成訓練後的模型下載到本地當中,要與下個步驟的GUI程式搭配
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout, Flatten
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
input_shape = (300, 300, 3)
# Initialising the CNN
model = Sequential([
Conv2D(64, (3, 3), input_shape=input_shape, padding='valid',activation='relu'),
Conv2D(64, (3, 3), activation='relu', padding='same'),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(128, (3, 3), activation='relu', padding='same'),
Conv2D(128, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(256, (3, 3), activation='relu', padding='same',),
Conv2D(256, (3, 3), activation='relu', padding='same',),
Conv2D(256, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
Conv2D(512, (3, 3), activation='relu', padding='same',),
MaxPooling2D(pool_size=(2, 2), strides=(2, 2)),
Flatten(),
Dense(4096, activation='relu'),
Dropout(0.5),
Dense(4096, activation='relu'),
Dropout(0.5),
Dense(1000, activation='softmax'),])
# Compiling the CNN
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('/content/drive/My Drive/defect_detection_training/casting_data/casting_data/train', target_size = (300, 300), batch_size = 32, class_mode = 'binary')
test_set = test_datagen.flow_from_directory('/content/drive/My Drive/defect_detection_training/casting_data/casting_data/test', target_size = (300, 300),batch_size = 32,class_mode = 'binary')
model = classifier.fit_generator(training_set,
steps_per_epoch = 1000,
epochs = 5,
validation_data = test_set, validation_steps = 1000)
classifier.save("vggmodel.h5")
print("Saved model to disk")
將Model整合到GUI程式
程式碼參考自murali
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 10:31:19 2020@author: murali
"""
from tkinter import *
from keras.preprocessing import image
import numpy as np
from keras.models import load_model
# loading Python Imaging Library
from PIL import ImageTk, Image
# To get the dialog box to open when required
from tkinter import filedialogmodel = load_model('vggmodel.h5')
print('Model Loaded Sucessfully')
def open_img():
# Select the Imagename from a folder
x = openfilename()
# opens the image
img = Image.open(x)
im1 = img.save("casting.jpeg")
img = ImageTk.PhotoImage(img)
# create a label
panel = Label(root, image = img)
# set the image as img
panel.image = img
panel.place(bordermode=OUTSIDE, x=50, y=50)
def openfilename():
# open file dialog box to select image
# The dialogue box has a title "Open"
filename = filedialog.askopenfilename(title ='Select Image')
return filenamedef prediction():
img ="casting.jpeg"
test_image = image.load_img(img, target_size = (300, 300))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = model.predict(test_image)
if result[0][0] == 1:
prediction = 'CASTING IS OK '
else:
prediction = 'CASTING IS DEFECTIVE'
result = Label(root, text = prediction)
# set the image as img
result.place(bordermode=OUTSIDE, x=400, y=120)# Create a window
root = Tk()
# Set Title as Image Loader
root.title("CASTING INSPECTOR")
# Set the resolution of window
root.geometry("700x450")
# Do't Allow Window to be resizable
root.resizable(width = False, height = False)
# Create a button and place it into the window using place layout
btn_open_image = Button(root, text ='Open image', command = open_img).place(
x = 10, y= 400)
btn_predict = Button(root, text ='Predict', command = prediction).place(
x = 200, y= 400)
result_hd = Label(root, text = "RESULT")
result_hd.place(bordermode=OUTSIDE, x=400, y=90)
root.mainloop()