Raspberry Pi locking door

General project help for Adafruit customers

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
User avatar
tdicola
 
Posts: 1074
Joined: Thu Oct 17, 2013 9:11 pm

Re: Raspberry Pi locking door

Post by tdicola »

Oh sorry should have clarified, after you clone the repository then navigate inside it to run the script. So the full steps are:

Code: Select all

sudo apt-get update && sudo apt-get install git && git clone https://github.com/tdicola/pi-facerec-box.git
cd pi-facerec-box
sudo ./install_dependencies.sh

Kairouz
 
Posts: 28
Joined: Wed Sep 11, 2013 4:05 am

Re: Raspberry Pi locking door

Post by Kairouz »

AWESOME!! It works! however im am struggling to adapt it to suit a solenoid rather than a servo, could you please advise the necessary changes to the files that need to be performed.

Thanks again!

User avatar
tdicola
 
Posts: 1074
Joined: Thu Oct 17, 2013 9:11 pm

Re: Raspberry Pi locking door

Post by tdicola »

Awesome, glad you were able to get the recognition to work! To use a solenoid you'll want to be careful about how you hook it up, since the solenoid needs a decent amount of current to turn on/off. Check out this knock activated door lock for a good wiring diagram that shows using a power mosfet to drive the solenoid from a GPIO line of an Arduino: https://learn.adafruit.com/secret-knock ... k/overview You'll want to do something similar, but connect to one of your GPIO pins on the Raspberry Pi. Be careful though as the solenoid requires 12 volts to drive and the Pi can only be driven by 5 volts. You'll need a separate 12 volt power supply for the solenoid--here's a small write up that describes using a few AA batteries to power a solenoid with a Pi. Then it's just a matter of switching the GPIO line high or low to engage or disengage the solenoid.

To modify the code, you'll want to change the Box class in hardware.py in a few small ways:

- In the __init__ function that intializes the box comment the line that initializes the servo and add right below it a line to initialize the GPIO line that will drive the solenoid. For example assuming GPIO 23 is hooked up to the solenoid, you would make it look something like:

Code: Select all

def __init__(self):
		# Initialize lock servo and button.
		# self.servo = PWM.Servo()
		RPIO.setup(23, RPIO.OUT)
		RPIO.setup(config.BUTTON_PIN, RPIO.IN)
		# Set initial box state.
		self.button_state = RPIO.input(config.BUTTON_PIN)
		self.is_locked = None
You can see I added the RPIO.setup(23, RPIO.OUT) command which initializes the GPIO 23 pin as a digital output.

- Then in the lock and unlock functions you just need to change so the GPIO pin is set high or low appropriately instead of moving the servo. For example these might look like, again assuming GPIO 23 and that the solenoid is locked when the signal is high:

Code: Select all

	def lock(self):
		"""Lock the box."""
		# self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_LOCKED)
		RPIO.output(23, RPIO.HIGH)
		self.is_locked = True

	def unlock(self):
		"""Unlock the box."""
		# self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_UNLOCKED)
		RPIO.output(23, RPIO.LOW)
		self.is_locked = False
You can see I commented the servo line and added a line below to set GPIO 23 high or low.

That should be all you need to do to switch the code to use a solenoid by setting a GPIO pin high or low. What you might want to do is start out by changing the code over to the above and then connecting an LED with a small resistor (like 300 or so ohms) to the GPIO pin that will control the solenoid. Check that when the box locks and unlocks the LED turns on and off appropriately. Then move on to replacing the LED with the mosfet, solenoid, etc. Good luck!

Kairouz
 
Posts: 28
Joined: Wed Sep 11, 2013 4:05 am

Re: Raspberry Pi locking door

Post by Kairouz »

Sorry for such a late reply but i am on school holidays and had left the project at school over the break. I had a holiday session today and made the appropriate changes as stated to the hardware.py script. However then running the main script i receive the following error
20140709_105227 (Small).jpg
20140709_105227 (Small).jpg (87.23 KiB) Viewed 724 times
Sorry to be a pain

Thanks

User avatar
tdicola
 
Posts: 1074
Joined: Thu Oct 17, 2013 9:11 pm

Re: Raspberry Pi locking door

Post by tdicola »

No problem, it looks like Python is complaining about the indentation of the line. Python is really strict about indentation and whitespace and it can be a little annoying when it isn't happy. Can you post the full code of box.py? That should help troubleshoot where the indentation and whitespace might be wrong.

Kairouz
 
