首写Python-实现文字图片识别
首先,安装所需依赖库:
pip install flask pytesseract pillow
然后,创建一个名为 app.py
的文件,并复制以下代码:
from flask import Flask, render_template, request
import pytesseract
from PIL import Image
app = Flask(__name__)
#首页路由
@app.route('/')
def index():
return render_template('index.html')
#文字识别路由
@app.route('/recognize', methods=['POST'])
def recognize():
if 'file' not in request.files:
return render_template('error.html', error='No file provided!')
file = request.files['file']
if file.filename == '':
return render_template('error.html', error='No file selected!')
#读取图片并进行文字识别
img = Image.open(file)
text = pytesseract.image_to_string(img, lang='chi_sim')
#返回识别结果
return render_template('result.html', text=text)
if __name__ == '__main__':
app.run(debug=True)
在同一目录下创建 templates
文件夹,并在 templates
文件夹中创建三个HTML文件:index.html
、result.html
和error.html
,分别复制以下代码:
index.html:
<!doctype html>
<html>
<head>
<title>Text Recognition App</title>
</head>
<body>
<h1>Text Recognition App</h1>
<form action="{
{ url_for('recognize') }}" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
result.html:
<!doctype html>
<html>
<head>
<title>Text Recognition Result</title>
</head>
<body>
<h1>Text Recognition Result</h1>
<p>{
{ text }}</p>
</body>
</html>
error.html:
<!doctype html>
<html>
<head>
<title>Text Recognition Error</title>
</head>
<body>
<h1>Text Recognition Error: {
{ error }}</h1>
</body>
</html>
最后,在终端中运行以下命令启动Flask程序:
python app.py
现在,打开浏览器访问 http://localhost:5000
即可使用该Web应用程序上传图片并进行中文文字识别。
以上代码示例只是一个基础的文字识别应用程序,需要注意的是,图片处理和文字识别是比较耗时的操作,这会占用很多计算和内存资源,对于大型图片和高要求的文字识别任务,可能需要更加复杂和高效的方案来完成。
还没有评论,来说两句吧...