Exemplo n.º 1
0
 def __init__(self, cube):
     CLEAR = 0
     BLUE = 1
     GREEN = 2
     CYAN = 3
     RED = 4
     MAGENTA = 5
     YELLOW = 6
     WHITE = 7
     self.rgb_led = [RGBLED(4), RGBLED(5)]
     self.led = [LED(3), LED(2), LED(1), LED(0)]
     self.button = [Button(index) for index in range(4)]
     self.switch = [Switch(0), Switch(1)]
     self.colors = {
         "D": WHITE,
         "F": GREEN,
         "U": YELLOW,
         "L": RED,
         "R": MAGENTA,
         "B": BLUE
     }
     self.faces = {"D": 5, "F": 0, "U": 4, "L": 3, "R": 1, "B": 2}
     self.speed = 3
     self.cube = cube
     self.address_ports = [
         Arduino_IO(3, i, 'out') for i in reversed(range(6))
     ]
     self.address_clock = Arduino_IO(3, 6, 'out')
     self.color_clock = Arduino_IO(3, 7, 'out')
Exemplo n.º 2
0
def print_to_pmod_solution(solution):
    for i in range(len(solution)):
        pmod_oled.clear()
        pmod_oled.write(solution[i])
        while True:
            if Button(0).read():
                time.sleep(1)
                break
    pmod_oled.clear()
    pmod_oled.write('Congratulations!\nYour cube is\n solved!')
Exemplo n.º 3
0
def test_btn_all():
    """Test for the Button class and its wrapper functions.
    
    Instantiates 4 Button objects on index 0 ~ 3 and performs some 
    actions on it, requesting user confirmation.
    
    """
    buttons = [Button(index) for index in range(4)]
    print("")
    for index in range(4):
        assert buttons[index].read()==0, \
            "Button {} reads wrong values.".format(index)
    for index in range(4):
        input("Hit enter while pressing Button {0} (BTN{0})...".format(index))
        assert buttons[index].read()==1, \
            "Button {} reads wrong values.".format(index)
Exemplo n.º 4
0
face_locations = []
face_encodings = []
face_names = []

print("Face Import Complete")

##########################################################
###### RUN FACIAL RECONGITION SYSTEM #####################
##########################################################

print("Executing")

from pynq.board import Button
import asyncio

stopButton = Button(0)

process_this_frame = True

ret, frame = webcam.read()
x = 0

while webcam.isOpened():
    ret, frame = webcam.read()
    frame_1080p = np.zeros((720, 1920, 3)).astype(np.uint8)

    #Resize Frame BGR
    inputBGR = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
    #Convert to facial_recogntion encoding BGR -> RGB
    rgb_small_frame = inputBGR[:, :, ::-1]
Exemplo n.º 5
0
            if(switches[3].read()):
                frame = cv2.Laplacian(frame, cv2.CV_8U) 
                
            cv2.rectangle(frame,(140,110),(210,180),(255,0,0),2)

            
            immaginee = frame[110:180, 140:210]
            b1, g1, r1 = cv2.split(immaginee)
            tmp = cv2.matchTemplate(r1, kern, cv2.TM_CCORR_NORMED)
            tmp = tmp * 254

            minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(tmp)
            y_quad = maxLoc[1] + 8
            x_quad = maxLoc[0] + 8
            cv2.circle(frame, (x_quad + 140, y_quad + 110), 1, (255, 0, 0),  2)
            reset=Button(3)
             
            #CALIBRATION
            button = Button(1)
            if button.read() and acq:
                
                b,g,r = cv2.split(frame[110:180,140:210])
                r=cv2.GaussianBlur(r,(5,5),0)
                r=cv2.Laplacian(r,cv2.CV_8U)
                r=cv2.medianBlur(r,3)
            
                circles=cv2.HoughCircles(r,cv2.HOUGH_GRADIENT,2,400,200,10,20)
                for j in circles[0,:]:

                    j[0]=j[0]+140
                    j[1]=j[1]+110
Exemplo n.º 6
0
from pynq import Overlay
from Cube import Cube
from CubeSolver import CubeSolver
import cv2
import numpy as np
from pynq.board import Button
from pynq.board import LED
from pynq.board import RGBLED

Overlay("base.bit").download()

button = Button(0)
led_0 = RGBLED(4)
led_1 = RGBLED(5)

IMAGE_PATH = "cube.png"


class CubeReader:
    def readCube(self):
        cube = Cube()

        for i in range(6):
            cube.face[i] = self._readFace(i)
        #cube.face[0] = self._readFace(0)

        return cube

    def _readFace(self, middle_color):
        face = []
        for i in range(3):
Exemplo n.º 7
0
# ### Step 2: Initialize camera from OpenCV

# In[4]:

from pynq.drivers.video import Frame
import cv2
from time import sleep
from pynq.board import LED
from pynq.board import RGBLED
from pynq.board import Button
from pynq.board import Switch

leds = [LED(index) for index in range(4)]
rgbleds = [RGBLED(index) for index in [4, 5]]
btns = [Button(index) for index in range(4)]
switches = [Switch(index) for index in range(2)]

while (1):
    x = 0
    for btn in btns:
        if (btn.read() == 1):
            leds[0].on()
            videoIn = cv2.VideoCapture(0)
            print("Image captured!")
            x = 1
            break
    if (x == 1):
        break

videoIn.set(cv2.CAP_PROP_FRAME_WIDTH, frame_in_w)
        count +=1
    for i in range (indice-1, max(indice-12, 0), -1):
        acc += Stringa[i]
        count +=1
    media=acc/count
    return media
​
# ADC configuration
pmod_adc = PMOD_ADC(1)
​
i=0
players = []
sample_freq = 0
​
# Leds&Button assignements
button = Button(0)
led1 = LED(0)
led2 = LED(1)
​
# We have 2 players -- i<2
while (i<2):
    
    # Status Led: Ready to start
    if(i==0):
        led1.on()
    else:
        led2.on()
    
    # Wait button push
    while(button.read() == 0):
        time.sleep(0.1)
Exemplo n.º 9
0
                logger.debug(
                    "Log: {} posted successfully, moving".format(LOG_FILE))
                # Copy the log file for safe keeping
                shutil.copy(LOG_FILE, "done/" + str(time.time()) + ".log")
        except:
            logger.debug("Timed Out Posting Log")
            return False

    # Truncate the log file
    with open(LOG_FILE, 'w') as file:
        pass
    return True


if __name__ == "__main__":
    rst = Button(0)
    counter = 0
    timer = 0  # Keep track of how long it's been since we've gotten a log
    run = False  # Loop flag
    posted = False

    LED_1.off()
    LED_2.off()
    LED_POSTING.off()
    LED_RUNNING.off()

    logger.debug("Starting now")
    while True:
        time.sleep(1)
        if run:
            LED_1.on()
