Created
March 31, 2021 06:35
-
-
Save tejastank/288ada9c981cf527f90ce344f6d7fd3a to your computer and use it in GitHub Desktop.
Distance to face calculation Windows10 web cam. OpenCv 3.4 Python 3.6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import imutils | |
import cv2 | |
from imutils.video import VideoStream | |
from imutils.video import FPS | |
import time | |
def distance_to_camera(knownWidth, focalLength, perWidth): | |
# compute and return the distance from the maker to the camera | |
return (knownWidth * focalLength) / perWidth | |
face_cascade = cv2.CascadeClassifier('C:/Users/bbartling/Desktop/Haar/frontalFace10/haarcascade_frontalface_alt2.xml') | |
#Calculated from a different script | |
focalLength = 709.0909090909091 | |
#average human head width | |
knownWidth = 7 | |
# Initialize mutithreading the video stream. | |
camera = VideoStream(src=0).start() | |
# Allow the camera to warm up. | |
time.sleep(2.0) | |
#start FPS | |
fps = FPS().start() | |
roi = None | |
while True: | |
image = camera.read() | |
image = imutils.resize(image, width=400) | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5); | |
for (x, y, w, h) in faces: | |
cv2.rectangle(gray,(x,y),(x+w,y+h),(255,255,255),2) | |
roi = gray[y:y+h, x:x+w] | |
if roi is None: | |
pass | |
else: | |
inches = distance_to_camera(knownWidth, focalLength, roi.shape[1]) | |
print(inches) | |
text = "Inches {}".format(np.int(inches)) | |
cv2.putText(gray, text, (x - 10, y - 10), | |
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2) | |
cv2.imshow("gray", gray) | |
key = cv2.waitKey(1) & 0xFF | |
fps.update() | |
# if the `q` key was pressed, break from the loop | |
if key == ord("q"): | |
break | |
fps.stop() | |
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed())) | |
print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) | |
camera.stop() | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment