Python 9 /5/8/2017


SUBMITTED BY: canonical

DATE: May 8, 2017, 6:02 p.m.

FORMAT: Python

SIZE: 2.1 kB

HITS: 423

  1. If you want more of my pastes visit: https://randompaste.000webhostapp.com/index.html
  2. --------------------------------------------------------------------------------------
  3. view my last post at: https://bitbin.it/yQvdDbDd/
  4. --------------------------------------------------------------------------------------
  5. """
  6. drawlines using kmeans to group
  7. """
  8. import cv2
  9. import numpy as np
  10. from grabscreen import grab_screen
  11. from sklearn.cluster import KMeans
  12. import pyautogui
  13. import time
  14. BOX = (0, 40, 800, 640)
  15. hood_y = 410
  16. horizon_y = 270
  17. VERTICES = np.array([[4, horizon_y], [800, horizon_y], [800, hood_y], [4, hood_y]])
  18. def draw_lines(img, lines):
  19. try:
  20. for coords in lines:
  21. coords = np.array(coords, dtype='uint32')
  22. cv2.line(img,
  23. (coords[0], coords[1]),
  24. (coords[2], coords[3]),
  25. [255, 255, 255], 5)
  26. except (TypeError, IndexError):
  27. pass
  28. def roi(img, vertices):
  29. mask = np.zeros_like(img)
  30. cv2.fillPoly(mask, vertices, 255)
  31. masked = cv2.bitwise_and(img, mask)
  32. return masked
  33. def process_img(processed_img):
  34. processed_img = cv2.Canny(processed_img, threshold1=100, threshold2=300)
  35. processed_img = roi(processed_img, [VERTICES])
  36. processed_img = cv2.GaussianBlur(processed_img, (5, 5), 0)
  37. lines = cv2.HoughLinesP(processed_img, 1, np.pi / 180, 180, np.array([]), 140, 20)
  38. try:
  39. nlines = np.array([l[0] for l in lines])
  40. kmeans = KMeans(n_clusters=2, random_state=0).fit(nlines)
  41. draw_lines(processed_img, kmeans.cluster_centers_)
  42. except TypeError:
  43. pass
  44. finally:
  45. return processed_img
  46. def main():
  47. while True:
  48. ti = time.time()
  49. screen = grab_screen(region=BOX)
  50. new_screen = process_img(screen)
  51. print('{:.2f} FPS'.format(1 / (time.time() - ti)))
  52. cv2.imshow('window', new_screen)
  53. if cv2.waitKey(25) & 0xFF == ord('q'):
  54. cv2.destroyAllWindows()
  55. break
  56. if __name__ == '__main__':
  57. main()

comments powered by Disqus