check_table.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 check_html(self):
  64. self.get_empty()
  65. if self.empty > 4 and self.empty > self.total // 4:
  66. self.change_green2white()
  67. return 1
  68. return 0