resolve.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. # @Author : lightXu
  2. # @File : resolve.py
  3. # @Time : 2018/12/3 0003 上午 10:16
  4. import time
  5. import traceback
  6. import xml.etree.cElementTree as ET
  7. from django.conf import settings
  8. import segment.logging_config as logging
  9. import segment.sheet_resolve.analysis.choice.analysis_choice as resolve_choice
  10. import segment.sheet_resolve.analysis.choice.choice_box as choice_box
  11. import segment.sheet_resolve.analysis.choice.choice_line_box as choice_line_box
  12. import segment.sheet_resolve.analysis.cloze.analysis_cloze as resolve_cloze
  13. import segment.sheet_resolve.analysis.cloze.cloze_line_box as resolve_cloze_line_box
  14. import segment.sheet_resolve.analysis.exam_number.exam_number_box as resolve_exam_number_box
  15. import segment.sheet_resolve.analysis.exam_number.exam_number_row_column as exam_number_row_column
  16. import segment.sheet_resolve.analysis.sheet.analysis_sheet as resolve_sheet
  17. import segment.sheet_resolve.analysis.solve.mark_box as resolve_mark_box
  18. import segment.sheet_resolve.analysis.solve.mark_line_box as resolve_mark_line_box
  19. from segment.sheet_resolve.tools import utils
  20. from segment.sheet_resolve.tools.tf_sess import TfSess
  21. from segment.sheet_resolve.tools.tf_settings import xml_template_path, model_dict
  22. from segment.sheet_resolve.tools.utils import read_single_img, read_xml_to_json, create_xml
  23. from segment.sheet_resolve.analysis.sheet.sheet_adjust import adjust_item_edge_by_gray_image
  24. from segment.sheet_resolve.analysis.sheet.sheet_infer import infer_bar_code, box_infer_and_complete
  25. from segment.sheet_resolve.analysis.sheet.sheet_infer import infer_exam_number, adjust_exam_number, exam_number_infer_by_s
  26. from segment.sheet_resolve.analysis.sheet.choice_infer import infer_choice_m
  27. logger = logging.getLogger(settings.LOGGING_TYPE)
  28. sheet_infer_dict = dict(bar_code=True,
  29. choice_m=True,
  30. exam_number=True,
  31. common_sheet=True)
  32. infer_choice_m_flag = False
  33. def sheet(series_number, image_path, image, conf_thresh, mns_thresh, subject, sheet_sess, ocr=''):
  34. global infer_choice_m_flag
  35. model_type = subject
  36. classes = list(model_dict[model_type]['classes'])
  37. coordinate_bias_dict = model_dict[model_type]['class_coordinate_bias']
  38. if '_blank' in model_type:
  39. model_type = model_type.replace("_blank", "")
  40. sheets_dict = resolve_sheet.get_single_image_sheet_regions(model_type, image_path, image, classes,
  41. sheet_sess.sess, sheet_sess.net,
  42. conf_thresh, mns_thresh, coordinate_bias_dict)
  43. h, w = image.shape[0], image.shape[1]
  44. regions = sheets_dict['regions']
  45. fetched_class = [ele['class_name'] for ele in regions]
  46. try:
  47. regions = adjust_item_edge_by_gray_image(image, regions)
  48. except Exception as e:
  49. traceback.print_exc()
  50. logger.info('试卷:{} 自适应边框失败: {}'.format(image_path, e))
  51. if sheet_infer_dict['bar_code']:
  52. try:
  53. if ('bar_code' not in fetched_class) and ocr:
  54. attention_region = [ele for ele in regions if ele['class_name'] == 'attention']
  55. bar_code_list = infer_bar_code(image, ocr, attention_region)
  56. regions.extend(bar_code_list)
  57. except Exception as e:
  58. traceback.print_exc()
  59. logger.info('试卷:{} 条形码推断失败: {}'.format(image_path, e))
  60. if sheet_infer_dict['exam_number']:
  61. try:
  62. cond1 = 'exam_number' in fetched_class
  63. tmp = ['info_title', 'qr_code', 'bar_code', 'choice', 'choice_m', 'exam_number_w']
  64. cond2 = True in [True for ele in tmp if ele in fetched_class] # 第一面特征
  65. cond3 = 'exam_number_w' in fetched_class
  66. cond4 = 'exam_number_s' in fetched_class
  67. if cond1 and cond3 and not cond4:
  68. regions = adjust_exam_number(regions)
  69. if not cond1 and cond4:
  70. exam_number_list = exam_number_infer_by_s(image, regions)
  71. regions.extend(exam_number_list)
  72. if not cond1 and not cond4 and cond2 and ocr:
  73. exam_number_list = infer_exam_number(image, ocr, regions)
  74. regions.extend(exam_number_list)
  75. except Exception as e:
  76. traceback.print_exc()
  77. logger.info('试卷:{} 考号推断失败: {}'.format(image_path, e))
  78. if sheet_infer_dict['choice_m']:
  79. try:
  80. choice_m_list = infer_choice_m(image, regions, ocr)
  81. remain_choice_m = []
  82. if len(choice_m_list) > 0:
  83. choice_m_old_list = [ele for ele in regions if 'choice_m' == ele['class_name']]
  84. for infer_box in choice_m_list.copy():
  85. infer_loc = infer_box['bounding_box']
  86. for tf_box in choice_m_old_list:
  87. tf_loc = tf_box['bounding_box']
  88. iou = utils.cal_iou(infer_loc, tf_loc)
  89. if iou[0] > 0.85 or iou[1] > 0.85:
  90. if infer_box not in remain_choice_m:
  91. remain_choice_m.append(infer_box)
  92. choice_m_list.remove(infer_box)
  93. regions.remove(tf_box)
  94. break
  95. elif iou[0] > 0:
  96. choice_m_list.remove(infer_box)
  97. break
  98. remain_choice_m.extend(choice_m_list)
  99. # regions = [ele for ele in regions if 'choice_m' != ele['class_name']]
  100. regions.extend(remain_choice_m)
  101. infer_choice_m_flag = True
  102. except Exception as e:
  103. traceback.print_exc()
  104. logger.info('试卷:{} 选择题推断失败: {}'.format(image_path, e))
  105. if sheet_infer_dict['common_sheet']:
  106. try:
  107. regions = box_infer_and_complete(image, regions, ocr)
  108. except Exception as e:
  109. traceback.print_exc()
  110. logger.info('试卷:{} 识别框补全推断失败: {}'.format(image_path, e))
  111. try:
  112. adjust_regions = adjust_item_edge_by_gray_image(image, regions)
  113. except Exception as e:
  114. adjust_regions = regions
  115. traceback.print_exc()
  116. logger.info('试卷:{} 自适应边框失败: {}'.format(image_path, e))
  117. sheets_dict.update({'regions': adjust_regions})
  118. # generate xml
  119. tree = ET.parse(xml_template_path)
  120. xml_save_path = sheets_dict['img_name'].replace('.jpg', '.xml')
  121. root = tree.getroot()
  122. series = ET.SubElement(root, 'paper_id')
  123. series.text = series_number
  124. img_shape = image.shape
  125. project = ET.SubElement(root, 'size', {})
  126. width = ET.SubElement(project, 'width')
  127. width.text = str(img_shape[1])
  128. height = ET.SubElement(project, 'height')
  129. height.text = str(img_shape[0])
  130. depth = ET.SubElement(project, 'depth')
  131. if len(img_shape) >= 3:
  132. depth.text = '3'
  133. else:
  134. depth.text = '1'
  135. for ele in regions:
  136. name = ele['class_name']
  137. xmin = ele['bounding_box']['xmin']
  138. ymin = ele['bounding_box']['ymin']
  139. xmax = ele['bounding_box']['xmax']
  140. ymax = ele['bounding_box']['ymax']
  141. tree = create_xml(name, tree, xmin, ymin, xmax, ymax)
  142. tree.write(xml_save_path)
  143. return sheets_dict, xml_save_path
  144. def choice(image, regions, xml_path, conf_thresh, mns_thresh, choice_sess):
  145. model_type = 'choice'
  146. classes = model_dict[model_type]['classes']
  147. coordinate_bias_dict = model_dict[model_type]['class_coordinate_bias']
  148. choice_list = []
  149. for ele in regions:
  150. if ele["class_name"] == 'choice':
  151. choice_bbox = ele['bounding_box']
  152. left = choice_bbox['xmin']
  153. top = choice_bbox['ymin']
  154. choice_img = utils.crop_region(image, choice_bbox)
  155. choice_dict_tf = resolve_choice. \
  156. get_single_image_sheet_regions('choice', choice_img, classes,
  157. choice_sess.sess, choice_sess.net, conf_thresh, mns_thresh,
  158. coordinate_bias_dict)
  159. choice_list = choice_list + choice_line_box.choice_line(left, top, choice_img, choice_dict_tf, xml_path)
  160. return choice_list
  161. def choice_row_col(image, regions, xml_path, conf_thresh, mns_thresh, choice_sess):
  162. model_type = 'choice_m'
  163. classes = model_dict[model_type]['classes']
  164. coordinate_bias_dict = model_dict[model_type]['class_coordinate_bias']
  165. choice_list = []
  166. for ele in regions:
  167. if ele["class_name"] == 'choice':
  168. choice_box = ele['bounding_box']
  169. left = choice_box['xmin']
  170. top = choice_box['ymin']
  171. choice_img = utils.crop_region(image, choice_box)
  172. choice_m_dict_tf = resolve_choice. \
  173. get_single_image_sheet_regions('choice_m', choice_img, classes,
  174. choice_sess.sess, choice_sess.net, conf_thresh, mns_thresh,
  175. coordinate_bias_dict)
  176. choice_list = choice_list + choice_line_box.choice_line_with_number(left, top, choice_img, choice_m_dict_tf, xml_path)
  177. return choice_list
  178. def choice_m_row_col(image, regions, xml_path):
  179. choice_m_dict_tf = [ele for ele in regions if ele['class_name'] == 'choice_m']
  180. # choice_m_row_col_with_number
  181. choice_list = []
  182. try:
  183. # choice_list = choice_box.get_number_by_enlarge_choice_m(image, choice_m_dict_tf, xml_path)
  184. # if infer_choice_m_flag:
  185. # choice_list = choice_line_box.choice_m_adjust(image, choice_m_dict_tf)
  186. #
  187. # else:
  188. # choice_list = choice_line_box.choice_m_row_col(image, choice_m_dict_tf, xml_path) # 找选择题行列、分数
  189. choice_list = choice_line_box.choice_m_row_col(image, choice_m_dict_tf, xml_path) # 找选择题行列、分数
  190. tree = ET.parse(xml_path) # xml tree
  191. for index_num, box in enumerate(choice_list):
  192. if len(box['bounding_box']) > 0:
  193. abcd = box['bounding_box']
  194. number = str(box['number'])
  195. name = '{}_{}*{}_{}_{}'.format('choice_m', box['rows'], box['cols'], box['direction'], number)
  196. tree = utils.create_xml(name, tree,
  197. abcd['xmin'], abcd['ymin'],
  198. abcd['xmax'], abcd['ymax'])
  199. tree.write(xml_path)
  200. except Exception as e:
  201. traceback.print_exc()
  202. print(e)
  203. return choice_list
  204. def exam_number(image, regions, xml_path):
  205. exam_number_dict = {}
  206. for ele in regions:
  207. if ele["class_name"] == 'exam_number':
  208. exam_number_dict = ele
  209. exam_number_box = exam_number_dict['bounding_box']
  210. left = exam_number_box['xmin']
  211. top = exam_number_box['ymin']
  212. exam_number_img = utils.crop_region(image, exam_number_box)
  213. # exam_number_dict = resolve_exam_number_box.exam_number(left, top, exam_number_img, xml_path)
  214. exam_number_dict = resolve_exam_number_box.exam_number_whole(left, top, exam_number_img, xml_path)
  215. # print(exam_number_dict)
  216. return exam_number_dict
  217. def exam_number_row_col(image, regions, xml_path):
  218. exam_number_dict = {}
  219. for ele in regions:
  220. if ele["class_name"] == 'exam_number':
  221. exam_number_dict = ele
  222. exam_number_box = exam_number_dict['bounding_box']
  223. left = exam_number_box['xmin']
  224. top = exam_number_box['ymin']
  225. exam_number_img = utils.crop_region(image, exam_number_box)
  226. exam_number_row_col_dict = exam_number_row_column.get_exam_number_row_and_col(left, top, exam_number_img)
  227. tree = ET.parse(xml_path) # xml tree
  228. if len(exam_number_row_col_dict) > 0:
  229. exam_number_box = exam_number_row_col_dict['bounding_box']
  230. name = '{}_{}*{}_{}'.format('exam_number',
  231. exam_number_row_col_dict['rows'],
  232. exam_number_row_col_dict['cols'],
  233. exam_number_row_col_dict['direction'])
  234. tree = utils.create_xml(name, tree,
  235. exam_number_box['xmin'], exam_number_box['ymin'],
  236. exam_number_box['xmax'], exam_number_box['ymax'])
  237. else:
  238. tree = utils.create_xml('exam_number', tree,
  239. exam_number_box['xmin'], exam_number_box['ymin'],
  240. exam_number_box['xmax'], exam_number_box['ymax'])
  241. exam_number_row_col_dict = {}
  242. tree.write(xml_path)
  243. return [exam_number_row_col_dict]
  244. def cloze(image, regions, xml_path, conf_thresh, mns_thresh, cloze_sess):
  245. classes = model_dict['cloze']['classes']
  246. coordinate_bias_dict = model_dict['cloze']['class_coordinate_bias']
  247. cloze_list = []
  248. for ele in regions:
  249. if ele["class_name"] == 'cloze':
  250. cloze_box = ele['bounding_box']
  251. left = cloze_box['xmin']
  252. top = cloze_box['ymin']
  253. cloze_img = utils.crop_region(image, cloze_box)
  254. cloze_dict_tf = resolve_cloze.get_single_image_sheet_regions('cloze', cloze_img, classes,
  255. cloze_sess.sess, cloze_sess.net, conf_thresh,
  256. mns_thresh, coordinate_bias_dict)
  257. cloze_list = cloze_list + resolve_cloze_line_box.cloze_line(left, top, cloze_img, cloze_dict_tf['regions'], xml_path)
  258. return cloze_list
  259. def solve_with_mark(image, regions, xml_path):
  260. solve_list = []
  261. mark_list = []
  262. for ele in regions.copy():
  263. if 'solve' in ele["class_name"]:
  264. exam_number_box = ele['bounding_box']
  265. left = exam_number_box['xmin']
  266. top = exam_number_box['ymin']
  267. exam_number_img = utils.crop_region(image, exam_number_box)
  268. solve_mark_dict = resolve_mark_box.solve_mark(left, top, exam_number_img, xml_path)
  269. if len(solve_mark_dict) > 0:
  270. ele['class_name'] = 'solve_'+str(solve_mark_dict['number'])
  271. solve_list.append(ele)
  272. mark_list.append(solve_mark_dict)
  273. return solve_list, mark_list
  274. def solve(image, regions, xml_path):
  275. solve_list = []
  276. tree = ET.parse(xml_path)
  277. for ele in regions.copy():
  278. if 'solve' in ele["class_name"]:
  279. exam_number_box = ele['bounding_box']
  280. exam_number_img = utils.crop_region(image, exam_number_box)
  281. number = resolve_mark_line_box.solve_line(exam_number_img)
  282. solve_dict = {'number': number, 'location': exam_number_box, 'default_points': 12}
  283. solve_list.append(solve_dict)
  284. tree = utils.create_xml(str(number), tree,
  285. exam_number_box['xmin'], exam_number_box['ymin'],
  286. exam_number_box['xmax'], exam_number_box['ymax'])
  287. tree.write(xml_path)
  288. return solve_list
  289. def solve_with_number(regions, xml_path):
  290. solve_list = []
  291. for ele in regions:
  292. if 'solve' in ele["class_name"] or 'composition' in ele["class_name"]:
  293. solve_dict = {'number': -1, 'default_points': -1}
  294. ele.update(solve_dict)
  295. solve_list.append(ele)
  296. tree = ET.parse(xml_path) # xml tree
  297. for index_num, box in enumerate(solve_list):
  298. if len(box['bounding_box']) > 0:
  299. abcd = box['bounding_box']
  300. number = str(box['number'])
  301. default_points = box["default_points"]
  302. name = '{}_{}_{}'.format(box["class_name"], number, default_points)
  303. tree = utils.create_xml(name, tree,
  304. abcd['xmin'], abcd['ymin'],
  305. abcd['xmax'], abcd['ymax'])
  306. tree.write(xml_path)
  307. return solve_list
  308. def cloze_with_number(regions, xml_path):
  309. cloze_list = []
  310. for ele in regions:
  311. if 'cloze' == ele["class_name"] or "cloze_s" == ele["class_name"]:
  312. cloze_dict = {'number': -1, 'default_points': -1}
  313. ele.update(cloze_dict)
  314. cloze_list.append(ele)
  315. tree = ET.parse(xml_path) # xml tree
  316. for index_num, box in enumerate(cloze_list):
  317. if len(box['bounding_box']) > 0:
  318. abcd = box['bounding_box']
  319. number = str(box['number'])
  320. default_points = box["default_points"]
  321. name = '{}_{}_{}'.format(box["class_name"], number, default_points)
  322. tree = utils.create_xml(name, tree,
  323. abcd['xmin'], abcd['ymin'],
  324. abcd['xmax'], abcd['ymax'])
  325. tree.write(xml_path)
  326. return cloze_list
  327. def make_together(image_path):
  328. sheet_sess = TfSess('sheet')
  329. choice_sess = TfSess('choice')
  330. cloze_sess = TfSess('cloze')
  331. raw_img = read_single_img(image_path)
  332. conf_thresh_0 = 0.7
  333. mns_thresh_0 = 0.3
  334. series_number = 123456789
  335. subject = 'english'
  336. sheets_dict_0, xml_save_path = sheet(series_number, image_path, raw_img, conf_thresh_0, mns_thresh_0, subject, sheet_sess)
  337. # 手动修改faster_rcnn识别生成的框
  338. sheets_dict_0 = read_xml_to_json(xml_save_path)
  339. regions = sheets_dict_0['regions']
  340. classes_name = str([ele['class_name'] for ele in regions])
  341. if 'choice' in classes_name:
  342. try:
  343. sheets_dict_0['choice'] = choice(raw_img, regions, xml_save_path, conf_thresh_0, mns_thresh_0, choice_sess)
  344. except Exception:
  345. traceback.print_exc()
  346. if 'exam_number' in classes_name:
  347. try:
  348. sheets_dict_0['exam_number'] = exam_number(raw_img, regions, xml_save_path)
  349. except Exception:
  350. traceback.print_exc()
  351. if 'cloze' in classes_name:
  352. try:
  353. sheets_dict_0['cloze'] = cloze(raw_img, regions, xml_save_path, conf_thresh_0, mns_thresh_0, cloze_sess)
  354. except Exception:
  355. traceback.print_exc()
  356. if 'solve' in classes_name:
  357. try:
  358. solve_list, mark_list = solve(raw_img, regions, xml_save_path,)
  359. sheets_dict_0['solve'] = solve_list
  360. sheets_dict_0['mark'] = mark_list
  361. except Exception:
  362. traceback.print_exc()
  363. # print(sheets_dict_0)
  364. return sheets_dict_0
  365. # if __name__ == '__main__':
  366. # start_time = time.time()
  367. #
  368. # image_path_0 = os.path.join(r'C:\Users\Administrator\Desktop\sheet\correct\back_sizes\template',
  369. # '20180719004308818_0020.jpg')
  370. # make_together(image_path_0)
  371. # end_time = time.time()
  372. # print('time cost: ', (end_time - start_time))