Twist_Nemo

Project.py

Mar 5th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1.  
  2. import cv2
  3. # variables
  4. # distance from camera to object(face) measured
  5. Known_distance = 30 #centimeter
  6. # width of face in the real world or Object Plane
  7. Known_width =14.3
  8. # Colors
  9. GREEN = (0, 255, 0)
  10. RED = (0, 0, 255)
  11. WHITE = (255, 255, 255)
  12. fonts = cv2.FONT_HERSHEY_COMPLEX
  13. cap = cv2.VideoCapture(0) #Use camera 0
  14. # face detector object
  15. face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  16. # focal length finder function
  17. def FocalLength(measured_distance, real_width, width_in_rf_image):
  18.     focal_length = (width_in_rf_image* measured_distance)/ real_width
  19.     return focal_length
  20. # distance estimation function
  21. def Distance_finder (Focal_Length, real_face_width, face_width_in_frame):
  22.     distance = (real_face_width * Focal_Length)/face_width_in_frame
  23.     return distance
  24.  
  25. def face_data(image):
  26.     face_width = 0
  27.     gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  28.     faces = face_detector.detectMultiScale(gray_image, 1.3, 5)
  29.     for (x, y, h, w) in faces:
  30.         cv2.rectangle(image, (x, y), (x+w, y+h), WHITE, 1)
  31.         face_width = w
  32.  
  33.     return face_width
  34.  
  35.  
  36. while True:
  37.     _, frame = cap.read()
  38.  
  39.     # calling face_data function
  40.     face_width_in_frame = face_data(frame)
  41.     # finding the distance by calling function Distance finder
  42.     if face_width_in_frame != 0:
  43.         Distance = Distance_finder(Focal_length_found, Known_width,face_width_in_frame)
  44.     # Drwaing Text on the screen
  45.         cv2.putText(frame, f"Distance = {Distance}", (50,50), fonts,1, (WHITE),2)
  46.     cv2.imshow("frame", frame )
  47.     if cv2.waitKey(1) == ord("q"):
  48.         break
  49. cap.release()
  50. cv2.destroyAllWindows()
  51.  
Advertisement
Add Comment
Please, Sign In to add comment