Пример #1
0
from pyparrot.Anafi import Anafi
anafi = Anafi(drone_type="Anafi", ip_address="192.168.42.1")
anafi.set_indoor(0)
print("connecting")
success = anafi.connect(
    10)  #Continously attempts to 10 times until the drone is connected
print(success)
print("sleeping")
anafi.smart_sleep(
    5
)  # Use this which handles packets received while sleeping   Parameters:	timeout – number of seconds to sleep
print("taking off")
anafi.safe_takeoff(
    5
)  #Sends commands to takeoff until the mambo reports it is taking off   Parameters:	timeout – quit trying to takeoff if it takes more than timeout seconds
anafi.smart_sleep(1)  #delays before movement
print("moving")

anafi.fly_direct(0, 0, 90, 0,
                 2)  #fly_direct(roll, pitch, yaw, vertical_movement, duration)
#anafi.fly_direct(0,0,0,0,1) #fly_direct(roll, pitch, yaw, vertical_movement, duration)
print("Decending")

print("landing")
anafi.safe_land(
    5
)  #Ensure the mambo lands by sending the command until it shows landed on sensors
print("DONE - disconnecting")
anafi.disconnect()
Пример #2
0

class UserVision:
    def __init__(self, vision):
        self.index = 0
        self.vision = vision

    def save_pictures(self, args):
        img = self.vision.get_latest_valid_picture()
        if img is not None and WRITE_IMAGES:
            cv2.imwrite(f"image_{self.index:06d}.png", img)
            self.index += 1


