實戰七:手把手教你用Tensorflow進行驗證碼識別(下)
目錄
- 準備模型開發環境
- 生成驗證碼數據集
- 輸入與輸出數據處理
- 模型結構設計
- 模型損失函數設計
- 模型訓練過程分析
- 模型部署與效果演示
七、模型部署與效果演示
1.數據-模型-服務流水線
2.啓動一個flask服務
將下述代碼另存爲hello.py,然後本地python hello.py運行
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
訪問127.0.0.1:5000,便可看到結果
3.部署驗證碼識別服務
將下述代碼另外存app.py,啓動flask來加載app.py文件
import base64
import numpy as np
import tensorflow as tf
from io import BytesIO
from flask import Flask, request, jsonify
from keras.models import load_model
from PIL import Image
NUMBER = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
LOWERCASE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
UPPERCASE = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
CAPTCHA_CHARSET = NUMBER # 驗證碼字符集
CAPTCHA_LEN = 4 # 驗證碼長度
CAPTCHA_HEIGHT = 60 # 驗證碼高度
CAPTCHA_WIDTH = 160 # 驗證碼寬度
# 10 個 Epochs 訓練的模型
MODEL_FILE = './pre-trained/model/captcha_rmsprop_binary_crossentropy_bs_100_epochs_10.h5'
def vec2text(vector):
if not isinstance(vector, np.ndarray):
vector = np.asarray(vector)
vector = np.reshape(vector, [CAPTCHA_LEN, -1])
text = ''
for item in vector:
text += CAPTCHA_CHARSET[np.argmax(item)]
return text
def rgb2gray(img):
# Y' = 0.299 R + 0.587 G + 0.114 B
# https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
return np.dot(img[...,:3], [0.299, 0.587, 0.114])
app = Flask(__name__) # 創建 Flask 實例
# 測試 URL
@app.route('/ping', methods=['GET', 'POST'])
def hello_world():
return 'pong'
# 驗證碼識別 URL
@app.route('/predict', methods=['POST'])
def predict():
response = {'success': False, 'prediction': '', 'debug': 'error'}
received_image= False
if request.method == 'POST':
if request.files.get('image'): # 圖像文件
image = request.files['image'].read()
received_image = True
response['debug'] = 'get image'
elif request.get_json(): # base64 編碼的圖像文件
encoded_image = request.get_json()['image']
image = base64.b64decode(encoded_image)
received_image = True
response['debug'] = 'get json'
if received_image:
image = np.array(Image.open(BytesIO(image)))
image = rgb2gray(image).reshape(1, 60, 160, 1).astype('float32') / 255
with graph.as_default():
pred = model.predict(image)
response['prediction'] = response['prediction'] + vec2text(pred)
response['success'] = True
response['debug'] = 'predicted'
else:
response['debug'] = 'No Post'
return jsonify(response)
model = load_model(MODEL_FILE) # 加載模型
graph = tf.get_default_graph() # 獲取 TensorFlow 默認數據流圖
if __name__ == "__main__":
app.run()
3.使用Flask啓動驗證碼識別服務
a.啓動flask服務
b.打開遊覽器訪問測試URL(http://localhost:5000/ping)
c.訪問驗證碼識別服務
利用curl進行圖像上傳
curl -X POST -F [email protected] "http://localhost:5000/predict"
另開cmd終端,運行上述命令
可以看出圖片真實值爲0044,預測結果爲0244