direction.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import dataclasses
  2. import cv2
  3. import numpy as np
  4. from dataclasses import dataclass
  5. from paddleocr import PaddleOCR
  6. @dataclass
  7. # 角度检测器
  8. class AngleDetector(object):
  9. ocr: PaddleOCR
  10. def detect_angle(self, img, result) -> int:
  11. wc = 0
  12. hc = 0
  13. count_0 = 0
  14. count_180 = 0
  15. angle = 0
  16. print(result)
  17. for res in result:
  18. txt = res[1][0]
  19. if '号' not in txt: continue
  20. a = np.array(res[0])
  21. l, t = np.min(a, axis=0).tolist()
  22. r, b = np.max(a, axis=0).tolist()
  23. l, t, r, b = list(map(int, [l, t, r, b]))
  24. if b - t > r - l:
  25. hc += 1
  26. else:
  27. wc += 1
  28. imgb = img[t:b, l:r, :]
  29. r = self.ocr.ocr(imgb, det=False, rec=False, cls=True)
  30. print(f'ocr angle: {r}')
  31. if int(r[0][0]) == 180:
  32. count_180 += 1
  33. else:
  34. count_0 += 1
  35. if hc >= wc:
  36. if count_0 >= count_180:
  37. angle = 90
  38. else:
  39. angle = 270
  40. else:
  41. if count_0 > count_180:
  42. angle = 0
  43. else:
  44. angle = 180
  45. return angle
  46. def detect_angle(image):
  47. mask = np.zeros(image.shape, dtype=np.uint8)
  48. gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
  49. blur = cv2.GaussianBlur(gray, (3, 3), 0)
  50. adaptive = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 15, 4)
  51. cnts = cv2.findContours(adaptive, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  52. cnts = cnts[0] if len(cnts) == 2 else cnts[1]
  53. for c in cnts:
  54. area = cv2.contourArea(c)
  55. if area < 45000 and area > 20:
  56. cv2.drawContours(mask, [c], -1, (255, 255, 255), -1)
  57. mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
  58. h, w = mask.shape
  59. # Horizontal
  60. if w > h:
  61. left = mask[0:h, 0:0 + w // 2]
  62. right = mask[0:h, w // 2:]
  63. left_pixels = cv2.countNonZero(left)
  64. right_pixels = cv2.countNonZero(right)
  65. return 0 if left_pixels >= right_pixels else 180
  66. # Vertical
  67. else:
  68. top = mask[0:h // 2, 0:w]
  69. bottom = mask[h // 2:, 0:w]
  70. top_pixels = cv2.countNonZero(top)
  71. bottom_pixels = cv2.countNonZero(bottom)
  72. return 90 if bottom_pixels >= top_pixels else 270
  73. if __name__ == '__main__':
  74. image = cv2.imread('d40.jpg')
  75. angle = detect_angle(image)
  76. print(angle)