|
| 1 | +import cv2 as cv |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +known_distance = 40 |
| 5 | +known_width = 14.3 |
| 6 | + |
| 7 | +def Focal_length(measured_dist,real_width,width_in_rf_image): |
| 8 | + focal_length = (width_in_rf_image*measured_dist)/(real_width) |
| 9 | + return focal_length |
| 10 | + |
| 11 | +def Distance_finder(Focal_length,real_face_width,face_width_in_frame): |
| 12 | + distance = (real_face_width*Focal_length)/(face_width_in_frame) |
| 13 | + return distance |
| 14 | + |
| 15 | +def face_data(frame): |
| 16 | + face_width = 0 |
| 17 | + gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) |
| 18 | + haar_cascade = cv.CascadeClassifier(r'D:\HacktoberFest2021-Python\OpenCV\haar_face.xml') |
| 19 | + faces = haar_cascade.detectMultiScale(gray,scaleFactor=1.1, minNeighbors=5) |
| 20 | + for (x,y,w,h) in faces: |
| 21 | + cv.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),thickness=2) |
| 22 | + face_width = w |
| 23 | + # print("face width: ",w) |
| 24 | + return face_width |
| 25 | + |
| 26 | +ref_image = cv.imread(r'D:\HacktoberFest2021-Python\OpenCV\ref.jpg') |
| 27 | +ref_image_face_width = face_data(ref_image) |
| 28 | +Focal_length_found = Focal_length(known_distance,known_width,ref_image_face_width) |
| 29 | +# print(Focal_length_found) |
| 30 | +capture = cv.VideoCapture(0) |
| 31 | + |
| 32 | +while True: |
| 33 | + _,frame = capture.read() |
| 34 | + # cv.imshow('Video', gray) |
| 35 | + face_width_in_frame = face_data(frame) |
| 36 | + Distance = Distance_finder(Focal_length_found,known_width,face_width_in_frame) |
| 37 | + cv.putText(frame,f"Distance = {int(Distance)} cm",(50,50),cv.FONT_HERSHEY_PLAIN,3,(0,255,0),2) |
| 38 | + cv.imshow("Final",frame) |
| 39 | + if cv.waitKey(5) & 0xFF == ord('d'): |
| 40 | + break # d is the kill swich here |
| 41 | +capture.release() |
| 42 | +capture.destroAllWindows |
0 commit comments