Posts: 28
Joined: Wed Sep 11, 2013 4:05 am

Re: Raspberry Pi locking door

Post by Kairouz »

Here you go

box.py

Code: Select all

"""Raspberry Pi Face Recognition Treasure Box
Treasure Box Script
Copyright 2013 Tony DiCola 
"""
import cv2

import config
import face
import hardware


if __name__ == '__main__':
	# Load training data into model
	print 'Loading training data...'
	model = cv2.createEigenFaceRecognizer()
	model.load(config.TRAINING_FILE)
	print 'Training data loaded!'
	# Initialize camer and box.
	camera = config.get_camera()
	box = hardware.Box()
	# Move box to locked position.
	box.lock()
	print 'Running box...'
	print 'Press button to lock (if unlocked), or unlock if the correct face is detected.'
	print 'Press Ctrl-C to quit.'
	while True:
		# Check if capture should be made.
		# TODO: Check if button is pressed.
		if box.is_button_up():
			if not box.is_locked:
				# Lock the box if it is unlocked
				box.lock()
				print 'Box is now locked.'
			else:
				print 'Button pressed, looking for face...'
				# Check for the positive face and unlock if found.
				image = camera.read()
				# Convert image to grayscale.
				image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
				# Get coordinates of single face in captured image.
				result = face.detect_single(image)
				if result is None:
					print 'Could not detect single face!  Check the image in capture.pgm' \
						  ' to see what was captured and try again with only one face visible.'
					continue
				x, y, w, h = result
				# Crop and resize image to face.
				crop = face.resize(face.crop(image, x, y, w, h))
				# Test face against model.
				label, confidence = model.predict(crop)
				print 'Predicted {0} face with confidence {1} (lower is more confident).'.format(
					'POSITIVE' if label == config.POSITIVE_LABEL else 'NEGATIVE', 
					confidence)
				if label == config.POSITIVE_LABEL and confidence < config.POSITIVE_THRESHOLD:
					print 'Recognized face!'
					box.unlock()
				else:
					print 'Did not recognize face!'
hardware.py

Code: Select all

"""Raspberry Pi Face Recognition Treasure Box
Treasure Box Class
Copyright 2013 Tony DiCola 
"""
import time

import cv2
import RPIO
from RPIO import PWM

import picam
import config
import face


class Box(object):
	"""Class to represent the state and encapsulate access to the hardware of 
	the treasure box."""
def __init__(self):
      # Initialize lock servo and button.
      # self.servo = PWM.Servo()
      RPIO.setup(23, RPIO.OUT)
      RPIO.setup(config.BUTTON_PIN, RPIO.IN)
      # Set initial box state.
      self.button_state = RPIO.input(config.BUTTON_PIN)
      self.is_locked = None

	  def lock(self):
          """Lock the box."""
          # self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_LOCKED)
          RPIO.output(23, RPIO.HIGH)
          self.is_locked = True

       def unlock(self):
          """Unlock the box."""
          # self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_UNLOCKED)
          RPIO.output(23, RPIO.LOW)
          self.is_locked = False

	def is_button_up(self):
		"""Return True when the box button has transitioned from down to up (i.e.
		the button was pressed)."""
		old_state = self.button_state
		self.button_state = RPIO.input(config.BUTTON_PIN)
		# Check if transition from down to up
		if old_state == config.BUTTON_DOWN and self.button_state == config.BUTTON_UP:
			# Wait 20 milliseconds and measure again to debounce switch.
			time.sleep(20.0/1000.0)
			self.button_state = RPIO.input(config.BUTTON_PIN)
			if self.button_state == config.BUTTON_UP:
				return True
		return False

User avatar
tdicola
 
Posts: 1074
Joined: Thu Oct 17, 2013 9:11 pm

Re: Raspberry Pi locking door

Post by tdicola »

Oh it looks like the issue is the indentation is a little off for some of the functions. Python is really strict about indenting blocks of code. You can use tabs or spaces, but it needs to be consistent and all the same size. The _init_ function in particular isn't indented like the rest of the class functions so that's causing the error. When in doubt stick with an indentation of 4 spaces. Here's a good page to check out with more info on indentation rules: https://docs.python.org/release/2.5.1/r ... ation.html

Take a look at the code attached, this should have the right indentation levels using 4 spaces.

hardware.py:

Code: Select all

"""Raspberry Pi Face Recognition Treasure Box
Treasure Box Class
Copyright 2013 Tony DiCola 
"""
import time

