使用python框架Flask简单实现ocr服务的api

1. 准备

  • 安装好python环境、使用pip(pip可以配置国内镜像源)安装ddddocr、flask、requests
  • 写了两个api,使用网图作为参数的/coder接口,使用本地图片作为参数的upload接口
import requests
from flask import Flask, request, jsonify
import ddddocr

ocr = ddddocr.DdddOcr()
app = Flask(__name__)


@app.route('/coder', methods=['POST'])
def coder():
    picpath = request.json.get('picpath')  # 假设你通过POST请求发送JSON数据

    if picpath is None:
        return jsonify({'error': 'picpath not none'}), 400
    try:
        response = requests.get(picpath)
        response.raise_for_status()  # 确保请求成功
        with open("./testpng.png", "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)  # 写入图片二进制数据
        with open('./testpng.png', 'rb') as f:
            img_bytes = f.read()
        res = ocr.classification(img_bytes)
        tempjson = {'code': '0'}
        tempjson['code'] = res
        return jsonify(tempjson)  # 使用 jsonify 来返回 JSON 响应
    except requests.exceptions.MissingSchema:
        return jsonify({'error': 'File Not Found'}), 400

@app.route('/upload', methods=['POST'])
def upload_file():
    # 检查请求方法是否为 POST
    if request.method == 'POST':
        # 检查是否有文件字段
        if 'file' not in request.files:
            return jsonify({'error': 'agrs error'}), 400
        file = request.files['file']
        # 检查文件是否存在
        if file.filename == '':
            return jsonify({'error': 'No selected file'}), 400
            # 保存文件到指定目录
        file.save('./' + file.filename)
        with open('./' + file.filename, 'rb') as f:
            img_bytes = f.read()
        res = ocr.classification(img_bytes)
        tempjson = {'code': '0'}
        tempjson['code'] = res
        return jsonify(tempjson)
    return jsonify({'error': 'Method Not Allowed'}), 405


if __name__ == "__main__":
    app.run(host='localhost', port=8080, debug=True)

2. 实际调用

  • 使用本地验证码图片去识别

  • 使用网络验证码图片作为参数去识别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值