check_table.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. # print(tr_list)
  33. # print('\n')
  34. for i in range(len(tr_list)):
  35. if tr_list[i] == '':
  36. continue
  37. # print(tr_list[i])
  38. tr = tr_list[i].split('</td>')[:-1]
  39. temp_list = []
  40. for cell in tr:
  41. if '<td colspan=\\"3\\">' in cell:
  42. temp_list.append(cell.split('<td colspan=\\"3\\">')[1])
  43. if '<td>' in cell:
  44. temp_list.append(cell.split('<td>')[1])
  45. self.html_arr.append(temp_list)
  46. def get_empty(self):
  47. self.get_td()
  48. if self.total != 0:
  49. return
  50. for tr in self.html_arr:
  51. for cell in tr:
  52. self.total += 1
  53. if cell == '':
  54. self.empty += 1
  55. def change_green2white(self):
  56. hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
  57. lower_green = np.array([35, 43, 46])
  58. upper_green = np.array([77, 220, 255])
  59. mask_green = cv2.inRange(hsv, lower_green, upper_green)
  60. color = [248, 248, 255]
  61. self.img[mask_green != 0] = color
  62. cv2.imwrite('table.jpg', self.img)
  63. def get_str(self):
  64. str = ''
  65. for tr in self.html_arr:
  66. for cell in tr:
  67. str+=cell
  68. return str
  69. def check_html(self):
  70. self.get_empty()
  71. html_str = self.get_str()
  72. if (self.empty > 4 and self.empty > self.total // 4) or ('项目' in str and '每份' in str and '营养素参考值' in str and np.max([len(a) for a in self.html_arr])<3):
  73. self.change_green2white()
  74. return 1
  75. return 0