Posts: 1
Joined: Sun May 05, 2019 5:35 pm

How to fix "attributeerror: type object 'rpi.gpio.pwm' has no attribute 'servo' "?

Sun May 05, 2019 5:42 pm

Hi this is kind of urgent. I am running the code I got from this link :

https://learn.adafruit.com/raspberry-pi ... x/software

I want to imply the face recognition on a raspberry pi 3 B+.

However upon the following code I get the error of :

self.servo = PWM.Servo() attributeerror: type object 'rpi.gpio.pwm' has no attribute 'Servo'

I have tried many GPIO and other sudo installations but I'm getting nowhere
all the necessary dependencies are also installed

The main code is :

Code: Select all

"""Raspberry Pi Face Recognition Treasure Box
Positive Image Capture Script
Copyright 2013 Tony DiCola 

Run this script to capture positive images for training the face recognizer.
import glob
import os
import sys
import select

import cv2

import hardware
import config
import face

# Prefix for positive training image filenames.

def is_letter_input(letter):
        # Utility function to check if a specific character is available on stdin.
        # Comparison is case insensitive.
        if select.select([sys.stdin,],[],[],0.0)[0]:
                input_char = sys.stdin.read(1)
                return input_char.lower() == letter.lower()
        return False

if __name__ == '__main__':
	camera = config.get_camera()
	box = hardware.Box()
	# Create the directory for positive training images if it doesn't exist.
	if not os.path.exists(config.POSITIVE_DIR):
	# Find the largest ID of existing positive images.
	# Start new images after this ID value.
	files = sorted(glob.glob(os.path.join(config.POSITIVE_DIR, 
		POSITIVE_FILE_PREFIX + '[0-9][0-9][0-9].pgm')))
	count = 0
	if len(files) > 0:
		# Grab the count from the last filename.
		count = int(files[-1][-7:-4])+1
	print ('Capturing positive training images')
	print ('Press button or type c (and press enter) to capture an image.')
	print ('Press Ctrl-C to quit.')
	while True:
		# Check if button was pressed or 'c' was received, then capture image.
		if box.is_button_up() or is_letter_input('c'):
			print ('Capturing image...')
			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.')
			x, y, w, h = result
			# Crop image as close as possible to desired face aspect ratio.
			# Might be smaller if face is near edge of image.
			crop = face.crop(image, x, y, w, h)
			# Save image to file.
			filename = os.path.join(config.POSITIVE_DIR, POSITIVE_FILE_PREFIX + '%03d.pgm' % count)
			cv2.imwrite(filename, crop)
			print ('Found face and wrote training image'), filename
			count += 1

And the code related to hardware and servo is :

Code: Select all

import cv2

import RPi.GPIO as GPIO

from RPi.GPIO 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()
        GPIO.setup(config.BUTTON_PIN, RPIO.IN)
        # Set initial box state.
        self.button_state = GPIO.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)
        self.is_locked = True

    def unlock(self):
        """Unlock the box."""
        self.servo.set_servo(config.LOCK_SERVO_PIN, config.LOCK_SERVO_UNLOCKED)
        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 = GPIO.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.
            self.button_state = GPIO.input(config.BUTTON_PIN)
            if self.button_state == config.BUTTON_UP:
                return True
        return False

self.servo code is :

Code: Select all

# Raspberry Pi Face Recognition Box Servo Calibration Sketch
# Copyright 2013 Tony DiCola

from RPi.GPIO import PWM

import config

servo = PWM.Servo()

print 'Servo Calibration'
print 'Use this tool to find the pulsewidth values which move the'
print 'lock latch to the locked and unlocked position. Update config.py'
print 'with the locked and unlocked servo pulsewidth values.'
print 'Values range from 1000 to 2000 (in microseconds), with 1500 being the center.'
print 'Press Ctrl-C to quit'

while True:
	val = raw_input('Enter servo pulsewidth (1000 to 2000):')
		val = int(val)
	except ValueError:
		print 'Invalid value, must be between 1000 and 2000!'
	if val < 1000 or val > 2000:
		print 'Invalid value, must be between 1000 and 2000!'
	servo.set_servo(config.LOCK_SERVO_PIN, val)

User avatar
Posts: 314
Joined: Mon Dec 15, 2014 7:14 pm
Location: Noo Joysey, USA

Re: How to fix "attributeerror: type object 'rpi.gpio.pwm' has no attribute 'servo' "?

Sun May 05, 2019 11:48 pm

I don't think the following line of code is valid:

Code: Select all

servo = PWM.Servo()
If I check to see what attributes are available in RPi.GPIO PWM, here is what I see:

Code: Select all

>>> from Rpi.GPIO import PWM
>>> dir(PWM)
['ChangeDutyCycle', 'ChangeFrequency', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'start', 'stop']
Take a look at this article that explains how to use RPi.GPIO for servo control:

https://tutorials-raspberrypi.com/raspb ... r-control/

Return to “Python”