Facelock

This is a Python script that uses OpenCV to watch your face while you use your computer. If it cannot see your face, it locks your screen.

The Code

I put the code right up front for those who want it. This is still a work in progress, so read the description below to see what you are getting.

	import cv
	haar = "/usr/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml"
	def detect_faces(image):
		detected = cv.HaarDetectObjects(image, pattern, mem, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100))
		if detected:
			return True
		else:
			return False
	capture = cv.CaptureFromCAM(-1)
	mem = cv.CreateMemStorage()
	pattern = cv.Load(haar)
	while True:
		image = cv.QueryFrame(capture)
		if detect_faces(image):
			print "I see you"
		else:
			print "Where are you?"
			call(["xscreensaver-command", "-lock"])

There are some issues that I have with this code that I'm trying to figure out. It is basic Python syntax that isn't working as I feel it should.

  • If I return detected in the detect_faces function, it always returns a True. So, I have to do an if-else to return True or False. I want to remove the function all together and make the "if detect_faces" a direct call to "if cv.HaarDetectObjects".
  • I tried "if not detect_faces", but that didn't work. So, I am stuck with yet another if-else. Python logic is not very logical.
  • I added a time.sleep to the while True to slow down how much it polls. But, if I do that, it buffers the video stream. QueryFrame doesn't get the current frame. It gets the one after the last one you fetched. How can I tell QueryFrame to get the current frame and stop buffering old frames?

Work in Progress

First, I must state that I do not have time to do any projects. This is something I work on when I'm on a phone meeting and I really don't want to listen to anyone. It keeps me just a hair closer to the sanity side of life.

The idea here is to use a cam to watch a person's face. If the computer cannot see the person, lock the screen. Obviously, you don't want it to lock if you glance away for a second, so I'm planning to have it wait until it cannot see you for five seconds and then lock. The time delay should be adjustable.

Right now, I can detect a face. If the face is visible, it prints "I see you." If the face is not visible, it prints "Where are you?" and locks the screen using xscreenlock. The function used to lock the screen should also be an option to adjust.

Once the screen is locked, this should recognize so and just go into a polling state, waiting for the screen to unlock. The assumption is that once the screen is unlocked, the person sitting at the computer is an authorized user. So, it will watch that face and wait for it to go away. If it goes away for more than five seconds, it locks the screen again and goes into a polling state.

You've read it. You can't unread it.
Copyright ©1998-2017 C. Shaun Wagner. All rights reserved.