Skip to content

📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

update ocrweb, 添加图像格式大小限制,本地不存储图像

SWHL358d26e58dc2
diff --git a/ocrweb/main.py b/ocrweb/main.py
index 90e19be..b2a68da 100644
--- a/ocrweb/main.py
+++ b/ocrweb/main.py
@@ -2,12 +2,13 @@
# -*- encoding: utf-8 -*-
# @File: main.py
# @Author: Max
+import base64
+import json
import time
-from pathlib import Path
import cv2
-from flask import Flask, jsonify, render_template, request
-from werkzeug.utils import secure_filename
+import numpy as np
+from flask import Flask, render_template, request
from resources.bpocr import TextSystem, draw_text_det_res
@@ -21,71 +22,47 @@ text_sys = TextSystem(det_model_path,
use_angle_cls=True,
cls_model_path=cls_model_path)
-# 设置允许的文件格式
-ALLOWED_EXTENSIONS = {'png', 'jpg', 'JPG', 'PNG', 'bmp', 'jpeg', 'gif', 'tif'}
app = Flask(__name__)
# 设置上传文件大小
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10M
-# 设置静态文件缓存过期时间
-# app.send_file_max_age_default = TimedeltaFormat(seconds=10)
-def make_directory(directory_path):
- if not isinstance(directory_path, Path):
- directory_path = Path(directory_path)
- directory_path.mkdir(parents=True, exist_ok=True)
-
-
-def allowed_file(filename):
- return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
+def index():
+ return render_template('index.html')
@app.route('/ocr', methods=['POST', 'GET'])
def ocr():
if request.method == 'POST':
- f = request.files['file']
-
- if not (f and allowed_file(f.filename)):
- return jsonify({"error": 1001, "msg": "only support png、PNG、\
- jpg、JPG、bmp、JPEG、gif"})
-
- time_stamp = time.strftime('%Y-%m-%d-%H-%M-%S',
- time.localtime(time.time()))
- img_name = f"{time_stamp}_{secure_filename(f.filename)}"
-
- root_path = Path(__file__).resolve().parent
- static_directory = root_path / 'static'
-
- raw_directory = static_directory / 'images'
- make_directory(raw_directory)
-
- infer_directory = static_directory / 'inference_results'
- make_directory(infer_directory)
-
- upload_path = str(raw_directory / f'raw_{img_name}')
- f.save(upload_path)
+ url_get = request.get_json()
+ url_get = str(url_get).split(',')[1]
+ image = base64.b64decode(url_get)
+ nparr = np.frombuffer(image, np.uint8)
+ image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
t1 = time.time()
- dt_boxes, rec_res, img = text_sys(upload_path)
+ dt_boxes, rec_res, img = text_sys(image)
t2 = time.time()
- rec_res = list(zip(range(len(rec_res)), rec_res))
+ temp_rec_res = []
+ for i, value in enumerate(rec_res):
+ temp_rec_res.append([i, value[0], value[1]])
+ temp_rec_res = np.array(temp_rec_res)
+ rec_res_data = json.dumps(temp_rec_res.tolist(),
+ indent=2,
+ ensure_ascii=False)
det_im = draw_text_det_res(dt_boxes, img)
- det_path = f'inference_results/det_{img_name}'
+ image = cv2.imencode('.jpg', det_im)[1]
+ img = str(base64.b64encode(image))[2:-1]
- cv2.imwrite(str(static_directory / det_path), det_im)
-
- return render_template('index_ok.html',
- det_img_path=det_path,
- rec_res=rec_res,
- time=str(f'{t2-t1:.3f}'),
- width='100%',
- height='100%',
- )
- return render_template('index.html')
+ elapse = f'{t2-t1:.3f}'
+ return json.dumps({'image': img,
+ 'elapse': elapse,
+ 'rec_res': rec_res_data})
if __name__ == '__main__':
- app.run(host='0.0.0.0', port=9003, debug=False, processes=True)
+ app.run(host='0.0.0.0', port=9003, debug=True, processes=True)
diff --git a/ocrweb/resources/bpocr.py b/ocrweb/resources/bpocr.py
index 489bb51..fba270b 100644
--- a/ocrweb/resources/bpocr.py
+++ b/ocrweb/resources/bpocr.py
@@ -115,7 +115,8 @@ class TextSystem(object):
return img
def __call__(self, image_path):
- img = self.load_image(image_path)
+ # img = self.load_image(image_path)
+ img = image_path
dt_boxes, elapse = self.text_detector(img)
print("dt_boxes num : {}, elapse : {}".format(
len(dt_boxes), elapse))
@@ -166,6 +167,7 @@ if __name__ == '__main__':
# v2.0 通用模型
from ch_ppocr_server_v2_det import TextDetector
from ch_ppocr_server_v2_rec import TextRecognizer
+
from ch_ppocr_mobile_v2_cls import TextClassifier
det_model_path = 'models/ch_ppocr_server_v2.0_det_train.onnx'
diff --git "a/ocrweb/resources/models/\346\250\241\345\236\213\344\275\215\347\275\256.md" "b/ocrweb/resources/models/\346\250\241\345\236\213\344\275\215\347\275\256.md"
index 89254ac..e69de29 100644
--- "a/ocrweb/resources/models/\346\250\241\345\236\213\344\275\215\347\275\256.md"
+++ "b/ocrweb/resources/models/\346\250\241\345\236\213\344\275\215\347\275\256.md"
@@ -1,3 +0,0 @@
-det_model_path = 'resources/models/ch_ppocr_mobile_v2_det_train.onnx'
-cls_model_path = 'resources/models/ch_ppocr_mobile_v2.0_cls_train.onnx'
-rec_model_path = 'resources/models/ch_ppocr_mobile_v2.0_rec_pre.onnx'
\ No newline at end of file
diff --git a/ocrweb/templates/index.html b/ocrweb/templates/index.html
index f85849b..732988e 100644
--- a/ocrweb/templates/index.html
+++ b/ocrweb/templates/index.html
@@ -1,38 +1,195 @@
<!DOCTYPE html>
<html lang="en">
-<style type="text/css">
- body{
- background-color:#ebedef;
- }
- .area
- {
- text-align: center;
- height: auto;
- margin: auto;
- }
- .btn {
- background: #2196f3;
- border-color: #2196f3;
- font-size: 14px;
- padding-top: 6px;
- color: #fff;
- padding-bottom: 6px;
- }
- .upload {
- font-size: 14px;
- }
-</style>
<head>
<meta charset="UTF-8">
<title>RapidOCR Demo</title>
+ <style type="text/css">
+ body{
+ background-color:#ebedef;
+ }
+ .btn-gen {
+ /* position: absolute;top:540px; left: 500px; */
+ background-color: #00a1d6;
+ text-align: center;
+ border-radius: 20px;
+ margin-top: 5px;
+ font-size: 15px;
+ padding: 5px 5px;
+ height: 20px;
+ width: 120px;
+ text-transform: uppercase;
+ color: #fff;
+ border:none;
+ }
+ .btn-gen:hover,
+ .btn-gen:focus {
+ border-color: #23AAEE;
+ background-color: #23AAEE;
+ color: white;
+ cursor: pointer;
+ }
+ .area{
+ text-align: center;
+ height: auto;
+ margin: auto;
+ }
+ .leftarea{
+ float: left;
+ width: 50%;
+ height: auto;
+ }
+
+ .rightarea{
+ float: left;
+ width: 50%;
+ height: auto;
+ }
+ .table{
+ width: auto;
+ height: auto;
+ margin: 0 auto;
+ border: 0px solid #000;
+ }
+ .span_title{
+ width: 98%;
+ height: 36px;
+ margin-top: 4px;
+ line-height: 32px;
+ background-color: #00a1d6;
+ border: 1px solid #00a1d6;
+ border-radius: 20px;
+ color: #fff;
+ display: inline-block;
+ text-align: center;
+ font-size: 26px;
+ transition: .3s;
+ box-sizing: border-box;
+ }
+ .uplodNote{
+ font-size: 14px;
+ color:#000;
+ font-style: italic;
+ }
+ a{text-decoration:none}
+ </style>
</head>
<body>
- <h1 align="center">RapidOCR Demo</h1>
+ <h1 align="center">
+ RapidOCR Demo &nbsp;
+ <a href="https://github.com/znsoftm/RapidOCR" style="font-size: 14px;">欢迎Star</a>
+ </h1>
+ <div class='area'>
+ <span class="uplodNote">图片文件类型支持PNG、JPG、JPEG、BMP,图片大小不超过10M。</span>
+ <span class="btn-gen" onclick="javascript:$('#rapid_ocr').click();">试试你的图片?</span>
+ <input type="file" style="display: none;" name="pic" id="rapid_ocr"/>
+ </div>
+ <br/>
<div class="area">
- <form action="" enctype='multipart/form-data' method='POST'>
- <input type="file" name="file" class="upload" style="margin-top:20px;"/>
- <input type="submit" value="检测+识别" class="btn" style="margin-top:15px;cursor:pointer"/>
- </form>
+ <div class="leftarea" id="detectDiv">
+ <span class="span_title">文本检测结果:</span><br/><br/>
+ <img id="detect_img" src=""/>
+ </div>
+
+ <div class="rightarea" id="recogDiv">
+ <span id="rec_res" class="span_title">文本识别结果:</span>
+ <br/> <br/>
+ <table id="locTable" border="1" class="table" cellspacing="0" cellpadding="5"></table>
+ </div>
</div>
+ <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
+ <script type="text/javascript">
+ // 页面加载时,执行
+ window.onload = function () {
+ $("#detectDiv").hide();
+ $("#recogDiv").hide();
+ }
+
+ $("#rapid_ocr").change(function(){
+ let file = document.getElementById("rapid_ocr").files[0];
+
+ // 判断图像格式是否匹配
+ let imageName = file.name;
+ let index = imageName.lastIndexOf('.');
+ let extName = imageName.substr(index + 1);
+ let imgArr = ['jpg', 'bmp', 'png', 'jpeg'];
+ if (!(imgArr.includes(extName.toLocaleLowerCase()))){
+ alert("图像文件格式不支持!");
+ return;
+ }
+
+ // 判断图像大小是否符合
+ let imageSize = file.size / 1024 / 1024;
+ if (imageSize >= 10) {
+ alert("图像大小超过10M!");
+ return;
+ }
+
+ var reader = new FileReader();
+ reader.onload = function(e){
+ var upload_data = {"file": reader.result,};
+ console.log(reader.result)
+ $.ajax(
+ {
+ url:"/ocr",
+ type:"POST",
+ data: JSON.stringify(upload_data),
+ contentType: 'application/json; charset=UTF-8',
+ dataType: 'json',
+
+ beforeSend:function(){
+ $('#detect_img').attr("width", "");
+ $('#detect_img').attr("height", "");
+ },
+
+ success:function (data) {
+ $('#detect_img').attr("width", "95%");
+ $('#detect_img').attr("height", "95%");
+ $("#detectDiv").show();
+ $("#recogDiv").show();
+
+ if (data){
+ if (data['image']){
+ $("#detect_img").attr('src', 'data:image/jpeg;base64,'+ data['image']);
+ $('#detect_img').show();
+ }
+ if (data["elapse"]){
+ document.getElementById("rec_res").textContent = "文本识别结果(耗时:" + String(data['elapse']) + "s):"
+ }
+ if (data["rec_res"]){
+ var rec_res = JSON.parse(data["rec_res"]);
+
+ // 绘制整个结果表格
+ var data = "";
+ data += "<tr>" +
+ '<th bgcolor="#C0C0C0">序号</th>' +
+ '<th bgcolor="#C0C0C0">识别结果</th>' +
+ '<th bgcolor="#C0C0C0">置信度</th>' +
+ "</tr>"
+ for (let i = 0; i < rec_res.length; i++) {
+ const element = rec_res[i];
+ let num = element[0];
+
+ let rec_result = element[1];
+
+ let score = Number(element[2]);
+ score = score.toFixed(4);
+
+ data += "<tr>"
+ data += "<td>" + num + "</td>";
+ data += "<td align='left'>" + rec_result + "</td>";
+ data += "<td>" + score + "</td>";
+ data += "</tr>"
+ }
+ document.getElementById("locTable").innerHTML = data;
+ }
+ }
+
+ }
+ }
+ );
+ }
+ reader.readAsDataURL(this.files[0])
+ });
+ </script>
</body>
</html>
\ No newline at end of file
diff --git a/ocrweb/templates/index_ok.html b/ocrweb/templates/index_ok.html
deleted file mode 100644
index 904d3f4..0000000
--- a/ocrweb/templates/index_ok.html
+++ /dev/null
@@ -1,112 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <title>RapidOCR Demo</title>
-</head>
-<style type="text/css">
- body{
- background-color:#ebedef;
- }
- .area{
- text-align: center;
- height: auto;
- margin: auto;
- }
- .leftarea{
- float: left;
- width: 49%;
- height: auto;
- }
-
- .rightarea{
- float: left;
- width: 49%;
- height: auto;
- }
-
- .table{
- margin: 0 auto;
- /* border: 0; */
- /* border-spacing: 0px 15px; */
- }
- tr td{
- border:1px solid black;
- border-bottom-width: thin;
- border-right-style: thin;
- border-left-style: thin;
- border-top-style: thin;
- }
-
- .btn {
- margin-top: 4px;
- line-height: 32px;
- border-radius: 4px;
- display: inline-block;
- text-align: center;
- transition: .3s;
- box-sizing: border-box;
- }
-
- .upload{
- font-size: 14px;
- }
- .span_title{
- width: 98%;
- height: 36px;
- margin-top: 4px;
- line-height: 32px;
- background-color: #00a1d6;
- border: 1px solid #00a1d6;
- border-radius: 4px;
- color: #fff;
- display: inline-block;
- text-align: center;
- font-size: 26px;
- transition: .3s;
- box-sizing: border-box;
- }
- span{
- font-size: 26px;
- }
-</style>
-<body>
- <h1 align="center">RapidOCR Demo</h1>
- <div class="area">
- <form action="" enctype='multipart/form-data' method='POST'>
- <input type="file" name="file" class="upload" style="margin-top:20px;"/>
- <input type="submit" value="检测+识别" class="btn" style="margin-top:15px;cursor:pointer"/>
- </form>
- <br>
- </div>
-
- <div class="area">
- <div class="leftarea">
- <span class="span_title">文本检测结果:</span>
- <br/>
- <br/>
- <img src="{{ url_for('static', filename=det_img_path, _t=val1) }}" alt="文本检测图" width="{{width}}" height="{{height}}" title="文本检测图"/>
- </div>
-
- <div class="rightarea">
- <span class="span_title">文本识别结果(耗时:{{time}}s):</span>
- <br/> <br/>
- <table class="table" cellpadding="0" cellspacing="0">
- <tr>
- <td><strong>序号</strong></td>
- <td><strong>识别结果</strong></td>
- <td><strong>置信度</strong></td>
- </tr>
- {% for value in rec_res%}
- <tr>
- <td>{{value[0]}}</td>
- <td>{{value[1][0]}}</td>
- <td>{{value[1][1]}}</td>
- </tr>
- {% endfor %}
- </table>
- </div>
- </div>
-
-</body>
-</html>
\ No newline at end of file