jp ocr ok
Browse files- jp_ocr.py +15 -2
- ocr.py +396 -0
- requirements.txt +68 -0
jp_ocr.py
CHANGED
|
@@ -5,6 +5,8 @@
|
|
| 5 |
# 第一次 aliocr 识别中文 main.py
|
| 6 |
# 第二次用 ppocr 识别日文 jp_ocr.py
|
| 7 |
|
|
|
|
|
|
|
| 8 |
import json, cv2
|
| 9 |
|
| 10 |
def save_json(filename, dics):
|
|
@@ -39,6 +41,7 @@ if __name__ == '__main__':
|
|
| 39 |
jsn = item['js']
|
| 40 |
imgData = np.fromfile(pth_img, dtype=np.uint8)
|
| 41 |
img_color = cv2.imdecode(imgData, -1)
|
|
|
|
| 42 |
if 'prism_wordsInfo' in jsn:
|
| 43 |
wordsInfo = jsn['prism_wordsInfo']
|
| 44 |
else:
|
|
@@ -85,8 +88,13 @@ if __name__ == '__main__':
|
|
| 85 |
img_crop = img_color[lu[1]:lu[1]+(rd[1]-lu[1]), lu[0]:lu[0]+(rd[0]-lu[0])]
|
| 86 |
# img_crop = m4.ocr_frame[y:y+height, x:x+width]
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
|
| 92 |
|
|
@@ -333,6 +341,9 @@ def ocr_one_pdf(pth_pdf):
|
|
| 333 |
break
|
| 334 |
|
| 335 |
img_color = get_page_image(reader, nth_page)
|
|
|
|
|
|
|
|
|
|
| 336 |
cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))
|
| 337 |
|
| 338 |
# 把img 对象编码为jpg 格式
|
|
@@ -420,6 +431,8 @@ def ocr_one_pdf(pth_pdf):
|
|
| 420 |
# img_color = cv2.rectangle(img_color, (x1, y1), (x2, y2), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
|
| 421 |
img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
|
| 422 |
|
|
|
|
|
|
|
| 423 |
# cv2.imshow("green", img_color)
|
| 424 |
# cv2.waitKey(0)
|
| 425 |
|
|
|
|
| 5 |
# 第一次 aliocr 识别中文 main.py
|
| 6 |
# 第二次用 ppocr 识别日文 jp_ocr.py
|
| 7 |
|
| 8 |
+
from ocr import rec as ppocr
|
| 9 |
+
|
| 10 |
import json, cv2
|
| 11 |
|
| 12 |
def save_json(filename, dics):
|
|
|
|
| 41 |
jsn = item['js']
|
| 42 |
imgData = np.fromfile(pth_img, dtype=np.uint8)
|
| 43 |
img_color = cv2.imdecode(imgData, -1)
|
| 44 |
+
|
| 45 |
if 'prism_wordsInfo' in jsn:
|
| 46 |
wordsInfo = jsn['prism_wordsInfo']
|
| 47 |
else:
|
|
|
|
| 88 |
img_crop = img_color[lu[1]:lu[1]+(rd[1]-lu[1]), lu[0]:lu[0]+(rd[0]-lu[0])]
|
| 89 |
# img_crop = m4.ocr_frame[y:y+height, x:x+width]
|
| 90 |
|
| 91 |
+
txts, boxes, scores, pil_image = ppocr(img_crop)
|
| 92 |
+
print( txts )
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# cv2.imshow("img_crop", img_crop)
|
| 97 |
+
# cv2.waitKey(0)
|
| 98 |
|
| 99 |
|
| 100 |
|
|
|
|
| 341 |
break
|
| 342 |
|
| 343 |
img_color = get_page_image(reader, nth_page)
|
| 344 |
+
|
| 345 |
+
txts, boxes, scores, pil_image = ppocr( cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR) )
|
| 346 |
+
|
| 347 |
cv2.imwrite('./tmp.jpg', cv2.cvtColor(img_color, cv2.COLOR_RGB2BGR))
|
| 348 |
|
| 349 |
# 把img 对象编码为jpg 格式
|
|
|
|
| 431 |
# img_color = cv2.rectangle(img_color, (x1, y1), (x2, y2), (0, 255, 0), 2) # 矩形的左上角, 矩形的右下角
|
| 432 |
img_color = cv2.rectangle(img_color, (lu[0], lu[1]), (rd[0], rd[1]), (0, 255, 0), 2) # 矩形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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# proxychains4 pip install -r PaddleOCR_ali1k_det_rec_300epoch_standalone/requirements.txt
|
| 3 |
+
|
| 4 |
+
# PaddleOCR_ali1k_det_rec_300epoch/tools/infer/predict_system.py
|
| 5 |
+
|
| 6 |
+
__all__ = ['rec']
|
| 7 |
+
# 以”白名单“的形式暴露里面定义的符号
|
| 8 |
+
|
| 9 |
+
import os, sys
|
| 10 |
+
|
| 11 |
+
__dir__ = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
# sys.path.append(__dir__)
|
| 13 |
+
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, 'PaddleOCR_ali1k_det_rec_300epoch_standalone')))
|
| 14 |
+
|
| 15 |
+
os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
|
| 16 |
+
|
| 17 |
+
import cv2
|
| 18 |
+
import copy
|
| 19 |
+
import numpy as np
|
| 20 |
+
import json
|
| 21 |
+
import time
|
| 22 |
+
import logging
|
| 23 |
+
from PIL import Image
|
| 24 |
+
import PaddleOCR_ali1k_det_rec_300epoch_standalone.tools.infer.utility as utility
|
| 25 |
+
|
| 26 |
+
import PaddleOCR_ali1k_det_rec_300epoch_standalone.tools.infer.predict_rec as predict_rec
|
| 27 |
+
import PaddleOCR_ali1k_det_rec_300epoch_standalone.tools.infer.predict_det as predict_det
|
| 28 |
+
import PaddleOCR_ali1k_det_rec_300epoch_standalone.tools.infer.predict_cls as predict_cls
|
| 29 |
+
from PaddleOCR_ali1k_det_rec_300epoch_standalone.ppocr.utils.utility import get_image_file_list, check_and_read
|
| 30 |
+
from PaddleOCR_ali1k_det_rec_300epoch_standalone.ppocr.utils.logging import get_logger
|
| 31 |
+
from PaddleOCR_ali1k_det_rec_300epoch_standalone.tools.infer.utility import draw_ocr_box_txt, get_rotate_crop_image
|
| 32 |
+
logger = get_logger()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TextSystem(object):
|
| 36 |
+
def __init__(self, args):
|
| 37 |
+
if not args.show_log:
|
| 38 |
+
logger.setLevel(logging.INFO)
|
| 39 |
+
|
| 40 |
+
self.text_detector = predict_det.TextDetector(args)
|
| 41 |
+
self.text_recognizer = predict_rec.TextRecognizer(args)
|
| 42 |
+
self.use_angle_cls = args.use_angle_cls
|
| 43 |
+
self.drop_score = args.drop_score
|
| 44 |
+
if self.use_angle_cls:
|
| 45 |
+
self.text_classifier = predict_cls.TextClassifier(args)
|
| 46 |
+
|
| 47 |
+
self.args = args
|
| 48 |
+
self.crop_image_res_index = 0
|
| 49 |
+
|
| 50 |
+
def draw_crop_rec_res(self, output_dir, img_crop_list, rec_res):
|
| 51 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 52 |
+
bbox_num = len(img_crop_list)
|
| 53 |
+
for bno in range(bbox_num):
|
| 54 |
+
cv2.imwrite(
|
| 55 |
+
os.path.join(output_dir,
|
| 56 |
+
f"mg_crop_{bno+self.crop_image_res_index}.jpg"),
|
| 57 |
+
img_crop_list[bno])
|
| 58 |
+
logger.debug(f"{bno}, {rec_res[bno]}")
|
| 59 |
+
self.crop_image_res_index += bbox_num
|
| 60 |
+
|
| 61 |
+
def __call__(self, img, cls=True):
|
| 62 |
+
time_dict = {'det': 0, 'rec': 0, 'csl': 0, 'all': 0}
|
| 63 |
+
start = time.time()
|
| 64 |
+
ori_im = img.copy()
|
| 65 |
+
dt_boxes, elapse = self.text_detector(img)
|
| 66 |
+
time_dict['det'] = elapse
|
| 67 |
+
logger.debug("dt_boxes num : {}, elapse : {}".format(
|
| 68 |
+
len(dt_boxes), elapse))
|
| 69 |
+
if dt_boxes is None:
|
| 70 |
+
return None, None
|
| 71 |
+
img_crop_list = []
|
| 72 |
+
|
| 73 |
+
dt_boxes = sorted_boxes(dt_boxes)
|
| 74 |
+
|
| 75 |
+
for bno in range(len(dt_boxes)):
|
| 76 |
+
tmp_box = copy.deepcopy(dt_boxes[bno])
|
| 77 |
+
img_crop = get_rotate_crop_image(ori_im, tmp_box)
|
| 78 |
+
img_crop_list.append(img_crop)
|
| 79 |
+
if self.use_angle_cls and cls:
|
| 80 |
+
img_crop_list, angle_list, elapse = self.text_classifier(
|
| 81 |
+
img_crop_list)
|
| 82 |
+
time_dict['cls'] = elapse
|
| 83 |
+
logger.debug("cls num : {}, elapse : {}".format(
|
| 84 |
+
len(img_crop_list), elapse))
|
| 85 |
+
|
| 86 |
+
rec_res, elapse = self.text_recognizer(img_crop_list)
|
| 87 |
+
time_dict['rec'] = elapse
|
| 88 |
+
logger.debug("rec_res num : {}, elapse : {}".format(
|
| 89 |
+
len(rec_res), elapse))
|
| 90 |
+
if self.args.save_crop_res:
|
| 91 |
+
self.draw_crop_rec_res(self.args.crop_res_save_dir, img_crop_list,
|
| 92 |
+
rec_res)
|
| 93 |
+
filter_boxes, filter_rec_res = [], []
|
| 94 |
+
for box, rec_result in zip(dt_boxes, rec_res):
|
| 95 |
+
text, score = rec_result
|
| 96 |
+
if score >= self.drop_score:
|
| 97 |
+
filter_boxes.append(box)
|
| 98 |
+
filter_rec_res.append(rec_result)
|
| 99 |
+
end = time.time()
|
| 100 |
+
time_dict['all'] = end - start
|
| 101 |
+
return filter_boxes, filter_rec_res, time_dict
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def sorted_boxes(dt_boxes):
|
| 105 |
+
"""
|
| 106 |
+
Sort text boxes in order from top to bottom, left to right
|
| 107 |
+
args:
|
| 108 |
+
dt_boxes(array):detected text boxes with shape [4, 2]
|
| 109 |
+
return:
|
| 110 |
+
sorted boxes(array) with shape [4, 2]
|
| 111 |
+
"""
|
| 112 |
+
num_boxes = dt_boxes.shape[0]
|
| 113 |
+
sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
|
| 114 |
+
_boxes = list(sorted_boxes)
|
| 115 |
+
|
| 116 |
+
for i in range(num_boxes - 1):
|
| 117 |
+
for j in range(i, 0, -1):
|
| 118 |
+
if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \
|
| 119 |
+
(_boxes[j + 1][0][0] < _boxes[j][0][0]):
|
| 120 |
+
tmp = _boxes[j]
|
| 121 |
+
_boxes[j] = _boxes[j + 1]
|
| 122 |
+
_boxes[j + 1] = tmp
|
| 123 |
+
else:
|
| 124 |
+
break
|
| 125 |
+
return _boxes
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main(args):
|
| 129 |
+
image_file_list = get_image_file_list(args.image_dir)
|
| 130 |
+
image_file_list = image_file_list[args.process_id::args.total_process_num]
|
| 131 |
+
text_sys = TextSystem(args)
|
| 132 |
+
is_visualize = True
|
| 133 |
+
font_path = args.vis_font_path
|
| 134 |
+
drop_score = args.drop_score
|
| 135 |
+
draw_img_save_dir = args.draw_img_save_dir
|
| 136 |
+
os.makedirs(draw_img_save_dir, exist_ok=True)
|
| 137 |
+
save_results = []
|
| 138 |
+
|
| 139 |
+
logger.info(
|
| 140 |
+
"In PP-OCRv3, rec_image_shape parameter defaults to '3, 48, 320', "
|
| 141 |
+
"if you are using recognition model with PP-OCRv2 or an older version, please set --rec_image_shape='3,32,320"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# warm up 10 times
|
| 145 |
+
if args.warmup:
|
| 146 |
+
img = np.random.uniform(0, 255, [640, 640, 3]).astype(np.uint8)
|
| 147 |
+
for i in range(10):
|
| 148 |
+
res = text_sys(img)
|
| 149 |
+
|
| 150 |
+
total_time = 0
|
| 151 |
+
cpu_mem, gpu_mem, gpu_util = 0, 0, 0
|
| 152 |
+
_st = time.time()
|
| 153 |
+
count = 0
|
| 154 |
+
for idx, image_file in enumerate(image_file_list):
|
| 155 |
+
|
| 156 |
+
img, flag, _ = check_and_read(image_file)
|
| 157 |
+
if not flag:
|
| 158 |
+
img = cv2.imread(image_file)
|
| 159 |
+
if img is None:
|
| 160 |
+
logger.debug("error in loading image:{}".format(image_file))
|
| 161 |
+
continue
|
| 162 |
+
starttime = time.time()
|
| 163 |
+
dt_boxes, rec_res, time_dict = text_sys(img)
|
| 164 |
+
elapse = time.time() - starttime
|
| 165 |
+
total_time += elapse
|
| 166 |
+
|
| 167 |
+
logger.debug(
|
| 168 |
+
str(idx) + " Predict time of %s: %.3fs" % (image_file, elapse))
|
| 169 |
+
for text, score in rec_res:
|
| 170 |
+
logger.debug("{}, {:.3f}".format(text, score))
|
| 171 |
+
|
| 172 |
+
res = [{
|
| 173 |
+
"transcription": rec_res[idx][0],
|
| 174 |
+
"points": np.array(dt_boxes[idx]).astype(np.int32).tolist(),
|
| 175 |
+
} for idx in range(len(dt_boxes))]
|
| 176 |
+
save_pred = os.path.basename(image_file) + "\t" + json.dumps(
|
| 177 |
+
res, ensure_ascii=False) + "\n"
|
| 178 |
+
save_results.append(save_pred)
|
| 179 |
+
|
| 180 |
+
if is_visualize:
|
| 181 |
+
image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
| 182 |
+
boxes = dt_boxes
|
| 183 |
+
txts = [rec_res[i][0] for i in range(len(rec_res))]
|
| 184 |
+
scores = [rec_res[i][1] for i in range(len(rec_res))]
|
| 185 |
+
|
| 186 |
+
draw_img = draw_ocr_box_txt(
|
| 187 |
+
image,
|
| 188 |
+
boxes,
|
| 189 |
+
txts,
|
| 190 |
+
scores,
|
| 191 |
+
drop_score=drop_score,
|
| 192 |
+
font_path=font_path)
|
| 193 |
+
if flag:
|
| 194 |
+
image_file = image_file[:-3] + "png"
|
| 195 |
+
cv2.imwrite(
|
| 196 |
+
os.path.join(draw_img_save_dir, os.path.basename(image_file)),
|
| 197 |
+
draw_img[:, :, ::-1])
|
| 198 |
+
logger.debug("The visualized image saved in {}".format(
|
| 199 |
+
os.path.join(draw_img_save_dir, os.path.basename(image_file))))
|
| 200 |
+
|
| 201 |
+
logger.info("The predict total time is {}".format(time.time() - _st))
|
| 202 |
+
if args.benchmark:
|
| 203 |
+
text_sys.text_detector.autolog.report()
|
| 204 |
+
text_sys.text_recognizer.autolog.report()
|
| 205 |
+
|
| 206 |
+
with open(
|
| 207 |
+
os.path.join(draw_img_save_dir, "system_results.txt"),
|
| 208 |
+
'w',
|
| 209 |
+
encoding='utf-8') as f:
|
| 210 |
+
f.writelines(save_results)
|
| 211 |
+
|
| 212 |
+
class AttributeDict(dict):
|
| 213 |
+
def __getattr__(self, attr):
|
| 214 |
+
return self[attr]
|
| 215 |
+
def __setattr__(self, attr, value):
|
| 216 |
+
self[attr] = value
|
| 217 |
+
|
| 218 |
+
# sysargv = ['--image_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg', '--det_algorithm', 'DB', '--det_model_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer', '--det_limit_side_len', '1024', '--det_db_unclip_ratio', '3.5', '--rec_model_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer', '--rec_char_dict_path', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ppocr_keys.txt', '--use_gpu', 'False', '--enable_mkldnn', 'True', '--vis_font_path', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf']
|
| 219 |
+
# ch
|
| 220 |
+
sysargv = ['--image_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg', '--det_algorithm', 'DB', '--det_model_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer', '--det_limit_side_len', '1024', '--det_db_unclip_ratio', '3.5', '--rec_model_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_PP-OCRv3_rec_infer', '--rec_char_dict_path', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/japan_dict.txt', '--use_gpu', 'False', '--enable_mkldnn', 'True', '--vis_font_path', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf']
|
| 221 |
+
# jp
|
| 222 |
+
args = utility.parse_args(sysargv)
|
| 223 |
+
text_sys = TextSystem(args)
|
| 224 |
+
def rec(img: str | cv2.typing.MatLike):
|
| 225 |
+
|
| 226 |
+
if isinstance(img, (str)):
|
| 227 |
+
img = cv2.imread(img)
|
| 228 |
+
|
| 229 |
+
dt_boxes, rec_res, time_dict = text_sys(img)
|
| 230 |
+
|
| 231 |
+
res = [{
|
| 232 |
+
"transcription": rec_res[idx][0],
|
| 233 |
+
"points": np.array(dt_boxes[idx]).astype(np.int32).tolist(),
|
| 234 |
+
} for idx in range(len(dt_boxes))]
|
| 235 |
+
|
| 236 |
+
pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
| 237 |
+
boxes = dt_boxes
|
| 238 |
+
txts = [rec_res[i][0] for i in range(len(rec_res))]
|
| 239 |
+
scores = [rec_res[i][1] for i in range(len(rec_res))]
|
| 240 |
+
return txts, boxes, scores, pil_image
|
| 241 |
+
|
| 242 |
+
def showBox(txts, boxes, scores, pil_image):
|
| 243 |
+
|
| 244 |
+
draw_img = draw_ocr_box_txt(
|
| 245 |
+
pil_image,
|
| 246 |
+
boxes,
|
| 247 |
+
txts,
|
| 248 |
+
scores,
|
| 249 |
+
drop_score=0.5,
|
| 250 |
+
font_path='PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf'
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
cv2.imshow("result", draw_img)
|
| 254 |
+
cv2.waitKey(0)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
if __name__ == "__main__":
|
| 258 |
+
|
| 259 |
+
# text_detector = predict_det.TextDetector( AttributeDict({"det_algorithm": "DB"}) )
|
| 260 |
+
#text_recognizer = predict_rec.TextRecognizer(args)
|
| 261 |
+
|
| 262 |
+
# img = cv2.imread(image_file)
|
| 263 |
+
# starttime = time.time()
|
| 264 |
+
# dt_boxes, rec_res, time_dict = text_sys(img)
|
| 265 |
+
# elapse = time.time() - starttime
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
"""
|
| 269 |
+
python3 tools/infer/predict_system.py \
|
| 270 |
+
--image_dir="train_data/det/test/25.jpg" \
|
| 271 |
+
--det_algorithm="DB" \
|
| 272 |
+
--det_model_dir="output/det_model" \
|
| 273 |
+
--det_limit_side_len=960 \
|
| 274 |
+
--det_db_unclip_ratio=3.5 \
|
| 275 |
+
--rec_model_dir="output/rec_model/Student" \
|
| 276 |
+
--rec_char_dict_path="train_data/keys.txt" \
|
| 277 |
+
--use_gpu False \
|
| 278 |
+
--enable_mkldnn=True
|
| 279 |
+
|
| 280 |
+
"""
|
| 281 |
+
# import sys
|
| 282 |
+
# sys.argv.append( '--image_dir' )
|
| 283 |
+
# # sys.argv.append( 'train_data/det/test/12.jpg' )
|
| 284 |
+
# sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg' )
|
| 285 |
+
# sys.argv.append( '--det_algorithm' )
|
| 286 |
+
# sys.argv.append( 'DB' )
|
| 287 |
+
# sys.argv.append( '--det_model_dir' )
|
| 288 |
+
# # sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch/output/det_model' ) # 自已训练的
|
| 289 |
+
# sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer' ) # 官方的
|
| 290 |
+
# sys.argv.append( '--det_limit_side_len' )
|
| 291 |
+
# # sys.argv.append( '960' ) # 自已的
|
| 292 |
+
# sys.argv.append( '1024' ) # 官方的
|
| 293 |
+
# sys.argv.append( '--det_db_unclip_ratio' )
|
| 294 |
+
# sys.argv.append( '3.5' )
|
| 295 |
+
# sys.argv.append( '--rec_model_dir' )
|
| 296 |
+
# # sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch/output/rec_model/Student' ) # 自已的
|
| 297 |
+
# sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer' ) # 官方的
|
| 298 |
+
# sys.argv.append( '--rec_char_dict_path' )
|
| 299 |
+
# # sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch/train_data/keys.txt' ) # 自已的
|
| 300 |
+
# sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ppocr_keys.txt' ) # 官方的词表
|
| 301 |
+
# sys.argv.append( '--use_gpu' )
|
| 302 |
+
# sys.argv.append( 'False' )
|
| 303 |
+
# sys.argv.append( '--enable_mkldnn' )
|
| 304 |
+
# sys.argv.append( 'True' )
|
| 305 |
+
# sys.argv.append( '--vis_font_path' )
|
| 306 |
+
# sys.argv.append( 'PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf' )
|
| 307 |
+
|
| 308 |
+
sysargv = ['--image_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg', '--det_algorithm', 'DB', '--det_model_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_det_infer', '--det_limit_side_len', '1024', '--det_db_unclip_ratio', '3.5', '--rec_model_dir', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ch_PP-OCRv3_rec_infer', '--rec_char_dict_path', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/official_models/ppocr_keys.txt', '--use_gpu', 'False', '--enable_mkldnn', 'True', '--vis_font_path', 'PaddleOCR_ali1k_det_rec_300epoch_standalone/fonts/simfang.ttf']
|
| 309 |
+
# args = utility.parse_args()
|
| 310 |
+
args = utility.parse_args(sysargv)
|
| 311 |
+
|
| 312 |
+
text_sys = TextSystem(args)
|
| 313 |
+
img = cv2.imread('PaddleOCR_ali1k_det_rec_300epoch_standalone/train_data/det/train/3.jpg')
|
| 314 |
+
#img = cv2.imread('images/ch.png')
|
| 315 |
+
|
| 316 |
+
dt_boxes, rec_res, time_dict = text_sys(img)
|
| 317 |
+
|
| 318 |
+
res = [{
|
| 319 |
+
"transcription": rec_res[idx][0],
|
| 320 |
+
"points": np.array(dt_boxes[idx]).astype(np.int32).tolist(),
|
| 321 |
+
} for idx in range(len(dt_boxes))]
|
| 322 |
+
|
| 323 |
+
image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
| 324 |
+
boxes = dt_boxes
|
| 325 |
+
txts = [rec_res[i][0] for i in range(len(rec_res))]
|
| 326 |
+
scores = [rec_res[i][1] for i in range(len(rec_res))]
|
| 327 |
+
|
| 328 |
+
font_path = args.vis_font_path
|
| 329 |
+
drop_score = args.drop_score
|
| 330 |
+
draw_img = draw_ocr_box_txt(
|
| 331 |
+
image,
|
| 332 |
+
boxes,
|
| 333 |
+
txts,
|
| 334 |
+
scores,
|
| 335 |
+
drop_score=drop_score,
|
| 336 |
+
font_path=font_path)
|
| 337 |
+
|
| 338 |
+
# 缩放图片, 统一 800 宽
|
| 339 |
+
height, width, colorNum = img.shape
|
| 340 |
+
|
| 341 |
+
newWidth = 800
|
| 342 |
+
if width > newWidth:
|
| 343 |
+
rate = newWidth / width
|
| 344 |
+
newHeight = int(rate * height)
|
| 345 |
+
dim = (newWidth, newHeight)
|
| 346 |
+
img_des = cv2.resize(draw_img, dim, interpolation=cv2.INTER_LINEAR) #img.resize (new OpenCvSharp.Size(0, 0), rate, rate, InterpolationFlags.Linear);
|
| 347 |
+
else:
|
| 348 |
+
img_des = draw_img.copy()
|
| 349 |
+
|
| 350 |
+
cv2.imshow("result", draw_img)
|
| 351 |
+
cv2.waitKey(0)
|
| 352 |
+
|
| 353 |
+
main(args)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
# pip install paddlepaddle "paddleocr==2.7.0.0" -i https://mirror.baidu.com/pypi/simple
|
| 379 |
+
|
| 380 |
+
# apt install python3.10-dev
|
| 381 |
+
|
| 382 |
+
# pip install paddlepaddle "paddleocr==2.7.5" -i https://mirror.baidu.com/pypi/simple
|
| 383 |
+
|
| 384 |
+
# from paddleocr import PaddleOCR, draw_ocr
|
| 385 |
+
|
| 386 |
+
# # `ch`, `en`, `fr`, `german`, `korean`, `japan`
|
| 387 |
+
# ocr = PaddleOCR(use_angle_cls=True, lang="ch") # need to run only once to download and load model into memory
|
| 388 |
+
# img_path = './images/ch.png'
|
| 389 |
+
# result = ocr.ocr(img_path, cls=True)
|
| 390 |
+
# for idx in range(len(result)):
|
| 391 |
+
# res = result[idx]
|
| 392 |
+
# for line in res:
|
| 393 |
+
# print(line)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
|
requirements.txt
CHANGED
|
@@ -1,4 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
numpy==1.26.4
|
| 2 |
opencv-python==4.6.0.66
|
| 3 |
opencv-contrib-python==4.10.0.84
|
| 4 |
pypdf[image]==5.0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
######## jp_ocr begin ####################################################
|
| 4 |
numpy==1.26.4
|
| 5 |
opencv-python==4.6.0.66
|
| 6 |
opencv-contrib-python==4.10.0.84
|
| 7 |
pypdf[image]==5.0.0
|
| 8 |
+
######## jp_ocr end ######################################################
|
| 9 |
+
|
| 10 |
+
######### PaddleOCR_ali1k_det_rec_300epoch begin ########################
|
| 11 |
+
astor==0.8.1
|
| 12 |
+
attrdict==2.0.1
|
| 13 |
+
babel==2.16.0
|
| 14 |
+
bce-python-sdk==0.9.21
|
| 15 |
+
blinker==1.8.2
|
| 16 |
+
cachetools==5.5.0
|
| 17 |
+
certifi==2024.8.30
|
| 18 |
+
charset-normalizer==3.3.2
|
| 19 |
+
click==8.1.7
|
| 20 |
+
contourpy==1.3.0
|
| 21 |
+
cssselect==1.2.0
|
| 22 |
+
cssutils==2.11.1
|
| 23 |
+
cycler==0.12.1
|
| 24 |
+
Cython==3.0.11
|
| 25 |
+
decorator==5.1.1
|
| 26 |
+
et-xmlfile==1.1.0
|
| 27 |
+
Flask==3.0.3
|
| 28 |
+
flask-babel==4.0.0
|
| 29 |
+
fonttools==4.53.1
|
| 30 |
+
future==1.0.0
|
| 31 |
+
idna==3.8
|
| 32 |
+
imageio==2.35.1
|
| 33 |
+
imgaug==0.4.0
|
| 34 |
+
itsdangerous==2.2.0
|
| 35 |
+
Jinja2==3.1.4
|
| 36 |
+
kiwisolver==1.4.5
|
| 37 |
+
lazy_loader==0.4
|
| 38 |
+
lmdb==1.5.1
|
| 39 |
+
lxml==5.3.0
|
| 40 |
+
MarkupSafe==2.1.5
|
| 41 |
+
matplotlib==3.9.2
|
| 42 |
+
more-itertools==10.4.0
|
| 43 |
+
networkx==3.3
|
| 44 |
+
numpy==1.26.4
|
| 45 |
+
opencv-contrib-python==4.10.0.84
|
| 46 |
+
opencv-python==4.6.0.66
|
| 47 |
+
openpyxl==3.1.5
|
| 48 |
+
opt-einsum==3.3.0
|
| 49 |
+
packaging==24.1
|
| 50 |
+
pillow==10.4.0
|
| 51 |
+
premailer==3.10.0
|
| 52 |
+
psutil==6.0.0
|
| 53 |
+
pyclipper==1.3.0.post5
|
| 54 |
+
pycryptodome==3.20.0
|
| 55 |
+
pyparsing==3.1.4
|
| 56 |
+
python-dateutil==2.9.0.post0
|
| 57 |
+
pytz==2024.1
|
| 58 |
+
rapidfuzz==3.9.7
|
| 59 |
+
rarfile==4.2
|
| 60 |
+
requests==2.32.3
|
| 61 |
+
scikit-image==0.24.0
|
| 62 |
+
scipy==1.14.1
|
| 63 |
+
shapely==2.0.6
|
| 64 |
+
six==1.16.0
|
| 65 |
+
tifffile==2024.8.30
|
| 66 |
+
tqdm==4.66.5
|
| 67 |
+
tzdata==2024.1
|
| 68 |
+
urllib3==2.2.2
|
| 69 |
+
Werkzeug==3.0.4
|
| 70 |
+
######### PaddleOCR_ali1k_det_rec_300epoch end ########################
|
| 71 |
+
|
| 72 |
+
|