def monitor():
    """Monitor a blackjack game."""

    ranks = [2, 3, 4, 5, 6, 7, 7, 8, 9, 10, 11, 1, 1]

    classifiers = [
        cv2.CascadeClassifier("classifiers/2.xml"),
        cv2.CascadeClassifier("classifiers/3.xml"),
        cv2.CascadeClassifier("classifiers/4.xml"),
        cv2.CascadeClassifier("classifiers/5.xml"),
        cv2.CascadeClassifier("classifiers/6.xml"),  # Some errors.
        cv2.CascadeClassifier("classifiers/7l.xml"),
        cv2.CascadeClassifier("classifiers/7r.xml"),
        cv2.CascadeClassifier("classifiers/8.xml"),
        cv2.CascadeClassifier("classifiers/9.xml"),  # Some errors.
        cv2.CascadeClassifier("classifiers/10.xml"),
        cv2.CascadeClassifier("classifiers/face.xml"),
        cv2.CascadeClassifier("classifiers/a.xml"),  # Some errors.
        cv2.CascadeClassifier("classifiers/as.xml")
    ]  # Some errors.

    chip_classifier = cv2.CascadeClassifier("classifiers/chip.xml")

    def process(img, upper, lower):
        """Detect cards and chips."""

        image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

        detects = []

        for index in range(len(ranks)):

            try:
                detects.append(classifiers[index].detectMultiScale(
                    gray,
                    scaleFactor=1.05,
                    minNeighbors=4,
                    maxSize=upper,
                    minSize=lower))
            except:
                detects.append([])

        circles = cv2.HoughCircles(gray,
                                   cv2.HOUGH_GRADIENT,
                                   2.5,
                                   25,
                                   minRadius=20,
                                   maxRadius=30)

        widths = []
        heights = []

        out = [[], 0]

        index = 0
        windows = []

        for found in detects[:-2]:

            out[0] += [ranks[index]] * len(detects[index])
            index += 1

            for (x, y, w, h) in found:

                widths.append(w)
                heights.append(h)
                windows.append((x, y, w, h))
                cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5)

        for found in detects[-2:]:

            for (x, y, w, h) in found:

                if any([
                        x + w / 2.0 >= xx and x + w / 2.0 <= xx + ww
                        and y + h / 2.0 >= yy and y + h / 2.0 <= yy + hh
                        for (xx, yy, ww, hh) in windows
                ]):

                    continue

                out[0] += [1]
                widths.append(w)
                heights.append(h)

                cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5)

        if circles is not None:

            circles = np.round(circles[0, :]).astype("int")

            for (x, y, r) in circles:

                if any([
                        x >= xx and x <= xx + ww and y >= yy and y <= yy + hh
                        for (xx, yy, ww, hh) in windows
                ]):

                    continue

                cv2.circle(image, (x, y), r, (255, 0, 255), 4)
                out[1] += 1

        if widths and heights:

            upper = (max(widths) + 10, max(heights) + 6)
            lower = (min(widths) - 10, min(heights) - 6)

        plot.imshow(image)
        plot.show()
        print("CURRENT:", out[0], out[1])

        return out[0], out[1], upper, lower

    def update():
        """Clear all history and update number of decks."""

        state = 2 * switches[1].read() + switches[0].read()
        [leds[led].write(led <= state) for led in range(len(leds))]

        return CounterAttack(DECK_MAP[state], THRESH)

    error_messages = ("[OK]", "[HANDLING FAILED]", "[ATTEMPTING TO HANDLE]",
                      "", "[HANDLED]")
    exit, reset, new_player, shuffle = (Button(button) for button in range(4))
    leds = [LED(led) if led < 4 else RGBLED(led) for led in range(6)]
    switches = [Switch(0), Switch(1)]
    counter = update()
    upper, lower = (150, 90), (50, 30)

    error = 0

    while not exit.read():

        try:

            if reset.read(): counter = update()
            elif new_player.read(): counter.new_player()
            elif shuffle.read(): counter.shuffle()

            success = False
            cam = cv2.VideoCapture(0)
            while not success:
                success, img = cam.read()
            cam.release()

            detected, chips, upper, lower = process(img, upper, lower)

            colors = counter.count(detected, chips)

            leds[4].write(colors[0])
            leds[5].write(colors[1])

            if error:

                error = 0
                print(error_messages[error])

        except ShuffleError:

            if error: error = 1
            else: error = 4
            print("SHUFFLE REQUIRED.", error_messages[error])

        except Exception as exception:

            if error: error = 1
            else: error = 2
            print(exception, error_messages[error])

        finally:

            if error:

                [led.off() for led in leds[:5]]

                wait = 0

                # Toggle RGBs blue and relevant button LEDs
                while not any(
                        button.read()
                        for button in (exit, reset, None, shuffle)[:error]
                        if button):  # TODO: Length.

                    if not wait % error:
                        [led.write(not led.read()) for led in leds[4:6]]
                        [
                            leds[led].toggle() for led in range(error)
                            if led != 2
                        ]
                        'haarcascade_frontalface_alt.xml')
facealt2_cascade = cv2.CascadeClassifier(
                        'haarcascade_frontalface_alt2.xml')

frame_in_w = 640
frame_in_h = 480

videoIn = cv2.VideoCapture(0)
videoIn.set(cv2.CAP_PROP_FRAME_WIDTH, frame_in_w);
videoIn.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_in_h);

print("capture device is open: " + str(videoIn.isOpened()))
i = 0

while True:
    if Button(0).read():
        break
    f_x = 0
    f_y = 0
    fa_x = 0
    fa_y = 0
    fa2_x = 0
    fa2_y = 0
    p_x = 0
    p_y = 0
    f_len = 0
    fa_len = 0
    fa2_len = 0
    p_len = 0
    avg_counter = 0
    avg_len = 0
