1
\$\begingroup\$

The code is about an autonomous driving Rc car. In the first code I have created a function that imports a haar cascade for detecting a stop sign. The second code is the code that I run and test if the car can detect the stop sign and once doing so it should stop

Problem: I having trouble importing/calling this self.faces into drive.py After importing I will just add an if.statement so the car stops the moment is detects the stop sign

import os
import time
import numpy as np
from PIL import Image
import glob
import numpy as np
import cv2


class BaseCamera:

    def run_threaded(self):
        return self.frame


class Webcam(BaseCamera):
    def __init__(self, resolution=(120, 160), framerate=20):
        from picamera.array import PiRGBArray
        from picamera import PiCamera
        resolution = (resolution[1], resolution[0])
        # initialize the camera and stream
        self.camera = PiCamera()  # PiCamera gets resolution (height, width)
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.rawCapture = PiRGBArray(self.camera, size=resolution)
        self.stream = self.camera.capture_continuous(self.rawCapture,
                                                     format="rgb",
                                                     use_video_port=True)

        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.frame = None
        self.on = True

        print('PiCamera loaded.. .warming camera')
        time.sleep(2)

    def run(self):
        f = next(self.stream)
        frame = f.array
        self.rawCapture.truncate(0)
        return frame

    def update(self):
        # keep looping infinitely until the thread is stopped
        for f in self.stream:
            # grab the frame from the stream and clear the stream in
            # preparation for the next frame
            self.frame = f.array
            self.rawCapture.truncate(0)

            # if the thread indicator variable is set, stop the thread
            if not self.on:
                break

    def shutdown(self):
        # indicate that the thread should be stopped
        self.on = False
        print('stoping PiCamera')
        time.sleep(.5)
        self.stream.close()
        self.rawCapture.close()
        self.camera.close()

class PiCamera(BaseCamera):
    def __init__(self, resolution=(160, 120), framerate=20):
        import pygame
        import pygame.camera

        super().__init__()
        pygame.camera.init()
        l = pygame.camera.list_cameras()
        self.cam=pygame.camera.Camera(l[0],resolution,"RGB")
        self.resolution=resolution
        self.cam.start()
        self.framerate=framerate

        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.frame = None
        self.on = True
        self.faces= []

        print('Webcam loaded.. .warming camera')
        time.sleep(2)


    def update(self):
        from datetime import datetime,timedelta
        import pygame.image
        while self.on:

            start=datetime.now()

            if self.cam.query_image():
                face_cascade = cv2.CascadeClassifier('/home/pi/Downloads/stopsigns-master/stopsign_classifier.xml')
                snapshot = self.cam.get_image()
                snapshot1 = pygame.transform.scale(snapshot,self.resolution)
                self.frame=pygame.surfarray.pixels3d(pygame.transform.rotate(pygame.transform.flip(snapshot,True,False),90))
               # detect=np.asarray(snapshot1)
                self.faces = face_cascade.detectMultiScale(self.frame, 1.3, 5)
                #print(self.faces)
            stop=datetime.now()
            s = 1 / self.framerate - (stop - start ).total_seconds()
            if s>0:
                time.sleep(s)
        self.cam.stop()

    def run_threaded(self):
        return self.frame 

    def shutdown(self):
        # indicate that the thread should be stopped
        self.on = False
        print('stoping WebCamera')
        time.sleep(.5)

Drive.py file

import os
from docopt import docopt

import donkeycar as dk
from donkeypart_picamera import PiCamera
from donkeypart_keras_behavior_cloning import KerasLinear
from donkeypart_PCA9685_actuators import PCA9685, PWMSteering, PWMThrottle
from donkeypart_tub import TubWriter
from donkeypart_web_controller import LocalWebController
from donkeypart_common import Timestamp


