Skip to content

Instantly share code, notes, and snippets.

@Ridley-nelson17
Last active April 15, 2020 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ridley-nelson17/813e19747504a321bdc1f91ad36cb08b to your computer and use it in GitHub Desktop.
Save Ridley-nelson17/813e19747504a321bdc1f91ad36cb08b to your computer and use it in GitHub Desktop.
OpenCV-Object-Detection
import cv2
import numpy as np
from matplotlib import pyplot as plt
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
# Detect faces
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
eyeCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
glassesCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye_tree_eyeglasses.xml")
# Draw the boxes with faces
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.3,
minNeighbors=3,
minSize=(30, 30)
)
face_count = None
eye_count = None
glasses_count = None
# Define the camera input
camera = cv2.VideoCapture(0)
while True:
# Rescan the image before drawing every time
ret, image = cap.read()
# Define the gray version of the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
if face_count != None: face_count = face_count + len(faces)
else: face_count = len(faces)
detection_gray = gray[y:y+h, x:x+w]
color = image[y:y+h, x:x+w]
glasses = eyeCascade.detectMultiScale(detection_gray)
# Draw the boxes with eyes
for (ex,ey,ew,eh) in glasses:
cv2.rectangle(color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
if glasses_count != None: glasses_count = glasses_count + len(glasses)
else: glasses_count = len(glasses)
eyes = eyeCascade.detectMultiScale(detection_gray)
# Draw the boxes with eyes
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
if eye_count != None: eye_count = eye_count + len(eyes)
else: eye_count = len(eyes)
eye_count = len(eyes)
boxes, weights = hog.detectMultiScale(gray, winStride=(8,8) )
boxes = np.array([[x, y, x + w, y + h] for (x, y, w, h) in boxes])
for (xA, yA, xB, yB) in boxes:
# display the detected boxes in the colour picture
cv2.rectangle(image, (xA, yA), (xB, yB), (0, 170, 252), 2)
print("Found {0} faces".format(face_count))
print("Found {0} glasses".format(glasses_count))
print("Found {0} eyes".format(eye_count))
cv2.imshow('Camera Input', image)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
camera.release()
cv2.destroyAllWindows()
opencv-python==4.1.1.26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment