convert_image.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. # encoding=utf8
  2. import copy
  3. import inspect
  4. import io
  5. import logging
  6. import os
  7. import re
  8. import sys
  9. import time
  10. from glob import glob
  11. import requests
  12. import numpy as np
  13. from PIL import Image
  14. sys.path.append(os.path.dirname(__file__) + "/../")
  15. from pdfminer.layout import LTLine
  16. import traceback
  17. import cv2
  18. from isr.pre_process import count_red_pixel
  19. from format_convert.utils import judge_error_code, add_div, LineTable, get_table_html, get_logger, log, \
  20. memory_decorator, pil_resize, np2bytes, ocr_cant_read, get_garble_code2
  21. from format_convert.convert_need_interface import from_otr_interface, from_ocr_interface, from_gpu_interface_redis, \
  22. from_idc_interface, from_isr_interface
  23. from format_convert.table_correct import get_rotated_image
  24. from botr.extract_table import get_table
  25. def image_process(image_np, image_path, is_from_pdf=False, is_from_docx=False,
  26. b_table_from_text=False, pdf_obj_list=[], pdf_layout_size=()):
  27. from format_convert.convert_tree import _Table, _Sentence
  28. def get_cluster(t_list, b_list, axis):
  29. zip_list = list(zip(t_list, b_list))
  30. if len(zip_list) == 0:
  31. return t_list, b_list
  32. if len(zip_list[0]) > 0:
  33. zip_list.sort(key=lambda x: x[1][axis][1])
  34. cluster_list = []
  35. margin = 5
  36. for text, bbox in zip_list:
  37. _find = 0
  38. for cluster in cluster_list:
  39. if abs(cluster[1] - bbox[axis][1]) <= margin:
  40. cluster[0].append([text, bbox])
  41. cluster[1] = bbox[axis][1]
  42. _find = 1
  43. break
  44. if not _find:
  45. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  46. new_text_list = []
  47. new_bbox_list = []
  48. for cluster in cluster_list:
  49. # print("=============convert_image")
  50. # print("cluster_list", cluster)
  51. center_y = 0
  52. for text, bbox in cluster[0]:
  53. center_y += bbox[axis][1]
  54. center_y = int(center_y / len(cluster[0]))
  55. for text, bbox in cluster[0]:
  56. bbox[axis][1] = center_y
  57. new_text_list.append(text)
  58. new_bbox_list.append(bbox)
  59. # print("cluster_list", cluster)
  60. return new_text_list, new_bbox_list
  61. def merge_textbox(textbox_list, in_objs):
  62. delete_obj = []
  63. threshold = 5
  64. textbox_list.sort(key=lambda x:x.bbox[0])
  65. for k in range(len(textbox_list)):
  66. tb1 = textbox_list[k]
  67. if tb1 not in in_objs and tb1 not in delete_obj:
  68. for m in range(k+1, len(textbox_list)):
  69. tb2 = textbox_list[m]
  70. if tb2 in in_objs:
  71. continue
  72. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  73. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  74. if tb1.bbox[0] <= tb2.bbox[0]:
  75. tb1.text = tb1.text + tb2.text
  76. else:
  77. tb1.text = tb2.text + tb1.text
  78. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  79. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  80. delete_obj.append(tb2)
  81. for _obj in delete_obj:
  82. if _obj in textbox_list:
  83. textbox_list.remove(_obj)
  84. return textbox_list
  85. def idc_process(_image_np, return_angle=False):
  86. # 图片倾斜校正,写入原来的图片路径
  87. # print("image_process", image_path)
  88. # g_r_i = get_rotated_image(_image_np, image_path)
  89. # if judge_error_code(g_r_i):
  90. # if is_from_docx:
  91. # return []
  92. # else:
  93. # return g_r_i
  94. # _image_np = cv2.imread(image_path)
  95. # if _image_np is None:
  96. # return []
  97. # return _image_np
  98. # if _image_np is None:
  99. # return []
  100. # idc模型实现图片倾斜校正
  101. h, w = get_best_predict_size2(_image_np, 1080)
  102. image_resize = pil_resize(_image_np, h, w)
  103. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  104. # cv2.imwrite(image_resize_path, image_resize)
  105. # with open(image_resize_path, "rb") as f:
  106. # image_bytes = f.read()
  107. image_bytes = np2bytes(image_resize)
  108. angle = from_idc_interface(image_bytes)
  109. log('idc_process angle ' + str(angle))
  110. if judge_error_code(angle):
  111. if return_angle:
  112. if is_from_docx:
  113. return [], []
  114. else:
  115. return angle, angle
  116. else:
  117. if is_from_docx:
  118. return []
  119. else:
  120. return angle
  121. # 根据角度旋转
  122. _image_pil = Image.fromarray(_image_np)
  123. _image_np = np.array(_image_pil.rotate(angle, expand=1))
  124. # 写入
  125. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  126. # cv2.imwrite(idc_path, image_np)
  127. if return_angle:
  128. return _image_np, angle
  129. return _image_np
  130. def isr_process(_image_np):
  131. log("isr_process image shape " + str(_image_np.shape))
  132. image_np_copy = copy.deepcopy(_image_np)
  133. # isr模型去除印章
  134. _isr_time = time.time()
  135. if count_red_pixel(_image_np):
  136. # 红色像素达到一定值才过模型
  137. image_bytes = np2bytes(_image_np)
  138. _image_np = from_isr_interface(image_bytes)
  139. if judge_error_code(_image_np):
  140. if is_from_docx:
  141. return []
  142. else:
  143. return _image_np
  144. # [1]代表检测不到印章,直接返回
  145. if isinstance(_image_np, list) and _image_np == [1]:
  146. log("no seals detected!")
  147. _image_np = image_np_copy
  148. log("isr total time "+str(time.time()-_isr_time))
  149. return _image_np
  150. def ocr_process(_image_np, _threshold=2048):
  151. log("ocr_process image shape " + str(_image_np.shape))
  152. # ocr图片过大内存溢出,需resize
  153. # 大图按比例缩小,小图维持不变;若统一拉伸成固定大小如1024会爆显存
  154. ratio = (1, 1)
  155. if _image_np.shape[0] > _threshold or _image_np.shape[1] > _threshold:
  156. best_h, best_w = get_best_predict_size2(_image_np, _threshold)
  157. _image_np = pil_resize(_image_np, best_h, best_w)
  158. log("ocr_process image resize " + str(_image_np.shape))
  159. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  160. # 大图片ocr加锁,防止爆显存
  161. # if _image_np.shape[0] >= 1024 and _image_np.shape[1] >= 1024:
  162. # file_lock = True
  163. # else:
  164. # file_lock = False
  165. # 调用ocr模型接口
  166. image_bytes = np2bytes(_image_np)
  167. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=1)
  168. if judge_error_code(text_list):
  169. return text_list, text_list
  170. for i in range(len(bbox_list)):
  171. point = bbox_list[i]
  172. bbox_list[i] = [[int(point[0][0]*ratio[0]), int(point[0][1]*ratio[1])],
  173. [int(point[1][0]*ratio[0]), int(point[1][1]*ratio[1])],
  174. [int(point[2][0]*ratio[0]), int(point[2][1]*ratio[1])],
  175. [int(point[3][0]*ratio[0]), int(point[3][1]*ratio[1])]]
  176. # 去除水印字 根据识别是否为矩形框
  177. temp_text_list = []
  178. temp_bbox_list = []
  179. for i in range(len(bbox_list)):
  180. bbox = bbox_list[i]
  181. text = text_list[i]
  182. if len(re.findall('[\u4e00-\u9fa5]', text)) == len(text):
  183. if (abs(bbox[0][1] - bbox[1][1]) <= 2 and abs(bbox[2][1] - bbox[3][1]) <= 2) \
  184. or (abs(bbox[0][0] - bbox[3][0]) <= 4 and abs(bbox[2][0] - bbox[1][0]) <= 4):
  185. temp_text_list.append(text)
  186. temp_bbox_list.append(bbox)
  187. else:
  188. temp_text_list.append(text)
  189. temp_bbox_list.append(bbox)
  190. text_list = temp_text_list
  191. bbox_list = temp_bbox_list
  192. return text_list, bbox_list
  193. def otr_process(_image_np):
  194. log("otr_process image shape " + str(_image_np.shape))
  195. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  196. best_h, best_w = get_best_predict_size(_image_np)
  197. image_resize = pil_resize(_image_np, best_h, best_w)
  198. # image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  199. # cv2.imwrite(image_resize_path, image_resize)
  200. # 调用otr模型接口
  201. # with open(image_resize_path, "rb") as f:
  202. # image_bytes = f.read()
  203. image_bytes = np2bytes(image_resize)
  204. list_line = from_otr_interface(image_bytes, is_from_pdf)
  205. if judge_error_code(list_line):
  206. if is_from_docx:
  207. return []
  208. else:
  209. return list_line
  210. # otr resize后得到的bbox根据比例还原
  211. start_time = time.time()
  212. ratio = (_image_np.shape[0]/best_h, _image_np.shape[1]/best_w)
  213. for i in range(len(list_line)):
  214. point = list_line[i]
  215. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  216. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  217. log("otr resize bbox recover " + str(time.time()-start_time))
  218. return list_line
  219. def botr_process(_image_np, table_list2, text_list2, box_list2, text_box_list2, obj_in_table_list2,
  220. from_pdf=False, pdf_obj_list=[], pdf_layout_size=()):
  221. if from_pdf:
  222. # 交叉验证 ocr结果与pdf obj,暂时使用pdf提取的
  223. h_ratio = _image_np.shape[0] / pdf_layout_size[1]
  224. w_ratio = _image_np.shape[1] / pdf_layout_size[0]
  225. pdf_text_list = []
  226. pdf_box_list = []
  227. for obj in pdf_obj_list:
  228. # pdf坐标是上下颠倒的
  229. obj.bbox = (obj.bbox[0], pdf_layout_size[1]-obj.bbox[1],
  230. obj.bbox[2], pdf_layout_size[1]-obj.bbox[3])
  231. # 根据两个页面大小比例调整坐标
  232. obj.bbox = (obj.bbox[0]*w_ratio, obj.bbox[1]*h_ratio,
  233. obj.bbox[2]*w_ratio, obj.bbox[3]*h_ratio)
  234. # 剔除水印字
  235. text = re.sub('[\n ]', '', obj.get_text())
  236. if len(text) == 1 and abs(obj.bbox[0] - obj.bbox[2]) >= 70:
  237. continue
  238. pdf_box_list.append([[int(obj.bbox[0]), int(obj.bbox[3])],
  239. [],
  240. [int(obj.bbox[2]), int(obj.bbox[1])],
  241. []
  242. ])
  243. pdf_text_list.append(re.sub('[\n]', '', obj.get_text()))
  244. pdf_text_box_list = get_text_box_obj(pdf_text_list, pdf_box_list)
  245. text_list2 = pdf_text_list
  246. box_list2 = pdf_box_list
  247. text_box_list2 = pdf_text_box_list
  248. _text_box_list, _table_list, _obj_in_table_list = get_table(_image_np, table_list2, text_list2, box_list2, text_box_list2)
  249. # 保存无边框表格文件
  250. if _table_list:
  251. try:
  252. save_b_table(_image_np, text_box_list2, from_pdf)
  253. except:
  254. pass
  255. # print('_text_box_list', _text_box_list)
  256. # print('_table_list', _table_list)
  257. if from_pdf:
  258. text_box_list2 = []
  259. table_list2 = []
  260. if _table_list and _text_box_list:
  261. text_box_list2 += _text_box_list
  262. text_box_list2 = list(set(text_box_list2))
  263. # table_list2 += _table_list
  264. # obj_in_table_list2 = obj_in_table_list2.union(_obj_in_table_list)
  265. return text_box_list2, _table_list, _obj_in_table_list
  266. def table_process(list_line, list_text_boxes, _image_np):
  267. # 调用现成方法形成表格
  268. try:
  269. if list_line:
  270. # 排除掉短且经过文字bbox中间的竖线
  271. temp_list = []
  272. for line in list_line:
  273. find_cnt = 0
  274. if abs(line[0]-line[2]) < abs(line[1]-line[3]) and abs(line[1] - line[3]) <= _image_np.shape[0] / 20:
  275. for t_obj in list_text_boxes:
  276. if abs(t_obj.bbox[0]-t_obj.bbox[2])/5 + min(t_obj.bbox[0], t_obj.bbox[2]) <= line[0] <= abs(t_obj.bbox[0]-t_obj.bbox[2])/5*4 + min(t_obj.bbox[0], t_obj.bbox[2]) and (t_obj.bbox[0]-t_obj.bbox[2]) <= 60:
  277. # print('match', line[0], t_obj.bbox[0], t_obj.bbox[2])
  278. find_cnt += 1
  279. if find_cnt >= 2:
  280. break
  281. if find_cnt >= 2:
  282. continue
  283. temp_list.append(line)
  284. list_line = temp_list
  285. from format_convert.convert_tree import TableLine
  286. list_lines = []
  287. for line in list_line:
  288. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  289. lt = LineTable()
  290. tables, obj_in_table, _, connect_textbox_list = lt.recognize_table(list_text_boxes, list_lines,
  291. sourceP_LB=False, splited=False,
  292. from_pdf=is_from_pdf)
  293. # 需分割textbox
  294. if connect_textbox_list:
  295. list_text_boxes = table_textbox_split(_image_np, connect_textbox_list, list_text_boxes)
  296. # 新的textbox,重新做表格
  297. tables, obj_in_table, _, connect_textbox_list = lt.recognize_table(list_text_boxes, list_lines,
  298. sourceP_LB=False, splited=True,
  299. from_pdf=is_from_pdf)
  300. if not tables:
  301. return list_text_boxes, tables, obj_in_table
  302. return list_text_boxes, tables, obj_in_table
  303. else:
  304. return list_text_boxes, [], set()
  305. except:
  306. traceback.print_exc()
  307. return [-8], [-8], [-8]
  308. def get_text_box_obj(_text_list, _bbox_list):
  309. from format_convert.convert_tree import TextBox
  310. _text_box_list = []
  311. for i in range(len(_bbox_list)):
  312. bbox = _bbox_list[i]
  313. b_text = _text_list[i]
  314. _text_box_list.append(TextBox([bbox[0][0], bbox[0][1],
  315. bbox[2][0], bbox[2][1]], b_text))
  316. return _text_box_list
  317. def save_b_table(image_np2, text_box_list2, from_pdf=False):
  318. _start_time = time.time()
  319. _path = '/data/fangjiasheng/format_conversion_maxcompute/save_b_table'
  320. # _path = 'D:/Project/format_conversion_maxcompute/save_b_table'
  321. max_index = 20000
  322. if os.path.exists(_path):
  323. file_list = glob(_path + '/*')
  324. if file_list:
  325. file_index_list = [int(re.split('[/.\\\\-]', x)[-3]) for x in file_list]
  326. file_index_list.sort(key=lambda x: x)
  327. index = file_index_list[-1] + 1
  328. else:
  329. index = 0
  330. if index > max_index:
  331. return
  332. # 文件md5
  333. from format_convert import _global
  334. _md5 = _global.get("md5")
  335. _image_path = _path + '/' + str(index) + '-' + str(_md5) + '.png'
  336. cv2.imwrite(_image_path, image_np2)
  337. log('save b_table image success!')
  338. # if from_pdf:
  339. # _file_path = _path + '/' + str(_md5) + '-' + str(index) + '.txt'
  340. # new_text_box_list2 = [str(x) + '\n' for x in text_box_list2]
  341. # with open(_file_path, 'w') as f:
  342. # f.writelines(new_text_box_list2)
  343. # log('save b_table txt success!')
  344. log('save_b_table cost: ' + str(time.time()-_start_time))
  345. def table_textbox_split(image_np2, connect_textbox_list, textbox_list):
  346. """
  347. 两个单元格里的文本被ocr识别为一个,需分开才能准确放进表格
  348. :return:
  349. """
  350. split_bbox_list = []
  351. split_text_list = []
  352. splited_textbox_list = []
  353. for textbox in connect_textbox_list:
  354. bbox = textbox.bbox
  355. bbox = [[bbox[0], bbox[1]], [], [bbox[2], bbox[3]], []]
  356. sub_image_np = image_np2[int(bbox[0][1]):int(bbox[2][1]), int(bbox[0][0]):int(bbox[2][0]), :]
  357. split_index_list = []
  358. # 从左到右遍历img
  359. for i in range(5, sub_image_np.shape[1]-5):
  360. # 找表格分割线,这一列都为黑色像素
  361. if np.where(sub_image_np[:, i, 0] < 200)[0].size >= sub_image_np.shape[0]:
  362. split_index_list.append(i)
  363. # 判断两线之间宽度,去重
  364. if len(split_index_list) > 1:
  365. last_index = split_index_list[0]
  366. temp_list = []
  367. delete_list = []
  368. for index in split_index_list[1:]:
  369. if index in delete_list:
  370. continue
  371. if index - last_index <= 5:
  372. delete_list.append(index)
  373. else:
  374. last_index = index
  375. temp_list.append(last_index)
  376. split_index_list = temp_list
  377. # n条以上分割线,有问题
  378. if len(split_index_list) == 0 or len(split_index_list) >= 2:
  379. # print('len(split_index_list)', len(split_index_list), split_index_list)
  380. continue
  381. else:
  382. # 根据index拆开图片,重新ocr
  383. split_index_list.insert(0, 0)
  384. print('split_index_list1', split_index_list)
  385. for _i, index in enumerate(split_index_list):
  386. if _i == len(split_index_list) - 1:
  387. split_image_np = sub_image_np[:, index:, :]
  388. split_bbox_list.append([[bbox[0][0]+index, bbox[0][1]], [], [bbox[2][0], bbox[2][1]], []])
  389. else:
  390. next_index = split_index_list[_i+1]
  391. split_image_np = sub_image_np[:, index:next_index, :]
  392. split_bbox_list.append([[bbox[0][0]+index, bbox[0][1]], [], [bbox[0][0]+next_index, bbox[2][1]], []])
  393. # ocr
  394. split_image_bytes = np2bytes(split_image_np)
  395. text_list2, bbox_list2 = from_ocr_interface(split_image_bytes, is_table=1, only_rec=1)
  396. # print('text_list2', text_list2)
  397. # print('bbox_list2', split_bbox_list)
  398. if judge_error_code(text_list2):
  399. text2 = ''
  400. else:
  401. if text_list2:
  402. text2 = text_list2[0]
  403. else:
  404. text2 = ''
  405. split_text_list.append(text2)
  406. splited_textbox_list.append(textbox)
  407. if split_text_list and split_bbox_list:
  408. split_textbox_list = get_text_box_obj(split_text_list, split_bbox_list)
  409. for tb in splited_textbox_list:
  410. if tb in textbox_list:
  411. textbox_list.remove(tb)
  412. textbox_list += split_textbox_list
  413. return textbox_list
  414. log("into image_preprocess")
  415. try:
  416. if image_np is None:
  417. log("image_preprocess image_np is None")
  418. return []
  419. if image_np.shape[0] <= 20 or image_np.shape[1] <= 20:
  420. log('image_np.shape[0] <= 20 or image_np.shape[1] <= 20')
  421. return []
  422. if not b_table_from_text:
  423. # 判断是否需要长图分割
  424. slice_flag = need_image_slice(image_np)
  425. log("need_image_slice " + str(slice_flag) + " " + str(image_np.shape))
  426. idc_flag = False
  427. image_np_list = [image_np]
  428. if slice_flag:
  429. # 方向分类
  430. image_np = idc_process(image_np)
  431. idc_flag = True
  432. if isinstance(image_np, list):
  433. return image_np
  434. # 再判断
  435. if need_image_slice(image_np):
  436. # 长图分割
  437. image_np_list = image_slice_new(image_np)
  438. if len(image_np_list) < 1:
  439. log("image_slice failed!")
  440. image_np_list = [image_np]
  441. # return [-10]
  442. all_obj_list = []
  443. _add_y = 0
  444. for image_np in image_np_list:
  445. # print("sub image shape", image_np.shape)
  446. # 整体分辨率限制
  447. threshold = 2048
  448. if image_np.shape[0] > threshold or image_np.shape[1] > threshold:
  449. h, w = get_best_predict_size2(image_np, threshold=threshold)
  450. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  451. image_np = pil_resize(image_np, h, w)
  452. # 印章去除
  453. image_np = isr_process(image_np)
  454. if isinstance(image_np, list):
  455. return image_np
  456. # 文字识别
  457. text_list, box_list = ocr_process(image_np)
  458. if judge_error_code(text_list):
  459. return text_list
  460. # 判断ocr识别是否正确
  461. if ocr_cant_read(text_list, box_list) and not idc_flag:
  462. # if True:
  463. # 方向分类
  464. image_np, angle = idc_process(image_np, return_angle=True)
  465. if isinstance(image_np, list):
  466. return image_np
  467. # 如果角度不变,旋转180
  468. if angle in [0, 360]:
  469. image_pil = Image.fromarray(image_np)
  470. image_np = np.array(image_pil.rotate(180, expand=1))
  471. # cv2.imshow("idc_process", image_np)
  472. # cv2.waitKey(0)
  473. # 文字识别
  474. text_list1, box_list_1 = ocr_process(image_np)
  475. if judge_error_code(text_list1):
  476. return text_list1
  477. # all_text = ''.join(text_list1)
  478. # all_text = re.sub('[\s\d]', '', all_text)
  479. # if len(re.findall(get_garble_code2(), all_text)) >= 2:
  480. # log('text_list1' + ''.join(text_list1))
  481. if len(text_list1) > 0 and ocr_cant_read(text_list1, box_list_1) and is_from_pdf:
  482. return [-16]
  483. # 比较字数
  484. # print("ocr process", len("".join(text_list)), len("".join(text_list1)))
  485. if len("".join(text_list)) < len("".join(text_list1)):
  486. text_list = text_list1
  487. box_list = box_list_1
  488. # 表格识别
  489. line_list = otr_process(image_np)
  490. if judge_error_code(line_list):
  491. return line_list
  492. # 生成TextBox对象
  493. text_box_list = get_text_box_obj(text_list, box_list)
  494. # 表格生成
  495. text_box_list, table_list, obj_in_table_list = table_process(line_list, text_box_list, image_np)
  496. if judge_error_code(table_list):
  497. return table_list
  498. # 无边框表格识别
  499. start_time = time.time()
  500. text_box_list, b_table_list, b_obj_in_table_list = botr_process(image_np, table_list,
  501. text_list, box_list,
  502. text_box_list,
  503. obj_in_table_list,
  504. b_table_from_text,
  505. pdf_obj_list,
  506. pdf_layout_size,
  507. )
  508. log('botr process cost: ' + str(time.time()-start_time))
  509. # 合并非表格的同一行TextBox
  510. text_box_list = merge_textbox(text_box_list, obj_in_table_list)
  511. # 对象生成
  512. obj_list = []
  513. for table in table_list:
  514. _table = _Table(table["table"], table["bbox"])
  515. obj_list.append(_table)
  516. for table in b_table_list:
  517. _table = _Table(table["table"], table["bbox"])
  518. obj_list.append(_table)
  519. _table.y += 10000
  520. for text_box in text_box_list:
  521. if text_box not in obj_in_table_list:
  522. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  523. # 多图修正y
  524. if len(image_np_list) > 1:
  525. list_y = []
  526. for obj in obj_list:
  527. obj.y += _add_y
  528. list_y.append(obj.y)
  529. if len(list_y) > 0:
  530. _add_y = max(list_y)
  531. # 合并
  532. all_obj_list += obj_list
  533. else:
  534. all_obj_list = []
  535. table_list = []
  536. text_list = []
  537. box_list = []
  538. text_box_list = []
  539. obj_in_table_list = set()
  540. # 表格识别
  541. line_list = otr_process(image_np)
  542. if judge_error_code(line_list):
  543. return line_list
  544. # 生成TextBox对象
  545. text_box_list = get_text_box_obj(text_list, box_list)
  546. # 表格生成
  547. text_box_list, table_list, obj_in_table_list = table_process(line_list, text_box_list, image_np)
  548. if judge_error_code(table_list):
  549. return table_list
  550. # 无边框表格识别
  551. start_time = time.time()
  552. text_box_list, table_list, obj_in_table_list = botr_process(image_np, table_list,
  553. text_list, box_list,
  554. text_box_list,
  555. obj_in_table_list,
  556. b_table_from_text,
  557. pdf_obj_list,
  558. pdf_layout_size,
  559. )
  560. log('botr process cost: ' + str(time.time()-start_time))
  561. # 合并非表格的同一行TextBox
  562. text_box_list = merge_textbox(text_box_list, obj_in_table_list)
  563. # 对象生成
  564. obj_list = []
  565. # print('table_list', table_list)
  566. for table in table_list:
  567. _table = _Table(table["table"], table["bbox"])
  568. obj_list.append(_table)
  569. for text_box in text_box_list:
  570. if text_box not in obj_in_table_list:
  571. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  572. # 合并
  573. all_obj_list += obj_list
  574. return all_obj_list
  575. except Exception as e:
  576. log("image_preprocess error")
  577. traceback.print_exc()
  578. return [-1]
  579. @memory_decorator
  580. def picture2text(path, html=False):
  581. log("into picture2text")
  582. try:
  583. # 判断图片中表格
  584. img = cv2.imread(path)
  585. if img is None:
  586. return [-3]
  587. text = image_process(img, path)
  588. if judge_error_code(text):
  589. return text
  590. if html:
  591. text = add_div(text)
  592. return [text]
  593. except Exception as e:
  594. log("picture2text error!")
  595. print("picture2text", traceback.print_exc())
  596. return [-1]
  597. def get_best_predict_size(image_np, times=64):
  598. sizes = []
  599. for i in range(1, 100):
  600. if i*times <= 1300:
  601. sizes.append(i*times)
  602. sizes.sort(key=lambda x: x, reverse=True)
  603. min_len = 10000
  604. best_height = sizes[0]
  605. for height in sizes:
  606. if abs(image_np.shape[0] - height) < min_len:
  607. min_len = abs(image_np.shape[0] - height)
  608. best_height = height
  609. min_len = 10000
  610. best_width = sizes[0]
  611. for width in sizes:
  612. if abs(image_np.shape[1] - width) < min_len:
  613. min_len = abs(image_np.shape[1] - width)
  614. best_width = width
  615. return best_height, best_width
  616. def get_best_predict_size2(image_np, threshold=3000):
  617. h, w = image_np.shape[:2]
  618. scale = threshold / max(h, w)
  619. h = int(h * scale)
  620. w = int(w * scale)
  621. return h, w
  622. def image_slice(image_np):
  623. """
  624. slice the image if the height is to large
  625. :return:
  626. """
  627. _sum = np.average(image_np, axis=1)
  628. list_white_line = []
  629. list_ave = list(_sum)
  630. for _i in range(len(list_ave)):
  631. if (list_ave[_i] > 250).all():
  632. list_white_line.append(_i)
  633. set_white_line = set(list_white_line)
  634. width = image_np.shape[1]
  635. height = image_np.shape[0]
  636. list_images = []
  637. _begin = 0
  638. _end = 0
  639. while 1:
  640. if _end > height:
  641. break
  642. _end += width
  643. while 1:
  644. if _begin in set_white_line:
  645. break
  646. if _begin > height:
  647. break
  648. _begin += 1
  649. _image = image_np[_begin:_end, ...]
  650. list_images.append(_image)
  651. _begin = _end
  652. log("image_slice into %d parts" % (len(list_images)))
  653. return list_images
  654. def image_slice_new(image_np):
  655. """
  656. 长图分割
  657. :return:
  658. """
  659. height, width = image_np.shape[:2]
  660. image_origin = copy.deepcopy(image_np)
  661. # 去除黑边
  662. image_np = remove_black_border(image_np)
  663. # 1. 转化成灰度图
  664. image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
  665. # 2. 二值化
  666. ret, binary = cv2.threshold(image_np, 125, 255, cv2.THRESH_BINARY_INV)
  667. # 3. 膨胀和腐蚀操作的核函数
  668. kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  669. # 4. 膨胀一次,让轮廓突出
  670. dilation = cv2.dilate(binary, kernal, iterations=1)
  671. # dilation = np.add(np.int0(np.full(dilation.shape, 255)), -1 * np.int0(dilation))
  672. # dilation = np.uint8(dilation)
  673. # cv2.namedWindow("dilation", 0)
  674. # cv2.resizeWindow("dilation", 1000, 800)
  675. # cv2.imshow("dilation", dilation)
  676. # cv2.waitKey(0)
  677. # cv2.imwrite("error.jpg", dilation)
  678. # 按行求平均
  679. width_avg = np.average(np.float32(dilation), axis=1)
  680. zero_index = np.where(width_avg == 0.)[0]
  681. # print(height, width)
  682. # print(width_avg)
  683. # print(width_avg.shape)
  684. # print(zero_index)
  685. # print(zero_index.shape)
  686. # zero_index.sort(key=lambda x: x)
  687. # 截取范围内寻找分割点
  688. max_distance = int(width / 2)
  689. image_list = []
  690. last_h = 0
  691. for i in range(height // width + 1):
  692. h = last_h + width
  693. # 前后的分割点
  694. zero_h_after = zero_index[np.where(zero_index >= h)]
  695. zero_h_before = zero_index[np.where(zero_index <= h)]
  696. # print("last_h, h", last_h, h)
  697. # print("last_h, h", last_h, h)
  698. # print(zero_index.shape)
  699. # print("zero_h_after.shape", zero_h_after.shape)
  700. if zero_h_after.shape[0] == 0:
  701. # 最后一截
  702. last_image = image_origin[last_h:, :, :]
  703. if last_image.shape[0] <= max_distance:
  704. image_list[-1] = np.concatenate([image_list[-1], last_image], axis=0)
  705. else:
  706. image_list.append(last_image)
  707. break
  708. # 分割点距离不能太远
  709. cut_h = zero_h_after.tolist()[0]
  710. # print("cut_h", cut_h)
  711. if abs(h - cut_h) <= max_distance:
  712. image_list.append(image_origin[last_h:cut_h, :, :])
  713. last_h = cut_h
  714. # 后面找不到往前找
  715. else:
  716. cut_h = zero_h_before.tolist()[-1]
  717. if abs(cut_h - h) <= max_distance:
  718. image_list.append(image_origin[last_h:cut_h, :, :])
  719. last_h = cut_h
  720. # i = 0
  721. # for im in image_list:
  722. # print(im.shape)
  723. # cv2.imwrite("error" + str(i) + ".jpg", im)
  724. # i += 1
  725. # cv2.namedWindow("im", 0)
  726. # cv2.resizeWindow("im", 1000, 800)
  727. # cv2.imshow("im", im)
  728. # cv2.waitKey(0)
  729. log("image_slice into %d parts" % (len(image_list)))
  730. return image_list
  731. def need_image_slice(image_np):
  732. h, w = image_np.shape[:2]
  733. # if h > 3000 and w < 2000:
  734. # return True
  735. if 2. <= h / w and w >= 100:
  736. return True
  737. return False
  738. def remove_black_border(img_np):
  739. try:
  740. # 阈值
  741. threshold = 100
  742. # 转换为灰度图像
  743. gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
  744. # 获取图片尺寸
  745. h, w = gray.shape[:2]
  746. # 无法区分黑色区域超过一半的情况
  747. rowc = gray[:, int(1/2*w)]
  748. colc = gray[int(1/2*h), :]
  749. rowflag = np.argwhere(rowc > threshold)
  750. colflag = np.argwhere(colc > threshold)
  751. left, bottom, right, top = rowflag[0, 0], colflag[-1, 0], rowflag[-1, 0], colflag[0, 0]
  752. # cv2.imshow('remove_black_border', img_np[left:right, top:bottom, :])
  753. # cv2.waitKey()
  754. return img_np[left:right, top:bottom, :]
  755. except:
  756. return img_np
  757. class ImageConvert:
  758. def __init__(self, path, unique_type_dir):
  759. from format_convert.convert_tree import _Document
  760. self._doc = _Document(path)
  761. self.path = path
  762. self.unique_type_dir = unique_type_dir
  763. def init_package(self):
  764. # 各个包初始化
  765. try:
  766. with open(self.path, "rb") as f:
  767. self.image = f.read()
  768. except:
  769. log("cannot open image!")
  770. traceback.print_exc()
  771. self._doc.error_code = [-3]
  772. def convert(self):
  773. from format_convert.convert_tree import _Page, _Image
  774. self.init_package()
  775. if self._doc.error_code is not None:
  776. return
  777. _page = _Page(None, 0)
  778. _image = _Image(self.image, self.path)
  779. _page.add_child(_image)
  780. self._doc.add_child(_page)
  781. def get_html(self):
  782. try:
  783. self.convert()
  784. except:
  785. traceback.print_exc()
  786. self._doc.error_code = [-1]
  787. if self._doc.error_code is not None:
  788. return self._doc.error_code
  789. return self._doc.get_html()
  790. def image_process_old(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  791. from format_convert.convert_tree import _Table, _Sentence
  792. def get_cluster(t_list, b_list, axis):
  793. zip_list = list(zip(t_list, b_list))
  794. if len(zip_list) == 0:
  795. return t_list, b_list
  796. if len(zip_list[0]) > 0:
  797. zip_list.sort(key=lambda x: x[1][axis][1])
  798. cluster_list = []
  799. margin = 5
  800. for text, bbox in zip_list:
  801. _find = 0
  802. for cluster in cluster_list:
  803. if abs(cluster[1] - bbox[axis][1]) <= margin:
  804. cluster[0].append([text, bbox])
  805. cluster[1] = bbox[axis][1]
  806. _find = 1
  807. break
  808. if not _find:
  809. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  810. new_text_list = []
  811. new_bbox_list = []
  812. for cluster in cluster_list:
  813. # print("=============convert_image")
  814. # print("cluster_list", cluster)
  815. center_y = 0
  816. for text, bbox in cluster[0]:
  817. center_y += bbox[axis][1]
  818. center_y = int(center_y / len(cluster[0]))
  819. for text, bbox in cluster[0]:
  820. bbox[axis][1] = center_y
  821. new_text_list.append(text)
  822. new_bbox_list.append(bbox)
  823. # print("cluster_list", cluster)
  824. return new_text_list, new_bbox_list
  825. def merge_textbox(textbox_list, in_objs):
  826. delete_obj = []
  827. threshold = 5
  828. textbox_list.sort(key=lambda x:x.bbox[0])
  829. for k in range(len(textbox_list)):
  830. tb1 = textbox_list[k]
  831. if tb1 not in in_objs and tb1 not in delete_obj:
  832. for m in range(k+1, len(textbox_list)):
  833. tb2 = textbox_list[m]
  834. if tb2 in in_objs:
  835. continue
  836. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  837. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  838. if tb1.bbox[0] <= tb2.bbox[0]:
  839. tb1.text = tb1.text + tb2.text
  840. else:
  841. tb1.text = tb2.text + tb1.text
  842. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  843. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  844. delete_obj.append(tb2)
  845. for _obj in delete_obj:
  846. if _obj in textbox_list:
  847. textbox_list.remove(_obj)
  848. return textbox_list
  849. log("into image_preprocess")
  850. try:
  851. if image_np is None:
  852. return []
  853. # 整体分辨率限制
  854. if image_np.shape[0] > 2000 or image_np.shape[1] > 2000:
  855. h, w = get_best_predict_size2(image_np, threshold=2000)
  856. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  857. image_np = pil_resize(image_np, h, w)
  858. # 图片倾斜校正,写入原来的图片路径
  859. # print("image_process", image_path)
  860. g_r_i = get_rotated_image(image_np, image_path)
  861. if judge_error_code(g_r_i):
  862. if is_from_docx:
  863. return []
  864. else:
  865. return g_r_i
  866. image_np = cv2.imread(image_path)
  867. image_np_copy = copy.deepcopy(image_np)
  868. if image_np is None:
  869. return []
  870. # if image_np is None:
  871. # return []
  872. #
  873. # # idc模型实现图片倾斜校正
  874. # image_resize = pil_resize(image_np, 640, 640)
  875. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  876. # cv2.imwrite(image_resize_path, image_resize)
  877. #
  878. # with open(image_resize_path, "rb") as f:
  879. # image_bytes = f.read()
  880. # angle = from_idc_interface(image_bytes)
  881. # if judge_error_code(angle):
  882. # if is_from_docx:
  883. # return []
  884. # else:
  885. # return angle
  886. # # 根据角度旋转
  887. # image_pil = Image.fromarray(image_np)
  888. # image_np = np.array(image_pil.rotate(angle, expand=1))
  889. # # 写入
  890. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  891. # cv2.imwrite(idc_path, image_np)
  892. # isr模型去除印章
  893. _isr_time = time.time()
  894. if count_red_pixel(image_np):
  895. # 红色像素达到一定值才过模型
  896. with open(image_path, "rb") as f:
  897. image_bytes = f.read()
  898. image_np = from_isr_interface(image_bytes)
  899. if judge_error_code(image_np):
  900. if is_from_docx:
  901. return []
  902. else:
  903. return image_np
  904. # [1]代表检测不到印章,直接返回
  905. if isinstance(image_np, list) and image_np == [1]:
  906. log("no seals detected!")
  907. image_np = image_np_copy
  908. else:
  909. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  910. cv2.imwrite(isr_path, image_np)
  911. log("isr total time "+str(time.time()-_isr_time))
  912. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  913. best_h, best_w = get_best_predict_size(image_np)
  914. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  915. image_resize = pil_resize(image_np, best_h, best_w)
  916. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  917. cv2.imwrite(image_resize_path, image_resize)
  918. # 调用otr模型接口
  919. with open(image_resize_path, "rb") as f:
  920. image_bytes = f.read()
  921. list_line = from_otr_interface(image_bytes, is_from_pdf)
  922. if judge_error_code(list_line):
  923. return list_line
  924. # # 预处理
  925. # if is_from_pdf:
  926. # prob = 0.2
  927. # else:
  928. # prob = 0.5
  929. # with open(image_resize_path, "rb") as f:
  930. # image_bytes = f.read()
  931. # img_new, inputs = table_preprocess(image_bytes, prob)
  932. # if type(img_new) is list and judge_error_code(img_new):
  933. # return img_new
  934. # log("img_new.shape " + str(img_new.shape))
  935. #
  936. # # 调用模型运行接口
  937. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  938. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  939. # if judge_error_code(result):
  940. # logging.error("from_gpu_interface failed! " + str(result))
  941. # raise requests.exceptions.RequestException
  942. #
  943. # pred = result.get("preds")
  944. # gpu_time = result.get("gpu_time")
  945. # log("otr model predict time " + str(gpu_time))
  946. #
  947. # # # 解压numpy
  948. # # decompressed_array = io.BytesIO()
  949. # # decompressed_array.write(pred)
  950. # # decompressed_array.seek(0)
  951. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  952. # # log("inputs.shape" + str(pred.shape))
  953. #
  954. # 调用gpu共享内存处理
  955. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  956. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  957. # if judge_error_code(result):
  958. # logging.error("from_gpu_interface failed! " + str(result))
  959. # raise requests.exceptions.RequestException
  960. #
  961. # pred = result.get("preds")
  962. # gpu_time = result.get("gpu_time")
  963. # log("otr model predict time " + str(gpu_time))
  964. #
  965. # # 后处理
  966. # list_line = table_postprocess(img_new, pred, prob)
  967. # log("len(list_line) " + str(len(list_line)))
  968. # if judge_error_code(list_line):
  969. # return list_line
  970. # otr resize后得到的bbox根据比例还原
  971. start_time = time.time()
  972. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  973. for i in range(len(list_line)):
  974. point = list_line[i]
  975. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  976. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  977. log("otr resize bbox recover " + str(time.time()-start_time))
  978. # ocr图片过大内存溢出,需resize
  979. start_time = time.time()
  980. threshold = 3000
  981. ocr_resize_flag = 0
  982. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  983. ocr_resize_flag = 1
  984. best_h, best_w = get_best_predict_size2(image_np, threshold)
  985. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  986. image_resize = pil_resize(image_np, best_h, best_w)
  987. log("ocr_process image resize " + str(image_resize.shape))
  988. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  989. cv2.imwrite(image_resize_path, image_resize)
  990. log("ocr resize before " + str(time.time()-start_time))
  991. # 调用ocr模型接口
  992. with open(image_resize_path, "rb") as f:
  993. image_bytes = f.read()
  994. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=1)
  995. if judge_error_code(text_list):
  996. return text_list
  997. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  998. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  999. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  1000. # # 循环每张图片识别结果
  1001. # text_list = []
  1002. # bbox_list = []
  1003. # for line in results:
  1004. # # print("ocr_interface line", line)
  1005. # text_list.append(line[-1][0])
  1006. # bbox_list.append(line[0])
  1007. # if len(text_list) == 0:
  1008. # return []
  1009. # ocr resize后的bbox还原
  1010. if ocr_resize_flag:
  1011. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  1012. else:
  1013. ratio = (1, 1)
  1014. for i in range(len(bbox_list)):
  1015. point = bbox_list[i]
  1016. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  1017. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  1018. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  1019. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  1020. # 调用现成方法形成表格
  1021. try:
  1022. from format_convert.convert_tree import TableLine
  1023. list_lines = []
  1024. for line in list_line:
  1025. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  1026. from format_convert.convert_tree import TextBox
  1027. list_text_boxes = []
  1028. for i in range(len(bbox_list)):
  1029. bbox = bbox_list[i]
  1030. b_text = text_list[i]
  1031. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  1032. bbox[2][0], bbox[2][1]], b_text))
  1033. # for _textbox in list_text_boxes:
  1034. # print("==",_textbox.get_text())
  1035. lt = LineTable()
  1036. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  1037. # 合并同一行textbox
  1038. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  1039. obj_list = []
  1040. for table in tables:
  1041. obj_list.append(_Table(table["table"], table["bbox"]))
  1042. for text_box in list_text_boxes:
  1043. if text_box not in obj_in_table:
  1044. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  1045. return obj_list
  1046. except:
  1047. traceback.print_exc()
  1048. return [-8]
  1049. except Exception as e:
  1050. log("image_preprocess error")
  1051. traceback.print_exc()
  1052. return [-1]
  1053. if __name__ == "__main__":
  1054. image_slice_new(cv2.imread("C:/Users/Administrator/Desktop/test_image/error28.jpg"))