在本文中,我們將探討如何使用Python和Flask框架搭建一個基于卷積神經網絡(CNN)的在線手寫中文識別網站。我們將從環境搭建、模型訓練、Flask應用開發到部署的整個過程進行詳細講解。
首先,我們需要準備開發環境。確保你已經安裝了Python 3.x版本,并且安裝了以下必要的庫:
pip install flask tensorflow keras numpy pillow
手寫中文識別需要大量的手寫漢字數據集。常用的數據集有CASIA-HWDB(中科院手寫漢字數據庫)等。你可以從相關網站下載數據集,并將其轉換為適合訓練的格式。
假設我們已經有了一個預處理好的數據集,包含圖像和對應的標簽。
接下來,我們使用Keras構建一個簡單的CNN模型。以下是一個基本的CNN模型示例:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
def build_model(input_shape, num_classes):
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
在這個模型中,我們使用了兩個卷積層和兩個池化層,然后通過全連接層進行分類。
在構建好模型后,我們需要對模型進行訓練。假設我們已經將數據集加載為X_train
, y_train
, X_test
, y_test
。
from tensorflow.keras.utils import to_categorical
# 假設輸入圖像大小為64x64,類別數為100
input_shape = (64, 64, 1)
num_classes = 100
# 將標簽轉換為one-hot編碼
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
# 構建模型
model = build_model(input_shape, num_classes)
# 訓練模型
model.fit(X_train, y_train, batch_size=128, epochs=10, validation_data=(X_test, y_test))
訓練完成后,我們可以保存模型以便后續使用:
model.save('handwritten_chinese_model.h5')
接下來,我們使用Flask構建一個簡單的Web應用,允許用戶上傳手寫漢字圖片并進行識別。
首先,創建一個基本的Flask應用結構:
my_flask_app/
│
├── app.py
├── templates/
│ └── index.html
└── static/
└── uploads/
app.py
在app.py
中,我們編寫Flask應用的主要邏輯:
from flask import Flask, render_template, request, redirect, url_for
import numpy as np
from tensorflow.keras.models import load_model
from PIL import Image
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
# 加載模型
model = load_model('handwritten_chinese_model.h5')
def preprocess_image(image_path):
img = Image.open(image_path).convert('L') # 轉換為灰度圖像
img = img.resize((64, 64)) # 調整大小為64x64
img = np.array(img) / 255.0 # 歸一化
img = np.expand_dims(img, axis=0) # 增加批次維度
img = np.expand_dims(img, axis=-1) # 增加通道維度
return img
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file:
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(file_path)
img = preprocess_image(file_path)
prediction = model.predict(img)
predicted_class = np.argmax(prediction, axis=1)[0]
return render_template('index.html', prediction=predicted_class, image_url=file_path)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
在templates/index.html
中,我們創建一個簡單的HTML頁面,允許用戶上傳圖片并顯示識別結果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手寫中文識別</title>
</head>
<body>
<h1>手寫中文識別</h1>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上傳并識別">
</form>
{% if prediction %}
<h2>識別結果: {{ prediction }}</h2>
<img src="{{ image_url }}" alt="Uploaded Image">
{% endif %}
</body>
</html>
在完成上述步驟后,我們可以通過以下命令運行Flask應用:
python app.py
應用將在本地運行,并可以通過瀏覽器訪問http://127.0.0.1:5000/
。
如果你希望將應用部署到生產環境,可以考慮使用Gunicorn和Nginx進行部署。
通過本文,我們學習了如何使用Python和Flask搭建一個基于CNN的在線手寫中文識別網站。我們從環境搭建、模型訓練、Flask應用開發到部署的整個過程進行了詳細講解。希望這篇文章能幫助你快速上手并構建自己的手寫中文識別應用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。