|
@@ -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]
|