import cv2
import RPIO
from RPIO import PWM

import picam
import config
import face


class Box(object):
    """Class to represent the state and encapsulate access to the hardware of 
    the treasure box."""
    def __init__(self):
        # Initialize lock servo and button.
        # self.servo = PWM.Servo()
        RPIO.setup(23, RPIO.OUT)
        RPIO.setup(config.BUTTON_PIN, RPIO.IN)
        # Set initial box state.
        self.button_state = RPIO.input(config.BUTTON_PIN)
        self.is_locked = None

    def lock(self):
        """Lock the box."""
        # self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_LOCKED)
        RPIO.output(23, RPIO.HIGH)
        self.is_locked = True

    def unlock(self):
        """Unlock the box."""
        # self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_UNLOCKED)
        RPIO.output(23, RPIO.LOW)
        self.is_locked = False

    def is_button_up(self):
        """Return True when the box button has transitioned from down to up (i.e.
        the button was pressed)."""
        old_state = self.button_state
        self.button_state = RPIO.input(config.BUTTON_PIN)
        # Check if transition from down to up
        if old_state == config.BUTTON_DOWN and self.button_state == config.BUTTON_UP:
           # Wait 20 milliseconds and measure again to debounce switch.
           time.sleep(20.0/1000.0)
           self.button_state = RPIO.input(config.BUTTON_PIN)
           if self.button_state == config.BUTTON_UP:
              return True
        return False


Kairouz
 
Posts: 28
Joined: Wed Sep 11, 2013 4:05 am

Re: Raspberry Pi locking door

Post by Kairouz »

Ok so now it can successfully load the training data but cannot proceed any further, here is the error:
Capture5.JPG
Capture5.JPG (24.73 KiB) Viewed 704 times
Thanks

User avatar
tdicola
 
Posts: 1074
Joined: Thu Oct 17, 2013 9:11 pm

Re: Raspberry Pi locking door

Post by tdicola »

Hrm, double check the code copied over correctly. It looks like it can't find the lock function defined on the Box class in hardware.py, but if you scroll up and look at the hardware.py code the lock function is defined there:

Code: Select all

def lock(self):
        """Lock the box."""
        # self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_LOCKED)
        RPIO.output(23, RPIO.HIGH)
        self.is_locked = True

Kairouz
 
Posts: 28
Joined: Wed Sep 11, 2013 4:05 am

Re: Raspberry Pi locking door

Post by Kairouz »

Tony you are a champion! It works!! however i have one slight issue, whenever i try to change the positive threshold value it causes this error to occur:
20140717_150347 (Medium).jpg
20140717_150347 (Medium).jpg (133.31 KiB) Viewed 675 times
However, whenever i change it back to 2000 its fine.

Also, i ended up taking 20 different photos for the positive data, all with different angles/expressions etc. Would too many cause "confusion" or inaccuracy when trying to find a positive match? as the numbers range between 2200 to 2900.

Thanks again

Kairouz
 
Posts: 28
Joined: Wed Sep 11, 2013 4:05 am

Re: Raspberry Pi locking door

Post by Kairouz »

please advice as soon as possible.

User avatar
tdicola
 
Posts: 1074
Joined: Thu Oct 17, 2013 9:11 pm

Re: Raspberry Pi locking door

Post by tdicola »

Ack sorry, missed your reply earlier. Hrm, the error looks like it's potentially running out of memory or other resources. If you run raspi-config (execute 'sudo raspi-config' without quotes) and check the memory split between CPU & GPU (it's in the advanced options menu, can see more details here), what value is currently set? If you bump it up to give 128 or even 256 megabytes of memory to the GPU does that help? Also try bumping it down to a low value like 64 megabytes for the GPU.

One other option is to use less positive images. If you grab only about ~5 images, does that let you adjust the threshold?

User avatar
happouch
 
Posts: 1
Joined: Sat Apr 02, 2016 8:34 am

Re: Raspberry Pi locking door

Post by happouch »

hi,thanks for the tuto,i have a problem when i run
box.py it recognize all the faces it must recognize just the faces which
exist in positive and negatives folder please help

User avatar
charudatt
 
Posts: 1
Joined: Sat Sep 24, 2016 12:02 am

Re: Raspberry Pi locking door

Post by charudatt »

box.py giving error towards the end

label,confidence = model.predective(crop)
TypeError: 'int' object is not iterable.

this is using OpenCV3.1

anyhelp.

Locked
Please be positive and constructive with your questions and comments.

Return to “General Project help”