Create a gist now

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 and update image in Google Slides (see
import io
import picamera
import cv2
import numpy
import requests
import base64
def hitGA(faces):
print("Sending to GA")
requests.get("" \
+ "&cid=1111" \
+ "&t=event" \
+ "&ec=FaceDetection" \
+ "&ea=faces" \
+ "&el=DevFest17"
+ "&ev=" + faces).close
maxFaces = -1
#Setup posting result to Slides
# prepare headers for http request
content_type = 'image/jpeg'
headers = {'content-type': content_type}
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)
facesInt = len(faces)
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:
#Save the result image if new maximum
if facesInt > maxFaces:
retval, buffer = cv2.imencode('.jpg', image)
img_encoded = base64.b64encode(buffer)
response =, data=img_encoded, headers=headers)
maxFaces = facesInt
print (response.text)
#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