def drive(cfg, model_path=None, use_chaos=False):
    """
    """

    V = dk.vehicle.Vehicle()

    clock = Timestamp()
    V.add(clock, outputs=['timestamp'])

    cam = PiCamera(resolution=cfg.CAMERA_RESOLUTION)
    V.add(cam, outputs=['cam/image_array'], threaded=True)
    mystring=cam.self.faces


    ctr = LocalWebController(use_chaos=use_chaos)
    V.add(ctr,
          inputs=['cam/image_array'],
          outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'],
          threaded=True)

    # See if we should even run the pilot module.
    # This is only needed because the part run_condition only accepts boolean

    pilot_condition_part = MakeRunConditionBoolean()
    V.add(pilot_condition_part,
          inputs=['user/mode'],
          outputs=['run_pilot'])

    # Run the pilot if the mode is not user.
    kl = KerasLinear()
    if model_path:
        kl.load(model_path)

    V.add(kl,
          inputs=['cam/image_array'],
          outputs=['pilot/angle', 'pilot/throttle'],
          run_condition='run_pilot')

    state_controller = StateController()
    V.add(state_controller,
          inputs=['user/mode',
                  'user/angle', 'user/throttle',
                  'pilot/angle', 'pilot/throttle'],
          outputs=['angle', 'throttle'])

    steering_controller = PCA9685(cfg.STEERING_CHANNEL)
    steering = PWMSteering(controller=steering_controller,
                           left_pulse=cfg.STEERING_LEFT_PWM,
                           right_pulse=cfg.STEERING_RIGHT_PWM) 

    throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL)
    throttle = PWMThrottle(controller=throttle_controller,
                           max_pulse=cfg.THROTTLE_FORWARD_PWM,
                           zero_pulse=cfg.THROTTLE_STOPPED_PWM,
                           min_pulse=cfg.THROTTLE_REVERSE_PWM)

    V.add(steering, inputs=['angle'])
    V.add(throttle, inputs=['throttle'])

    # add tub to save data
    inputs = ['cam/image_array', 'user/angle', 'user/throttle', 'user/mode', 'timestamp']
    types = ['image_array', 'float', 'float',  'str', 'str']

    # single tub
    tub = TubWriter(path=cfg.TUB_PATH, inputs=inputs, types=types)
    V.add(tub, inputs=inputs, run_condition='recording')

    # run the vehicle
    V.start(rate_hz=cfg.DRIVE_LOOP_HZ)



class MakeRunConditionBoolean:
    def run(self, mode):
        if mode == 'user':
            return False
        else:
            return True


class StateController:
    """
    Wraps a function into a donkey part.
    """

    def __init__(self):
        pass

    def run(self, mode,
            user_angle, user_throttle,
            pilot_angle, pilot_throttle):

        """
        Returns the angle, throttle and boolean if autopilot should be run.
        The angle and throttles returned are the ones given to the steering and
        throttle actuators.
        """

        if mode == 'user':
            #mystring=cam.faces

            print(user_angle[0])
            return user_angle, user_throttle


        elif mode == 'local_angle':
            return pilot_angle, user_throttle

        else:
            return pilot_angle, pilot_throttle


if __name__ == '__main__':
    args = docopt(__doc__)
    cfg = dk.load_config()

    drive(cfg, model_path=args['--model'])
\$\endgroup\$
  • 2
    \$\begingroup\$ I am actually pretty confused of what exactly you're asking. Does your code work as expected or not? If it's the latter, your question is unfortunately off-topic here. \$\endgroup\$ – Grajdeanu Alex. Aug 18 '19 at 17:36
  • \$\begingroup\$ Im sorry but I still I think it belongs here. I having calling self.faces into drive.py \$\endgroup\$ – Miriam List Aug 18 '19 at 17:44
  • \$\begingroup\$ Does or doesn't the code work as intended? Because it reads like you're having import problems. But it isn't entirely clear either way. If there are problems preventing this code to work as intended, fix those first. After that, feel free to come back and we'll help you do it in a better/cleaner way. \$\endgroup\$ – Mast Aug 19 '19 at 5:45
  • \$\begingroup\$ @Mast the code works, however there are many other files that are included. I was trying to call that self.faces from try.py inside drive.py \$\endgroup\$ – Miriam List Aug 19 '19 at 6:10

Browse other questions tagged or ask your own question.