resolve.py 19 KB

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