Advertisement
Guest User

Laser_detection

a guest
Apr 26th, 2018
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. ## program written by Shane Ormonde 7th sept 2013
  2. ## updated on 25th January 2014
  3. ## calculates the distance of a red dot in the field of view of the webcam.
  4. import cv2
  5. from numpy import *
  6. import math
  7.  
  8. #variables
  9. loop = 1
  10. dot_dist = 0
  11.  
  12. cv2.namedWindow("preview")
  13. vc = cv2.VideoCapture(0)
  14.  
  15. if vc.isOpened(): # try to get the first frame
  16.     rval, frame = vc.read()
  17.  
  18. else:
  19.     rval = False
  20.     #print "failed to open webcam"
  21.  
  22. if rval == 1 :
  23.  
  24.     while loop == 1:
  25.         cv2.imshow("preview", frame)
  26.         rval, frame = vc.read()
  27.         key = cv2.waitKey(20)
  28.         if key == 27: # exit on ESC
  29.             loop = 0
  30.         num = (frame[...,...,2] > 236)
  31.         xy_val =  num.nonzero()
  32.  
  33.         y_val = median(xy_val[0])
  34.         x_val = median(xy_val[1])
  35.  
  36.         #dist = ((x_val - 320)**2 + (y_val - 240)**2 )**0.5 # distance of dot from center pixel
  37.         dist = abs(x_val - 320) # distance of dot from center x_axis only
  38.  
  39.         print(" dist from center pixel is " + str(dist))
  40.  
  41.         # work out distance using D = h/tan(theta)
  42.  
  43.         theta =0.0011450*dist + 0.0154
  44.         tan_theta = math.tan(theta)
  45.  
  46.         if tan_theta > 0: # bit of error checking
  47.             obj_dist =  int(5.33 / tan_theta)
  48.  
  49.         print("the dot is " + str(obj_dist) + "cm  away")
  50. elif rval == 0:
  51.     print(" webcam error ")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement