Browse Source

v3.5: fix full black image problem.

Tinger 2 năm trước cách đây
mục cha
commit
2c0ad7e0e3
2 tập tin đã thay đổi với 18 bổ sung16 xóa
  1. 16 16
      blues/idc.py
  2. 2 0
      utils/util.py

+ 16 - 16
blues/idc.py

@@ -8,7 +8,7 @@ from utils.logger import Logger
 idc = Blueprint("idc", __name__, url_prefix="/idc")
 
 _MIN_SIZE = 46
-__exclude = "中国CHINA *#★☆"
+_EXCLUDE_CHAR = "中国CHINA *#★☆"
 __face_ptn = r"姓名(?P<name>.+)" \
              r"性别(?P<gender>男|女)民族(?P<nation>.+)" \
              r"出生(?P<year>\d{4})年(?P<month>\d\d)月(?P<day>\d\d)日" \
@@ -85,10 +85,10 @@ class IdcView(views.MethodView):
         img = read_img(content)
         cropped = crop_img(img)  # 边缘裁剪,对深色背景的效果很好
         images = [item for item in rot_img(cropped) if item.shape[0] < item.shape[1]]  # 旋转后仅取横长竖宽
-        rec = Engine.rec_multi(images)
-        info, err_rec, sta, idx = {}, [], False, 0
-        for i, ocr_res in enumerate(rec):
-            rec_str = "".join([it[0] for it in ocr_res])
+        recognizes = Engine.rec_multi(images)
+        info, msg, sta, idx = {}, "识别失败,请重新选择", False, 0
+        for i, ocr_res in enumerate(recognizes):
+            rec_str = "".join([it[0] for it in ocr_res if not str_include(_EXCLUDE_CHAR, it[0])])
             if which == "face":
                 if rec_str.startswith("姓名"):
                     idx = i
@@ -100,17 +100,15 @@ class IdcView(views.MethodView):
             if sta:
                 break
             elif len(rec_str) >= _MIN_SIZE:
+                msg = "识别失败,建议选择深色背景"
                 Logger.error(rec_str)
-                err_rec.append(rec_str)
 
         info["duration"] = time() - start
         if sta:
             raw_path = f"static/images/{current_time()}_{rand_str()}.{ext}"
             save_img(raw_path, images[idx])
             return Response(data=info)
-        else:
-            msg = "识别失败,建议使用深色背景"
-            return Response(msg, info)
+        return Response(msg, info)
 
 
 class IdcHtmlView(views.MethodView):
@@ -135,10 +133,11 @@ class IdcHtmlView(views.MethodView):
         img = read_img(content)
         cropped = crop_img(img)
         images = [item for item in rot_img(cropped) if item.shape[0] < item.shape[1]]
-        rec = Engine.rec_multi(images)
+        recognizes = Engine.rec_multi(images)
         info, err_rec, sta, idx = {}, [], False, 0
-        for i, ocr_res in enumerate(rec):
-            rec_str = "".join([it[0] for it in ocr_res])
+        msg = "识别失败,请重新选择"
+        for i, ocr_res in enumerate(recognizes):
+            rec_str = "".join([it[0] for it in ocr_res if not str_include(_EXCLUDE_CHAR, it[0])])
             if which == "face":
                 if rec_str.startswith("姓名"):
                     idx = i
@@ -148,8 +147,10 @@ class IdcHtmlView(views.MethodView):
                     idx = i
                     info, sta = get_icon_info(rec_str)
             if sta:
+                msg = "识别成功"
                 break
             elif len(rec_str) >= _MIN_SIZE:
+                msg = "识别失败,建议选择深色背景"
                 Logger.error(rec_str)
                 err_rec.append(rec_str)
 
@@ -157,10 +158,9 @@ class IdcHtmlView(views.MethodView):
         save_img(file_path, images[idx])
 
         info["SUCCESS"] = str(sta).upper()
-        if sta:
-            info["MESSAGE"] = "识别成功"
-        else:
-            info["MESSAGE"] = "识别失败,建议使用深色背景<br>识别结果:<br>" + "<br>".join(err_rec)
+        info["MESSAGE"] = msg
+        if len(err_rec):
+            info["MESSAGE"] += "<br>识别结果:<br>" + "<br>".join(err_rec)
         info["DURATION"] = time() - start  # noqa
         return render_template("k-v_result.html", raw=file_path, data=info)
 

+ 2 - 0
utils/util.py

@@ -54,6 +54,8 @@ def crop_img(image: "np.ndarray") -> "np.ndarray":
     gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # noqa 将图像转换为灰度图像
     _, threshold = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)  # noqa 换为二值图像 => save: [150,255]
     contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  # noqa 查找轮廓
+    if not contours:
+        return image
     max_contour = max(contours, key=cv2.contourArea)  # noqa 找到最大的轮廓
     rect = cv2.minAreaRect(max_contour)  # noqa 计算最小外接矩形
     box = cv2.boxPoints(rect)  # noqa 获取矩形的四个角点