direction.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import cv2
  2. import numpy as np
  3. def detect_angle(image):
  4. mask = np.zeros(image.shape, dtype=np.uint8)
  5. gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
  6. blur = cv2.GaussianBlur(gray, (3,3), 0)
  7. adaptive = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,15,4)
  8. cnts = cv2.findContours(adaptive, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  9. cnts = cnts[0] if len(cnts) == 2 else cnts[1]
  10. for c in cnts:
  11. area = cv2.contourArea(c)
  12. if area < 45000 and area > 20:
  13. cv2.drawContours(mask, [c], -1, (255,255,255), -1)
  14. mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
  15. h, w = mask.shape
  16. # Horizontal
  17. if w > h:
  18. left = mask[0:h, 0:0+w//2]
  19. right = mask[0:h, w//2:]
  20. left_pixels = cv2.countNonZero(left)
  21. right_pixels = cv2.countNonZero(right)
  22. return 0 if left_pixels >= right_pixels else 180
  23. # Vertical
  24. else:
  25. top = mask[0:h//2, 0:w]
  26. bottom = mask[h//2:, 0:w]
  27. top_pixels = cv2.countNonZero(top)
  28. bottom_pixels = cv2.countNonZero(bottom)
  29. return 90 if bottom_pixels >= top_pixels else 270
  30. if __name__ == '__main__':
  31. image = cv2.imread('d40.jpg')
  32. angle = detect_angle(image)
  33. print(angle)