check_table.py 2.5 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. print(self.html)
  12. try:
  13. res = self.html.split('<tbody>')[1]
  14. except Exception as r:
  15. print('<tbody> 识别失败')
  16. print(r)
  17. try:
  18. res = res.split('</tbody>')[0]
  19. except Exception as r:
  20. print('</tbody> 识别失败')
  21. print(r)
  22. return res
  23. def get_tr(self):
  24. # str = self.get_body()
  25. if len(str.split('<tr>')) > 1:
  26. return str.split('<tr>')[1:-1]
  27. else:
  28. return []
  29. def get_td(self):
  30. if self.html_arr != []:
  31. return
  32. tr_list = self.get_tr()
  33. for i in range(len(tr_list)):
  34. if tr_list[i] == '':
  35. continue
  36. tr = tr_list[i].split('</td>')[:-1]
  37. temp_list = []
  38. for cell in tr:
  39. if '<td colspan=\\"3\\">' in cell:
  40. temp_list.append(cell.split('<td colspan=\\"3\\">')[1])
  41. if '<td>' in cell:
  42. temp_list.append(cell.split('<td>')[1])
  43. self.html_arr.append(temp_list)
  44. def get_empty(self):
  45. self.get_td()
  46. if self.total != 0:
  47. return
  48. for tr in self.html_arr:
  49. for cell in tr:
  50. self.total += 1
  51. if cell == '':
  52. self.empty += 1
  53. def change_green2white(self):
  54. hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
  55. lower_green = np.array([35, 43, 46])
  56. upper_green = np.array([77, 220, 255])
  57. mask_green = cv2.inRange(hsv, lower_green, upper_green)
  58. color = [248, 248, 255]
  59. self.img[mask_green != 0] = color
  60. def get_str(self):
  61. str = ''
  62. for tr in self.html_arr:
  63. for cell in tr:
  64. str+=cell
  65. return str
  66. def check_html(self):
  67. self.get_empty()
  68. html_str = self.get_str()
  69. print(self.html_arr)
  70. print(self.empty)
  71. 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):
  72. print('识别效果不佳,改变图片颜色!')
  73. self.change_green2white()
  74. return 1
  75. return 0