前言
這個專案的話我也是偶然在B站看到一個阿婆主(SvePana)在講解這個,跟著他的視頻敲的代碼并學習起來的,并寫在自己這里做個筆記也為大家提供代碼哈哈哈哈,
一、Keras?
1.Keras簡介
Keras是由純python撰寫的基于theano/tensorflow的深度學習框架, Keras是一個高層神經網路API,支持快速實驗,能夠把你的idea迅速轉換為結果,如果有如下需求,可以優先選擇Keras,
2.為什么
目前Keras已經被TensorFlow收錄,添加到TensorFlow 中,成為其默認的框架,成為TensorFlow官方的高級API,Keras簡易和快速的原型設計(keras具有高度模塊化,極簡,和可擴充特性),用戶友好:Keras是為人類而不是天頂星人設計的API,用戶的使用體驗始終是我們考慮的首要和中心內容,Keras遵循減少認知困難的最佳實踐:Keras提供一致而簡潔的API, 能夠極大減少一般應用下用戶的作業量,同時,Keras提供清晰和具有實踐意義的bug反饋,
二、全連接神經網路實作
1.思路
匯入資料-------> 選擇模型------>設計神經網路------->編譯------->訓練權重引數------->預測
2.實作代碼
定義函式 train() 實作(匯入資料———>訓練權重引數),
定義函式 text() 實作 預測及輸出結果,
匯入資料:mnist = tf.keras.datasets.mnist #匯入mnist
選擇模型:model = tf.keras.models.Sequential()
有兩種型別的模型,序貫模型(Sequential)和函式式模型(Model),函式式模型應用更為廣泛,序貫模型是函式式模型的一種特殊情況,
序貫模型(Sequential) :單輸入單輸出,一條路通到底,層與層之間只有相鄰關系,沒有跨層連接,這種模型編譯速度快,操作也比較簡單;
設計神經網路:
tf.keras.layers.Flatten(input_shape=(28,28)),
tf.keras.layers.Dense(512,activation='relu'),
tf.keras.layers.Dense(128,activation='relu'),
tf.keras.layers.Dense(10,activation='softmax',kernel_regularizer=tf.keras.regularizers.l2())
編譯:
model.compile(optimizer = 優化器,
loss = 損失函式,
metrics = ["準確率”]')
訓練權重引數:
history = model.fit(x_train,y_train,batch_size=每次訓練圖片數量,epochs=訓練次數,
validation_data=(x_test,y_test),validation_freq=1,callbacks=[cp_callback])
model.summary()
train函式全部代碼
def train():
mnist = tf.keras.datasets.mnist #匯入mnist
(x_train,y_train),(x_test,y_test) = mnist.load_data() #分割
x_train,x_test =x_train/255.0, x_test/255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28,28)),
tf.keras.layers.Dense(512,activation='relu'),
tf.keras.layers.Dense(128,activation='relu'),
tf.keras.layers.Dense(10,activation='softmax',kernel_regularizer=tf.keras.regularizers.l2())])
model.compile(optimizer= 'adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])#評價指標 categorical_accuracy和 sparse_categorical_accuracy
#注意修改路徑
checkpoint_save_path="C:/Users/VULCAN/sxti/TEST/Disconnect_detection/mnist.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
print('------load the model--------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)#斷點續訓
history = model.fit(x_train,y_train,batch_size=25,epochs=30,validation_data=(x_test,y_test),validation_freq=1,callbacks=[cp_callback])
model.summary()
#以下為列印訓練準確率及損失率等
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
f = Figure(figsize=(6,6),dpi=60)
a = f.add_subplot(1,2,1)
a.plot(acc,label = 'Training Accuracy')
a.plot(val_acc,label = 'Validation Accuracy')#驗證精度
a.legend()
b = f.add_subplot(1,2,2)
b.plot(loss,label = 'Training Loss')
b.plot(val_loss,label = 'Validation Loss')
b.legend()
canvas = FigureCanvasTkAgg(f,master=root)
canvas.draw()
canvas.get_tk_widget().place(x=60,y=100)
test函式全部代碼
#預測結果列印
def text():
#注意修改路徑與函式train上面保存的路徑一致
model_save_path = "C:/Users/VULCAN/sxti/TEST/Disconnect_detection/mnist.ckpt"
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28,28)),
tf.keras.layers.Dense(512,activation='relu'),
tf.keras.layers.Dense(128,activation='relu'),
tf.keras.layers.Dense(10,activation='softmax',kernel_regularizer=tf.keras.regularizers.l2())])
model.load_weights(model_save_path)
for i in range(1):
img = Image.open("tem2.png")
#強制壓縮為28,28
img = img.resize((28,28),Image.ANTIALIAS)
#將原有影像轉換為灰度圖
img_arr = np.array(img.convert("L"))
#圖片反相
for i in range(28):
for j in range(28):
if img_arr[i][j]<100:
img_arr[i][j]=255
else:
img_arr[i][j]= 0
img_arr = img_arr/255.0
x_predict = img_arr[tf.newaxis,...]
result = model.predict(x_predict)
pred = np.argmax(result , axis = 1)
#在GUI界面顯示結果
e4 = l = tk.Label(root,text = pred, bg="white",font=("Arial,12"),width=8)
e4.place(x=990,y=440)
三、GUI設計
這部分我直接附上代碼并在代碼中作必要的注釋,
全部所需的庫函式:
#使用Tkinter前需要先匯入
import tkinter as tk
#匯入對話框模塊
import tkinter.filedialog
#創建畫布需要的庫
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
#創建工具列需要的庫
from matplotlib.backends.backend_tkagg import NavigationToolbar2Tk
#快捷鍵需要的模塊2
from matplotlib.backend_bases import key_press_handler
#匯入繪圖需要的模塊
from matplotlib.figure import Figure
import cv2
import tensorflow as tf
import os
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image,ImageTk
其他關于圖片檔案的匯入及攝像頭呼叫的函式定義代碼:
#調取攝像頭并拍攝圖片
def buttonl():
capture = cv2.VideoCapture(0) #cv2模塊調取攝像頭
while(capture.isOpened()):
ret,frame = capture.read() #ret表示捕獲是否成功
frame = frame[:,80:560] #拍照默認為640*480
cv2.imwrite("tem1.png",frame)
dig_Gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
ref2,dig_Gray = cv2.threshold(dig_Gray,100,255,cv2.THRESH_BINARY)
cv2.imwrite("tem2.png",dig_Gray)
break
global photo1,photo2
#將圖片顯示到界面上
img1 = Image.open("tem1.png")
img1 = img1.resize((128,128))
photo1 = ImageTk.PhotoImage(img1)
l1 = tk.Label(root,bg="red",image = photo1).place(x=950,y=100)
img2 = Image.open("tem2.png")
img2 = img2.resize((128,128))
photo2 = ImageTk.PhotoImage(img2)
l2 = tk.Label(root,bg="red",image = photo2).place(x=950,y=250)
#保存當前攝像頭畫面
def frame():
capture = cv2.VideoCapture(0)
#控制元件定義
while(capture.isOpened()):
ref,frame = capture.read()
frame = frame[:,80:560]
cvimage = cv2.cvtColor(frame,cv2.COLOR_BGR2RGBA)
pilImage = Image.fromarray(cvimage)
pilImage = pilImage.resize((360,360),Image.ANTIALIAS)
tkImage = ImageTk.PhotoImage(image = pilImage)
canvas.create_image(0,0,anchor = "nw",image = tkImage)
root.update()
root.after(10)
#選擇檔案
def select_pic():
file_path = tk.filedialog.askopenfilename(title="選擇檔案",initialdir = (os.path.expanduser(r"")))
image = Image.open(file_path)
image.save("tem1.png")
gray = image.convert("L")
gray.save("tem2.png")
global photo3,photo4
#將圖片顯示在界面上
img3 = Image.open("tem1.png")
img3 = image.resize((128,128))
photo3 = ImageTk.PhotoImage(img3)
l3 = tk.Label(root,bg="red",image = photo3).place(x=950,y=100)
img4 = Image.open("tem2.png")
img4 = img4.resize((128,128))
photo4 = ImageTk.PhotoImage(img4)
l4 = tk.Label(root,bg="red",image = photo4).place(x=950,y=250)
主函式部分:
if __name__ =='__main__':
root = tk.Tk()
#第二步,給視窗的可視化起名字
root.title('手寫體數字識別')
#第三步,設定視窗的大小(長*寬)
root.geometry('1176x520') #這里的乘是小x
root.configure(bg = "#C0C0C0")
f = Figure(figsize=(6,6), dpi=60)
a=f.add_subplot(1,2,1) #添加子圖:1行1列第一個
a.plot(0,0)
b=f.add_subplot(1,2,2) #添加子圖,1行1列第二個
b.plot(0,0)
#將繪制的圖形顯示到tkinter:創建屬于root的canvas畫布,并將圖f置于畫布上
canvas=FigureCanvasTkAgg(f,master=root)
canvas.draw()#注意show方法已經過時,改用draw
canvas.get_tk_widget().place(x=60,y=100)
b1 = tk.Button(root,text='訓練',bg='white',font=('Arial',12),width=12,height=1,command=train).place(x=168,y=35)
b2 = tk.Button(root,text='拍照',bg='white',font=('Arial',12),width=12,height=1,command=frame).place(x=550,y=35)
b3 = tk.Button(root,text='測驗',bg='white',font=('Arial',12),width=12,height=1,command=text).place(x=960,y=35)
b4 = tk.Button(root,text='匯入圖片',bg='white',font=('Arial',12),width=12,height=1,command=select_pic).place(x=680,y=35)
b5 = tk.Button(root,text='識別結果',font=('Arial',12),bg='white',command=text).place(x=990,y=400)
canvas=tk.Canvas(root,bg="white",width=360,height=360) #繪制畫布
#控制元件位置設定
canvas.place(x=500,y=100)
b6=tk.Button(root,text="保存",bg="white",width=15,height=2,command=buttonl).place(x=620,y=420)
#第六步,主視窗回圈顯示
root.mainloop()
最后附上界面

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/340634.html
標籤:AI
