line1.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import cv2
  2. import numpy as np
  3. # define a video capture object
  4. vid = cv2.VideoCapture(0)
  5. while(True):
  6. # Capture the video frame
  7. # by frame
  8. ret, frame = vid.read()
  9. # Convert to grayscale.
  10. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  11. # Apply edge detection method on the image
  12. edges = cv2.Canny(gray, 50, 150, apertureSize=3)
  13. # This returns an array of r and theta values
  14. lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
  15. # The below for loop runs till r and theta values
  16. # are in the range of the 2d array
  17. if lines is not None:
  18. for r_theta in lines:
  19. arr = np.array(r_theta[0], dtype=np.float64)
  20. r, theta = arr
  21. # Stores the value of cos(theta) in a
  22. a = np.cos(theta)
  23. # Stores the value of sin(theta) in b
  24. b = np.sin(theta)
  25. # x0 stores the value rcos(theta)
  26. x0 = a*r
  27. # y0 stores the value rsin(theta)
  28. y0 = b*r
  29. # x1 stores the rounded off value of (rcos(theta)-1000sin(theta))
  30. x1 = int(x0 + 1000*(-b))
  31. # y1 stores the rounded off value of (rsin(theta)+1000cos(theta))
  32. y1 = int(y0 + 1000*(a))
  33. # x2 stores the rounded off value of (rcos(theta)+1000sin(theta))
  34. x2 = int(x0 - 1000*(-b))
  35. # y2 stores the rounded off value of (rsin(theta)-1000cos(theta))
  36. y2 = int(y0 - 1000*(a))
  37. # cv2.line draws a line in img from the point(x1,y1) to (x2,y2).
  38. # (0,0,255) denotes the colour of the line to be
  39. # drawn. In this case, it is red.
  40. cv2.line(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)
  41. # Display the resulting frame
  42. cv2.imshow('frame', frame)
  43. # the 'q' button is set as the
  44. # quitting button you may use any
  45. # desired button of your choice
  46. if cv2.waitKey(1) & 0xFF == ord('q'):
  47. break
  48. # After the loop release the cap object
  49. vid.release()
  50. # Destroy all the windows
  51. cv2.destroyAllWindows()