if __name__ == "__main__":
    anafi = Anafi()

    if anafi.connect(num_retries=3):
        print("Anafi connected")

        # State information
        print("Updating state information")
        anafi.smart_sleep(1)
        anafi.ask_for_state_update()
        anafi.smart_sleep(1)

        # Vision
        print("Starting vision")
        anafi_vision = DroneVision(anafi, Model.ANAFI)
        user_vision = UserVision(anafi_vision)
        anafi_vision.set_user_callback_function(user_vision.save_pictures,
Пример #3
0
"""
Flies the Anafi in a fairly wide arc.  You want to be sure you have room for this. (it is commented
out but even what is here is still going to require a large space)

Author: Amy McGovern
"""
from pyparrot.Anafi import Anafi
import math

Anafi = Anafi()

print("connecting")
success = Anafi.connect(10)
print(success)

print("sleeping")
#Anafi.smart_sleep(5)

Anafi.ask_for_state_update()

#print("Flying direct: going forward (positive pitch)")
#Anafi.fly_direct(roll=0, pitch=50, yaw=0, vertical_movement=0, duration=1)

#print("Flying direct: yaw")
#Anafi.fly_direct(roll=0, pitch=0, yaw=50, vertical_movement=0, duration=1)

#print("Flying direct: going backwards (negative pitch)")
#Anafi.fly_direct(roll=0, pitch=-50, yaw=0, vertical_movement=0, duration=0.5)

#print("Flying direct: roll")
#Anafi.fly_direct(roll=50, pitch=0, yaw=0, vertical_movement=0, duration=1)
Пример #4
0
from pyparrot.Anafi import Anafi
anafi = Anafi(drone_type="Anafi", ip_address="192.168.42.1")
print("connecting")
success = anafi.connect(10)
print(success)
print("sleeping")
anafi.smart_sleep(5)
print("taking off")
anafi.safe_takeoff(5)
anafi.smart_sleep(1)
print("moving")
anafi.move_relative(dx=1, dy=0, dz=0, dradians=0)
print("landing")
anafi.safe_land(5)
print("DONE - disconnecting")
anafi.disconnect()
Пример #5
0
"""
Demo the trick flying for the python interface

Author: Amy McGovern
"""

from pyparrot.Anafi import Anafi

# you will need to change this to the address of YOUR anafi
mamboAddr = "e0:14:d0:63:3d:d0"

# make my anafi object
# remember to set True/False for the wifi depending on if you are using the wifi or the BLE to connect
anafi = Anafi(mamboAddr, use_wifi=True)

print("trying to connect")
success = anafi.connect(num_retries=3)
print("connected: %s" % success)

if (success):
    # get the state information
    print("sleeping")
    anafi.smart_sleep(2)
    anafi.ask_for_state_update()
    anafi.smart_sleep(2)

    print("taking off!")
    anafi.safe_takeoff(5)

    if (anafi.sensors.flying_state != "emergency"):
        print("flying state is %s" % anafi.sensors.flying_state)
def main():

    print("connecting")
    if not debug_mode:
        anafi = Anafi(drone_type="Anafi", ip_address="192.168.42.1")
        success = anafi.connect(10)
    elif debug_mode:
        success = True

    if (success):
        if not debug_mode:
            anafi.ask_for_state_update()
            print(anafi.sensors.flying_state)
        '''
                #vision
                print("Starting vision")
                anafi_vision = DroneVision(anafi, Model.ANAFI)
                user_vision = UserVision(anafi_vision)
                anafi_vision.set_user_callback_function(
                    user_vision.save_pictures, user_callback_args=None
                )
        
            #video
                if anafi_vision.open_video():
                    print("Opened video feed")
                    print("Sleeping for 15 seconds - move Anafi around to test feed")
                    anafi.smart_sleep(15)
                    print("Closing video feed")
                    anafi_vision.close_video()
                    anafi.smart_sleep(5)
                else:
                    print("Could not open video feed")
        
        '''
        '''
        print("Preparing to open video stream")
        anafi_vision = DroneVisionGUI(
            anafi,
            Model.ANAFI,
            buffer_size=200,
            user_code_to_run=demo_anafi_user_vision,
            user_args=(anafi,),
        )
        user_vision = UserVision(anafi_vision)
        anafi_vision.set_user_callback_function(
            user_vision.save_pictures, user_callback_args=None
        )

        print("Opening video stream")
        anafi_vision.open_video()

        anafi.smart_sleep(10)
        '''

        command_flag = 1
        fly_flag = 0
        land_flag = 0
        right_flag = 0
        left_flag = 0
        drone_status = 0  # 0 : on the ground ; 1 : in the air

        while command_flag == 1:
            with open(filename, "r+") as new:
                command = new.readline().lower()
                if command == "fly":
                    fly_flag = 1
                    new.truncate(0)
                    new.close()

                elif command == "land":
                    land_flag = 1
                    new.truncate(0)
                    new.close()

                elif command == "turn right":
                    right_flag = 1
                    new.truncate(0)
                    new.close()

                elif command == "turn left":
                    left_flag = 1
                    new.truncate(0)
                    new.close()

                else:
                    print("No new commands")

            # take-off when 'takeoff' & drone is on the ground
            if fly_flag == 1 and drone_status == 0:
                print("Take off")
                if not debug_mode:
                    anafi.safe_takeoff(5)
                drone_status = 1
                fly_flag = 0

            # land when 'land' & drone is in the air
            if land_flag == 1 and drone_status == 1:
                print("Land")
                if not debug_mode:
                    anafi.safe_land(5)
                land_flag = 0
                drone_status = 0
                command_flag = 0

            # turn when 'turn right" & drone is in the air
            if right_flag == 1 and drone_status == 1:
                print("Turn Right 30 degree")
                if not debug_mode:
                    anafi.move_relative(dx=0, dy=0, dz=0, dradians=np.pi / 6)
                right_flag = 0

            #turn when 'turn left" & drone is in the air
            if left_flag == 1 and drone_status == 1:
                print("Turn Left 30 degree")
                if not debug_mode:
                    anafi.move_relative(dx=0, dy=0, dz=0, dradians=-np.pi / 6)
                left_flag = 0

            time.sleep(1)

        print("DONE - disconnecting")
        if not debug_mode:
            anafi.disconnect()
    else:
        print("Error connecting Anafi")
Пример #7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p",
                        "--weight_path",
                        required=True,
                        type=str,
                        help="Path to load weights for the model.")
    parser.add_argument(
        "-a",
        "--pyparrot_path",
        required=True,
        type=str,
        help="Path to pyparrot module downloaded from amymcgovern on github.",
    )
    parser.add_argument("-w",
                        "--img_width",
                        required=False,
                        default=28,
                        type=int,
                        help="Image width.")
    parser.add_argument("-n",
                        "--num_classes",
                        required=False,
                        default=7,
                        type=int,
                        help="Number of classes.")
    parser.add_argument(
        "-c",
        "--crop",
        required=False,
        default=None,
        type=str,
        help="Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\
              Set -1 for the unchanged ones",
    )
    parser.add_argument(
        "-r",
        "--resize",
        required=False,
        default=None,
        type=str,
        help="Resize shape, format: height,width",
    )
    parser.add_argument(
        "-b",
        "--binarize",
        required=False,
        default=None,
        type=str,
        help="To binarize images, format for thresholding: min,max",
    )
    parser.add_argument("-g",
                        "--gray",
                        required=False,
                        action="store_true",
                        help="To save 1-channel images")
    parser.add_argument(
        "-e",
        "--erode",
        required=False,
        default=None,
        type=str,
        help="Erode option, format: kernel_size,iteration",
    )
    parser.add_argument(
        "-d",
        "--dilate",
        required=False,
        default=None,
        type=str,
        help="Dilate option, format: kernel_size,iteration",
    )
    parser.add_argument("-m",
                        "--camid",
                        required=False,
                        default=0,
                        type=int,
                        help="Camera ID, default is 0")
    parser.add_argument(
        "-t",
        "--tensorflow",
        required=False,
        action="store_true",
        help="To specify if Tensorflow model is used.",
    )
    parser.add_argument(
        "-z",
        "--number_of_confimation",
        required=False,
        default=3,
        type=int,
        help="Minimum number of identical commands before sending to drone.",
    )

    args = parser.parse_args()
    """
    Drone connection
    """
    sys.path.append(args.pyparrot_path)
    from pyparrot.Anafi import Anafi

    print("Connecting to drone...")
    anafi = Anafi(drone_type="Anafi", ip_address="192.168.42.1")
    success = anafi.connect(10)
    print(success)
    print("Sleeping few seconds...")
    anafi.smart_sleep(3)
    """
    Load model
    """
    print("Loading model...")
    input_size = args.img_width**2
    num_class = args.num_classes
    hidden_size = 128

    if args.tensorflow:
        import tensorflow as tf

        model = tf.keras.models.load_model(args.weight_path)
    else:
        script_path = os.path.realpath(__file__)
        sys.path.append(os.path.dirname(script_path) + "/../")
        from homemade_framework import framework as NN

        model = NN.Sequential(
            [
                NN.Linear(input_size, hidden_size),
                NN.LeakyReLU(),
                NN.BatchNorm(),
                NN.Linear(hidden_size, hidden_size),
                NN.LeakyReLU(),
                NN.BatchNorm(),
                NN.Linear(hidden_size, num_class),
                NN.Softmax(),
            ],
            NN.LossMSE(),
        )
        model.load(args.weight_path)
    """
    Webcam process
    """
    print("Start webcam...")
    cam = cv2.VideoCapture(args.camid)
    ret, frame = cam.read()

    min_height, max_height = 0, frame.shape[0]
    min_width, max_width = 0, frame.shape[1]
    print("Cam resolution: {}x{}".format(max_width, max_height))
    if args.crop is not None:
        res = [int(x) for x in args.crop.split(',')]
        if res[0] != -1:
            min_width = res[0]
        if res[1] != -1:
            max_width = res[1]
        if res[2] != -1:
            min_height = res[2]
        if res[3] != -1:
            max_height = res[3]
        print("Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\
              , {},{}".format(min_width, max_width, min_height, max_height))
    pause = False
    imgs = []

    while True:
        ret, frame = cam.read()
        if not ret:
            print("failed to grab frame")
            break
        if args.crop is not None:
            frame = frame[min_height:max_height, min_width:max_width]
        cv2.imshow("Original image", frame)

        k = cv2.waitKey(1)
        if k % 256 == 27:
            # ESC pressed
            print("Escape hit, closing...")
            break
        elif k % 256 == ord('p'):
            # p pressed
            if pause:
                pause = False
            else:
                pause = True

        if not pause:
            if args.gray:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            if args.binarize:
                frame = cv2.medianBlur(frame, 5)
                min_thresh, max_thresh = [
                    int(x) for x in args.binarize.split(',')
                ]
                ret, frame = cv2.threshold(frame, min_thresh, max_thresh,
                                           cv2.THRESH_BINARY)
            if args.erode is not None:
                k_size, iteration = [int(x) for x in args.erode.split(',')]
                kernel = np.ones((k_size, k_size), np.uint8)
                frame = cv2.erode(frame, kernel, iterations=int(iteration))
            if args.dilate is not None:
                k_size, iteration = [int(x) for x in args.dilate.split(',')]
                kernel = np.ones((k_size, k_size), np.uint8)
                frame = cv2.dilate(frame, kernel, iterations=int(iteration))

            if args.resize:
                height, width = [int(size) for size in args.resize.split(',')]
                frame = cv2.resize(frame, (height, width),
                                   interpolation=cv2.INTER_AREA)

            image = np.asarray(frame) / 255.0
            cv2.imshow("Input image for the model", frame)
            image = image.reshape([np.prod(image.shape)])
            if len(imgs) < args.number_of_confimation:
                imgs.append(image)
            else:
                if args.tensorflow:
                    results = np.argmax(model(np.asarray(imgs)), axis=1)
                else:
                    results = NN.get_inferences(model, np.asarray(imgs))
                print("Model's output on buffer: ", results)
                if np.unique(
                        results).size == 1 and COMMANDS[results[0]] != "idle":
                    send_command(anafi, results[0])
                    imgs = []
                imgs = imgs[1:]
                imgs.append(image)
            time.sleep(0.3)

    cam.release()
    cv2.destroyAllWindows()