Exemplo n.º 12
0
                frame[0:frame_h, 0:frame_w, 2] = 0
            if (switches[3].read()):
                frame = cv2.Laplacian(frame, cv2.CV_8U)

            cv2.rectangle(frame, (140, 110), (210, 180), (255, 0, 0), 2)

            immaginee = frame[110:180, 140:210]
            b1, g1, r1 = cv2.split(immaginee)
            tmp = cv2.matchTemplate(r1, kern, cv2.TM_CCORR_NORMED)
            tmp = tmp * 254

            minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(tmp)
            y_quad = maxLoc[1] + 8
            x_quad = maxLoc[0] + 8
            cv2.circle(frame, (x_quad + 140, y_quad + 110), 1, (255, 0, 0), 2)
            reset = Button(3)

            #CALIBRATION
            button = Button(1)
            if button.read() and acq:

                b, g, r = cv2.split(frame[110:180, 140:210])
                r = cv2.GaussianBlur(r, (5, 5), 0)
                r = cv2.Laplacian(r, cv2.CV_8U)
                r = cv2.medianBlur(r, 3)

                circles = cv2.HoughCircles(r, cv2.HOUGH_GRADIENT, 2, 400, 200,
                                           10, 20)
                for j in circles[0, :]:

                    j[0] = j[0] + 140
Exemplo n.º 13
0
def get_cube_from_pictures():
    i = 0
    j = False
    cube = {
        "top": [
            'X', 'X', 'X',
            'X', 'X', 'X',
            'X', 'X', 'X',
        ],
        "left": [
            'X', 'X', 'X',
            'X', 'X', 'X',
            'X', 'X', 'X',
        ],
        "front": [
            'X', 'X', 'X',
            'X', 'X', 'X',
            'X', 'X', 'X',
        ],
        "right": [
            'X', 'X', 'X',
            'X', 'X', 'X',
            'X', 'X', 'X',
        ],
        "back": [
            'X', 'X', 'X',
            'X', 'X', 'X',
            'X', 'X', 'X',
        ],
        "bottom": [
            'X', 'X', 'X',
            'X', 'X', 'X',
            'X', 'X', 'X',
        ]
    }

    def print_to_pmod_get_sides(i):
        pmod_oled.clear()
        remaining = 'Sides Remaining:' + str(6 - i)
        if i == 0:
            pmod_oled.write('Show Front,\n' + remaining)
        elif i == 1:
            pmod_oled.write('Show Top,\n' + remaining)
        elif i == 2:
            pmod_oled.write('Show Back,\n' + remaining)
        elif i == 3:
            pmod_oled.write('Show Bottom,\n' + remaining)
        elif i == 4:
            pmod_oled.write('Show Left,\n' + remaining)
        elif i == 5:
            pmod_oled.write('Show Right,\n' + remaining)

    print_to_pmod_get_sides(i)

    def draw_to_cube(i, listFromPic):
        print(listFromPic)
        order = ['front', 'top', 'back', 'bottom', 'left', 'right']
        if i == 2:
            for j in range(9):
                cube['back'][j] = listFromPic[8 - j]
        else:
            cube[order[i]] = listFromPic
        pmod_oled.clear()
        pmod_oled.write(
            listFromPic[0] + listFromPic[1] + listFromPic[2] + ' 0 if good\n' +
            listFromPic[3] + listFromPic[4] + listFromPic[5] + ' 1 if bad\n' +
            listFromPic[6] + listFromPic[7] + listFromPic[8])


    def process_input(i):
        pmod_oled.clear()
        pmod_oled.write('Taking Picture, please wait')
        draw_to_cube(i, get_side_from_picture())


    while i < 6:
        if Button(0).read():
            if j == True:
                print('called')
                i += 1
                print_to_pmod_get_sides(i)
                j = False
                time.sleep(1)
            else:
                print('other')
                process_input(i)
                j = True
        elif Button(1).read():
            if j == True:
                print_to_pmod_get_sides(i)
                j = False
                time.sleep(1)

    print(cube)
    pmod_oled.clear()
    pmod_oled.write('Calculating\nSolution...')
    return cube