Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Snippet of code used for DevFest London 2017 to count faces in audience and send to Google Analytics (see
import io
import picamera
import cv2
import numpy
def hitGA(faces):
print("Sending to GA")
requests.get("" \
+ "&cid=1111" \
+ "&t=event" \
+ "&ec=FaceDetection" \
+ "&ea=faces" \
+ "&el=DevFest17"
+ "&ev=" + faces).close
#Based on Face detection with Raspberry Pi
#For org. + setup
#Modified by mhawksey
while True:
#Create a memory stream so photos doesn't need to be saved in a file
stream = io.BytesIO()
#Here you can also specify other parameters (e.g.:rotate the image)
with picamera.PiCamera() as camera:
camera.resolution = (2592, 1944)
camera.iso = 800
camera.capture(stream, format='jpeg')
#Convert the picture into a numpy array
buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)
#Now creates an OpenCV image
image = cv2.imdecode(buff, 1)
#Load a cascade file for detecting faces
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml')
#Convert to grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#Look for faces in the image using the loaded cascade file
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
print ("Found " + str(facesInt) + " face(s)")
#Send faces counted to GA
#Draw a rectangle around every found face
for (x,y,w,h) in faces:
#Show the result image
imS = cv2.resize(image, (640, 360))
cv2.imshow('frame', imS)
k = cv2.waitKey(1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment