Browse Source

v3.5: 提升日志

Tinger 2 years ago
parent
commit
41994e6aae
3 changed files with 22 additions and 3 deletions
  1. 2 1
      .gitignore
  2. 1 1
      utils/logger.py
  3. 19 1
      utils/util.py

+ 2 - 1
.gitignore

@@ -3,4 +3,5 @@ venv
 .idea
 static/images/*
 
-test
+test
+test.py

+ 1 - 1
utils/logger.py

@@ -3,4 +3,4 @@ import logging
 __all__ = ["Logger"]
 
 Logger = logging.getLogger("HuiMvOCR")
-Logger.setLevel(logging.INFO)
+Logger.setLevel(logging.WARNING)

+ 19 - 1
utils/util.py

@@ -1,5 +1,7 @@
 import cv2
 import numpy as np
+from PIL import Image
+from io import BytesIO
 from typing import Union
 from flask import jsonify
 from random import randint
@@ -8,11 +10,13 @@ from time import localtime, strftime
 
 __all__ = [
     "Response", "rand_str", "current_time", "get_ext_name", "is_image_ext",
-    "str_include", "read_img", "crop_img", "rot_img", "save_img", "Engine"
+    "str_include", "read_img", "compress_img", "crop_img", "rot_img", "save_img",
+    "Engine"
 ]
 
 __StrBase = "qwertyuioplkjhgfdsazxcvbnm1234567890ZXCVBNMLKJHGFDSAQWERTYUIOP"
 __StrBaseLen = len(__StrBase) - 1
+__MAX_IMAGE_SIZE = 3500 * 2000
 __AcceptExtNames = ["jpg", "jpeg", "bmp", "png", "rgb", "tif", "tiff", "gif"]
 Engine = HuiMvOCR(Args())
 
@@ -50,6 +54,20 @@ def read_img(content: "str") -> "np.ndarray":
     return cv2.imdecode(np.frombuffer(content, np.uint8), 1)  # noqa
 
 
+def compress_img(img: "np.ndarray", tar_size: "int" = __MAX_IMAGE_SIZE) -> "np.ndarray":
+    cur_size = img.shape[0] * img.shape[1]
+    if cur_size <= tar_size:
+        return img
+
+    image = Image.fromarray(img)
+    output = BytesIO()
+    image.save(output, format="JPEG", quality=int(tar_size / cur_size * 100))
+    output.seek(0)
+    compressed_image = Image.open(output)
+
+    return np.array(compressed_image)
+
+
 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]