首写Python-实现文字图片识别

深碍√TFBOYSˉ_ 2023-10-09 20:21 198阅读 0赞

首先,安装所需依赖库:

  1. pip install flask pytesseract pillow

然后,创建一个名为 app.py 的文件,并复制以下代码:

  1. from flask import Flask, render_template, request
  2. import pytesseract
  3. from PIL import Image
  4. app = Flask(__name__)
  5. #首页路由
  6. @app.route('/')
  7. def index():
  8. return render_template('index.html')
  9. #文字识别路由
  10. @app.route('/recognize', methods=['POST'])
  11. def recognize():
  12. if 'file' not in request.files:
  13. return render_template('error.html', error='No file provided!')
  14. file = request.files['file']
  15. if file.filename == '':
  16. return render_template('error.html', error='No file selected!')
  17. #读取图片并进行文字识别
  18. img = Image.open(file)
  19. text = pytesseract.image_to_string(img, lang='chi_sim')
  20. #返回识别结果
  21. return render_template('result.html', text=text)
  22. if __name__ == '__main__':
  23. app.run(debug=True)

在同一目录下创建 templates 文件夹,并在 templates 文件夹中创建三个HTML文件:index.htmlresult.htmlerror.html,分别复制以下代码:

index.html:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Text Recognition App</title>
  5. </head>
  6. <body>
  7. <h1>Text Recognition App</h1>
  8. <form action="{
  9. { url_for('recognize') }}" method="POST" enctype="multipart/form-data">
  10. <input type="file" name="file">
  11. <input type="submit" value="Upload">
  12. </form>
  13. </body>
  14. </html>

result.html:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Text Recognition Result</title>
  5. </head>
  6. <body>
  7. <h1>Text Recognition Result</h1>
  8. <p>{
  9. { text }}</p>
  10. </body>
  11. </html>

error.html:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <title>Text Recognition Error</title>
  5. </head>
  6. <body>
  7. <h1>Text Recognition Error: {
  8. { error }}</h1>
  9. </body>
  10. </html>

最后,在终端中运行以下命令启动Flask程序:

  1. python app.py

现在,打开浏览器访问 http://localhost:5000 即可使用该Web应用程序上传图片并进行中文文字识别。

以上代码示例只是一个基础的文字识别应用程序,需要注意的是,图片处理和文字识别是比较耗时的操作,这会占用很多计算和内存资源,对于大型图片和高要求的文字识别任务,可能需要更加复杂和高效的方案来完成。

发表评论

表情:
评论列表 (有 0 条评论,198人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python3 图片文字识别

      最近用到了图片文字识别这个功能,从网上搜查了一下,决定利用百度的文字识别接口。通过测试发现文字识别率还可以。下面就测试过程简要说明一下   1、注册用户    链接:[