Skip to content

Instantly share code, notes, and snippets.

@aallan
Last active August 19, 2018 22:31
Show Gist options
  • Save aallan/d6c878d0d74e074aed43d31eea619cbf to your computer and use it in GitHub Desktop.
Save aallan/d6c878d0d74e074aed43d31eea619cbf to your computer and use it in GitHub Desktop.
Example script using the Vision bonnet to detect faces in the camera frame and write the number of faces to a file.
#!/usr/bin/env python
import argparse
from aiy.vision.inference import CameraInference
from aiy.vision.models import face_detection
from examples.vision.annotator import Annotator
from picamera import PiCamera
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--num_frames',
'-n',
type=int,
dest='num_frames',
default=-1,
help='Sets the number of frames to run for, otherwise runs forever.')
args = parser.parse_args()
with PiCamera() as camera:
camera.sensor_mode = 4
camera.resolution = (1640, 1232)
camera.framerate = 30
camera.start_preview()
annotator = Annotator(camera, dimensions=(320, 240))
scale_x = 320 / 1640
scale_y = 240 / 1232
def transform(bounding_box):
x, y, width, height = bounding_box
return (scale_x * x, scale_y * y, scale_x * (x + width),
scale_y * (y + height))
with CameraInference(face_detection.model()) as inference:
for i, result in enumerate(inference.run()):
if i == args.num_frames:
break
faces = face_detection.get_faces(result)
annotator.clear()
for face in faces:
annotator.bounding_box(transform(face.bounding_box), fill=0)
annotator.update()
file = open("/home/pi/www/face_count.txt","w")
file.write('%d' % len(faces))
print('Iteration #%d: num_faces=%d' % (i, len(faces)))
file.close()
camera.stop_preview()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment