check_table.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import cv2
  2. import numpy as np
  3. class Table:
  4. def __init__(self, html, img=[]):
  5. self.img = img
  6. self.html = html
  7. self.html_arr = []
  8. self.total = 0
  9. self.empty = 0
  10. def get_body(self):
  11. try:
  12. res = self.html.split('<tbody>')[1]
  13. except Exception as r:
  14. print('<tbody> 识别失败')
  15. print(r)
  16. try:
  17. res = res.split('</tbody>')[0]
  18. except Exception as r:
  19. print('</tbody> 识别失败')
  20. print(r)
  21. return res
  22. def get_tr(self):
  23. str = self.get_body()
  24. if len(str.split('<tr>')) > 1:
  25. return str.split('<tr>')
  26. else:
  27. return []
  28. def get_td(self):
  29. if self.html_arr != []:
  30. return
  31. tr_list = self.get_tr()
  32. for i in range(len(tr_list)):
  33. if tr_list[i] == '':
  34. continue
  35. tr = tr_list[i].split('</td>')[:-1]
  36. temp_list = []
  37. for cell in tr:
  38. if '<td colspan=\\"3\\">' in cell:
  39. temp_list.append(cell.split('<td colspan=\\"3\\">')[1])
  40. if '<td>' in cell:
  41. temp_list.append(cell.split('<td>')[1])
  42. self.html_arr.append(temp_list)
  43. def get_empty(self):
  44. self.get_td()
  45. if self.total != 0:
  46. return
  47. for tr in self.html_arr:
  48. for cell in tr:
  49. self.total += 1
  50. if cell == '':
  51. self.empty += 1
  52. def change_green2white(self):
  53. hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
  54. lower_green = np.array([35, 43, 46])
  55. upper_green = np.array([77, 220, 255])
  56. mask_green = cv2.inRange(hsv, lower_green, upper_green)
  57. color = [248, 248, 255]
  58. self.img[mask_green != 0] = color
  59. def get_str(self):
  60. str = ''
  61. for tr in self.html_arr:
  62. for cell in tr:
  63. str+=cell
  64. return str
  65. def check_html(self):
  66. self.get_empty()
  67. html_str = self.get_str()
  68. if (self.empty > 4 and self.empty > self.total // 4) or ('项目' in html_str and '每份' in html_str and '营养素参考值' in html_str and np.max([len(a) for a in self.html_arr])<3):
  69. self.change_green2white()
  70. return 1
  71. return 0