Exemplo n.º 1
0
	def detect(self):
		faces = []
		eyes = []
		rgb_green = (0, 255, 0)
		rgb_blue = (0, 0, 255)

		detected_faces = self.__detect_faces()

		for (x, y, w, h) in detected_faces:
			face = Face(self.image, x, y, w, h, rgb_green)
			face.draw(2)
			faces.append(face)
			detected_eyes = self.__detect_eyes(face.data())
			if len(detected_eyes) > 0:
				for(eye_x, eye_y, eye_w, eye_h) in detected_eyes:
					eye = Eye(self.image, face.x + eye_x, face.y + eye_y, eye_w, eye_h, rgb_blue)
					eye.draw(2)
			        eyes.append(eye)

			detected_smile = self.__detect_smile(face.data())
			if len(detected_smile) > 0:
				smileness = detected_smile[0][1]
				smile_text_position = ((x - 15), y + (h + 25))
				if smileness >= 15:
					cv2.putText(self.image, "Smiling: Yes", smile_text_position, cv2.FONT_HERSHEY_DUPLEX, 1, (255,255,255))
				else:
					cv2.putText(self.image, "Smiling: No", smile_text_position, cv2.FONT_HERSHEY_DUPLEX, 1, (255,255,255))

			return { "faces" : faces, "eyes" : eyes}
Exemplo n.º 2
0
    def detect(self):
        faces = []
        eyes = []
        rgb_green = (0, 255, 0)
        rgb_blue = (0, 0, 255)

        detected_faces = self.__detect_faces()

        for (x, y, w, h) in detected_faces:
            face = Face(self.image, x, y, w, h, rgb_green)
            face.draw(2)
            faces.append(face)
            detected_eyes = self.__detect_eyes(face.data())
            if len(detected_eyes) > 0:
                for (eye_x, eye_y, eye_w, eye_h) in detected_eyes:
                    eye = Eye(self.image, face.x + eye_x, face.y + eye_y,
                              eye_w, eye_h, rgb_blue)
                    eye.draw(2)
                    eyes.append(eye)
            detected_smile = self.__detect_smile(face.data())
            if len(detected_smile) > 0:
                smileness = detected_smile[0][1]
                smile_text_position = ((x - 15), y + (h + 25))
                if smileness >= 15:
                    cv2.putText(self.image, "Smiling: Yes",
                                smile_text_position, cv2.FONT_HERSHEY_DUPLEX,
                                1, (255, 255, 255))
                else:
                    cv2.putText(self.image, "Smiling: No", smile_text_position,
                                cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255))
            return {"faces": faces, "eyes": eyes}
Exemplo n.º 3
0
    def __init__(self, fill_color):
        Eye.__init__(self, fill_color)

        self._pixbufs = []
        self._pixbufs.append(svg_str_to_pixbuf(lefteye_svg()))
        self._pixbufs.append(svg_str_to_pixbuf(centereye_svg()))
        self._pixbufs.append(svg_str_to_pixbuf(righteye_svg()))
        self._which_eye = 1
Exemplo n.º 4
0
    def __init__(self, fill_color):
        Eye.__init__(self, fill_color)

        self._pixbufs = []
        self._pixbufs.append(svg_str_to_pixbuf(lefteye_svg()))
        self._pixbufs.append(svg_str_to_pixbuf(centereye_svg()))
        self._pixbufs.append(svg_str_to_pixbuf(righteye_svg()))
        self._which_eye = 2
Exemplo n.º 5
0
 def __init__(self, position, window):
     self.window = window
     self.position = position
     self.size = 10
     self.view_angle = 0
     self.eye = Eye(self.position)
     self.eye.color = BLUE
     self.color = WHITE
     self.speed = 4
    def __init__(self, x, y, size):
        # Face position and size.
        self.x = x
        self.y = y
        self.size = size

        # Create the eyes.
        self.lefteye = Eye(x - 15, y - 15, 10)
        self.righteye = Eye(x + 15, y - 15, 10)
Exemplo n.º 7
0
    def __init__(self, face, frame):
        self.face = face
        self.frame = frame
        self.landmarks = predictor(frame, face)
        self.face_position = self.posit_predict()

        eye1 = np.array([[self.landmarks.part(mark).x, self.landmarks.part(mark).y] for mark in range(36, 42)])
        eye2 = np.array([[self.landmarks.part(mark).x, self.landmarks.part(mark).y] for mark in range(42, 48)])

        self.left_eye = Eye(eye1, self.frame, 'left')
        self.right_eye = Eye(eye2, self.frame, 'right')
Exemplo n.º 8
0
    def _analyze(self):

        frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
        faces = self._face_detector(frame)

        try:
            landmarks = self._predictor(frame, faces[0])
            self.eye_left = Eye(frame, landmarks, 0, self.calibration)
            self.eye_right = Eye(frame, landmarks, 1, self.calibration)

        except IndexError:
            self.eye_left = None
            self.eye_right = None
Exemplo n.º 9
0
    def __init__(self, position, window):
        self.window = window
        self.position = position
        self.size = 20
        self.view_angle = 0
        self.left_eye_pos = Position(self.position.x + 20, self.position.y)
        self.right_eye_pos = Position(self.position.x - 20, self.position.y)

        self.left_eye = Eye(self.left_eye_pos)
        self.right_eye = Eye(self.right_eye_pos)
        self.left_eye.color = BLUE
        self.color = WHITE
        self.speed = 4
        self.scene = []
Exemplo n.º 10
0
class Face:
    def __init__(self, x, y, size):
        # Face position and size.
        self.x = x
        self.y = y
        self.size = size

        # Create the eyes.
        self.lefteye = Eye(x - 15, y - 15, 10)
        self.righteye = Eye(x + 15, y - 15, 10)

    # Make this Face look at location lx, ly.
    def look_at(self, lx, ly):
        self.lefteye.look_at(lx, ly)
        self.righteye.look_at(lx, ly)

    def draw(self):
        enable_stroke()
        set_fill_color(1, 1, 1)
        draw_circle(self.x, self.y, self.size)  # draw face
        self.lefteye.draw()  # draw eyes
        self.righteye.draw()  # draw eyes
        draw_line(self.x, self.y, self.x, self.y + 15)  # draw nose
        draw_line(self.x - 15, self.y + 20, self.x + 15,
                  self.y + 20)  # draw mouth
Exemplo n.º 11
0
    def computeBits(self):
        bits = []
        self.eyes = []
        self.faces = []

        for image in self.images:
            face = Face(image)
            eye = Eye(face.frame, face.canvas, padding=10)
            eye.draw(face)
            eye.iris.normalizeIris()
            self.eyes.append(eye)
            self.faces.append(face)
            bits.append(eye.iris.bits_pattern)
        self.bits = np.array(bits)
Exemplo n.º 12
0
  def __init__(self,resolution,color=(0, 0, 0)):

    self.screen=pygame.display.set_mode(resolution)

    self.background = pygame.Surface(self.screen.get_size())
    self.background = self.background.convert()
    self.background.fill(color)

    center_x=self.background.get_width()/2

    self.left_eye=Eye(center_x-250,250)
    self.right_eye=Eye(center_x+250,250)
    self.mouth=Mouth(center_x,500)
    self.photo=Photo()

    self.draw()
Exemplo n.º 13
0
    def __init__(self, xy: XYPoint, ship_angle: float, width: int, height: int,
                 n_sensors: int, sensor_resolution: int, sensor_length: int,
                 sensor_width: float):
        self.xy = xy
        self.angle = ship_angle

        self.width = width
        self.height = height
        self.n_sensors = n_sensors
        self.sensor_resolution = sensor_resolution
        self.sensor_width = sensor_width
        self.step = 5
        self.turn_angle = pi / 12

        self.max_eye_length = distance(XYPoint(0, 0), XYPoint(width, height))
        self.eye_length = min(sensor_length, self.max_eye_length)

        eye_max_angle = self.sensor_width
        if n_sensors > 1:
            eye_step = (eye_max_angle) / (n_sensors - 1)
        else:
            eye_step = 0

        self.eyes = []
        # add the leftmost eye first, working our way from +sensor_width/2 to -sensor_width/2
        for i in range(0, n_sensors):
            if n_sensors == 1:
                angle = 0
            else:
                angle = eye_max_angle / 2 - eye_step * i
            self.eyes.append(
                Eye(xy, ship_angle, angle, eye_step, self.eye_length,
                    self.width, self.height))
Exemplo n.º 14
0
    def getMeanEyes(self, bufferLeftEye, bufferRightEye):
        """Smooth the eye detection by using a rolling mean window over the last detected best eyes.

        Args:
            bufferLeftEye (Buffer): Buffer for the last left best eyes chosen
            bufferRightEye (Buffer): Buffer for the last right best eyes chosen

        Returns:
            [Eye, Eye]: Mean best eyes
        """
        # Mean position
        eyes = [self.best_eye_left, self.best_eye_right]

        for eye, buffer, type_, index in ((self.best_eye_left, bufferLeftEye,
                                           EyeType.LEFT, 0),
                                          (self.best_eye_right, bufferRightEye,
                                           EyeType.RIGHT, 1)):
            buffer.addLast(eye)

            lasts = [item for item in buffer.lasts if item]
            if lasts:
                xm = int(np.mean([eye.x for eye in lasts]))
                ym = int(np.mean([eye.y for eye in lasts]))
                wm = int(np.mean([eye.w for eye in lasts]))
                hm = int(np.mean([eye.h for eye in lasts]))
                if xm + wm < self.w and ym + hm < self.h:
                    eyes[index] = Eye(self.frame, self.canvas, type_, xm, ym,
                                      wm, hm)
        return eyes
Exemplo n.º 15
0
 def detectEyes(self):
     """Uses classifiers to detect eyes in the face
     """
     eyes = eye_cascade.detectMultiScale(self.gray, 1.3, 5)
     self.eyes = [
         Eye(self.frame, self.canvas, x, y, w, h) for (x, y, w, h) in eyes
     ]
Exemplo n.º 16
0
 def __init__(self):
     self.capture = cv.CaptureFromCAM(0)
     cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, self.IMAGE_WIDTH)
     cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, self.IMAGE_HEIGHT)
     # cv.NamedWindow("Target", 1)
     # cv.NamedWindow("Intermediate", 1)
     self.theGiantEye = Eye()
     self.interest = 0.0 # how interested we are, 0 - 100
Exemplo n.º 17
0
 def __init__(self):
     GPIO.setmode(GPIO.BOARD)
     self.platform = TurretPlatform()
     self.arm = LaserArm(INPUT_WINDOW_SIZE)
     self.root = Tk()
     self.eye = Eye(CAM_RES[0],CAM_RES[1],10)
     self.isTracking = False
     self.trackingHaar = cv2.CascadeClassifier('../CAM/haar/haarcascade_frontalface_default.xml')
Exemplo n.º 18
0
class Eyes:
    def __init__(self):
        self.left_eye = Eye()
        self.right_eye = Eye()

    def display(self, x, y, direction):
        self.left_eye.look(direction)
        self.right_eye.look(direction)
        self.left_eye.display(x - 20, y)
        self.right_eye.display(x + 20, y)
Exemplo n.º 19
0
 def group_eye(self, x, y, w, h, now):
     found = False
     for group in self.eyeGroups:
         if group.update_group1(x, y, w, h, now):
             found = True
             break
     if not found:
         group = Eye(x + w / 2, y + h / 2, w, h, now)
         self.eyeGroups.append(group)
     return group
Exemplo n.º 20
0
class Eyes:
    def __init__(self):
        """Eyes constructor"""
        self.left_eye = Eye()
        self.right_eye = Eye()

    def display(self, x, y, direction):
        """Display eyes direction"""
        self.left_eye.look(direction)
        self.right_eye.look(direction)
        self.left_eye.display(x-20, y)
        self.right_eye.display(x+20, y)
Exemplo n.º 21
0
    def __init__(self):
        """ 
        コンストラクタが呼ばれた後に呼ばれるメソッド
        """
        # Raspberry Pi pin configuration:
        RST = 24

        # 128x64 display with hardware I2C:
        self.__disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

        # Initialize library.
        self.__disp.begin()

        # Get display width and height.
        self.__width = self.__disp.width
        self.__height = self.__disp.height

        # Clear display.
        self.__disp.clear()
        self.__disp.display()

        # Create image buffer.
        # Make sure to create image with mode '1' for 1-bit color.
        self.__image = Image.new('1', (self.__width, self.__height))

        # Create drawing object.
        self.__draw = ImageDraw.Draw(self.__image)
        # Clear image buffer by drawing a black filled box.
        self.__draw.rectangle((0, 0, self.__width, self.__height),
                              outline=0,
                              fill=0)
        # Draw the image buffer.
        self.__disp.image(self.__image)
        self.__disp.display()

        # 左右の目のインスタンスを作成
        # ここでの左右はディスプレイとしての左右であり、顔としての左右とは逆である
        self.__eye_l = Eye()
        self.__eye_r = Eye()

        self.set_nomal()
    def _analyze(self, cntFace):
        """Detects the face and initialize Eye objects"""
        frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY)
        # cv2.imwrite("image.png",frame)
        # if cntFace == 0:
        #     faces = self._face_detector(frame, 1)
        #     self.gface = faces[0]

        if cntFace == 0:
            faces = self._face_detector(frame, 1)
            self.gface = faces[0]

        try:
            landmarks = self._predictor(frame, self.gface)
            # landmarks = face_utils.shape_to_np(landmarks)
            self.eye_left = Eye(frame, landmarks, 0, self.calibration)
            self.eye_right = Eye(frame, landmarks, 1, self.calibration)

        except IndexError:
            self.eye_left = None
            self.eye_right = None
Exemplo n.º 23
0
class Cyclops():
    def __init__(self, position, window):
        self.window = window
        self.position = position
        self.size = 10
        self.view_angle = 0
        self.eye = Eye(self.position)
        self.eye.color = BLUE
        self.color = WHITE
        self.speed = 4

    def move(self, position):
        for element in self.scene:
            #on_line = (-3 < (distance(element.a, position) + distance(position, element.b) - distance(element.a, element.b)) < 3)
            if False:
                print("collision")
                return
            else:
                self.position.translate_to(position)

    def forward(self):
        direction = Position(math.sin(self.view_angle),
                             math.cos(self.view_angle))
        direction = direction.multipy(self.speed)
        self.move(self.position.plus(direction))

    def backward(self):
        direction = Position(math.sin(self.view_angle),
                             math.cos(self.view_angle))
        direction = direction.multipy(self.speed)
        self.move(self.position.minus(direction))

    def rotate(self, direction):
        self.eye.view_angle += direction
        self.view_angle += direction

    def show(self):

        #pygame.draw.circle(window, self.color, self.position.toTuple(), self.size, 1)
        self.eye.show(self.window)

        lineEnd = (self.position.x + math.sin(self.view_angle) *
                   (self.size - 2), self.position.y +
                   math.cos(self.view_angle) * (self.size - 2))
        pygame.draw.line(self.window, (255, 255, 255), self.position.toTuple(),
                         lineEnd, 2)

    def see(self):
        self.eye.update()
        self.eye.see(self.scene)
        self.render()

    def render(self):

        render = Image(self.eye.rays)
        render.draw2D(Position(0, MAP_HEIGHT), self.window)
Exemplo n.º 24
0
    def __init__(self):
        # Global variables for executions
        self._title_exam = ''
        self._path_dataset_out = ''

        # Dependences
        self._process = ProcessImage()
        self._pupil = Pupil()
        self._eye = Eye()

        # Limit cash dependences
        self._max_execution_with_cash = 20

        # Directoris
        self._projects_path = '/media/marcos/Dados/Projects'

        self._dataset_path = '{}/Datasets/exams'.format(self._projects_path)
        self._dataset_out = '{}/Results/PupilDeep/Frames'.format(
            self._projects_path)
        self._dataset_label = '{}/Results/PupilDeep/Labels'.format(
            self._projects_path)

        # Stops and executions
        self._frame_stop = 150
        self._frame_start = 100

        self._movie_stop = 0
        self._list_not_available = []
        self._list_available = [
            '25080325_08_2019_08_48_58', '25080425_08_2019_08_53_48'
        ]
        # self._list_available = ['25080325_08_2019_08_48_58', '25080425_08_2019_08_53_48', '25080425_08_2019_08_55_59', '25080425_08_2019_09_05_40', '25080425_08_2019_09_08_25']
        # self._list_available = ['new_benchmark']

        # Params color
        self._white_color = (255, 255, 0)
        self._gray_color = (170, 170, 0)

        # Params text and circle print image
        self._position_text = (30, 30)
        self._font_text = cv2.FONT_HERSHEY_DUPLEX
        self._size_point_pupil = 5

        # Params dataset labels out
        self._title_label = 'frame,center_x,center_y,radius,flash,eye_size,img_mean,img_std,img_median'
Exemplo n.º 25
0
class ChatConnection(tornadio2.conn.SocketConnection):
    # Class level variable
    participants = set()
    self.auto=Auto([29,31,33,35,38,40])
    self.network = UnmannedNet(768,60,2)
    self.eye=Eye("192.168.10.1")

    def on_open(self, info):                    #当网页发起连接后发送
        self.send("Welcome from the server.")
        self.participants.add(self)             #保存客户端客户的信息

    def on_message(self, message):              #有消息进来后
        # Pong message back
        #for p in self.participants:             #进行广播
            #p.send(message)
        value=message.split(",")
        alpha=int(float(value[0]))
        beta=int(float(value[1]))
        gamma=int(float(value[2]))
        self.auto.control(beta,gamma)
        self.network.adddata(self.eye.getResizeImage(),(beta,gamma))
    def on_close(self):                         #连接关闭后删除信息
        self.participants.remove(self)
        self.network.save_data()
Exemplo n.º 26
0
 def __init__(self):
     self.left_eye = Eye()
     self.right_eye = Eye()
Exemplo n.º 27
0
    def __init__(self, fill_color):
        Eye.__init__(self, fill_color)

        self._pixbuf = svg_str_to_pixbuf(eye_svg())
Exemplo n.º 28
0
from eye import Eye

pixel_pin = board.D18

nbPixelsPerRing = 16
nbRings = 2
nbPixels = nbRings * nbPixelsPerRing

# The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed!
# For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW.
ORDER = neopixel.GRB

pixels = neopixel.NeoPixel(pixel_pin,
                           nbPixels,
                           brightness=0.2,
                           auto_write=False,
                           pixel_order=ORDER)

rightEye = Eye(pixels, 0, nbPixelsPerRing, 0)  #4
leftEye = Eye(pixels, 16, nbPixelsPerRing, 14)  #2


def neopixelAllOff():
    pixels.fill((0, 0, 0))
    pixels.show()


def neopixelAllOnWhite():
    pixels.fill((255, 255, 255))
    pixels.show()
Exemplo n.º 29
0
class World():
    '''
    This class contains the eye, that is the point from where the world is seen,
    and the list of walls included in the world.
    '''
    
    def __init__(self):
        # Initialize Wall list and Eye
        self.walls = []
        self.eye = Eye(0, 0, Direction.North)
        

    def loadWalls(self, fname):
        # Manage loading of walls from file.
        f = open(fname, 'r')
        with f:
            self.walls = [] # Empty list from any existing walls.
            data = f.readline() # Read firs line, that should contain data for the eye. If this line does not exist, the file is not valid.
            eye = data.split(':')
            self.eye.setCoords([int(eye[0]), int(eye[1])], int(eye[2]))
            data = f.readline() # Read next line, walls should start here, if any exist.
            while data:
                # Add all wall to the wall list one by one until EOF is reached.
                wall = data.split(' ')
                coords1 = wall[0].split(':')
                coords2 = wall[1].split(':')
                self.addWall(Wall([int(coords1[0]), int(coords1[1])], [int(coords2[0]), int(coords2[1])]))
                data = f.readline()
        f.close()
        
        
    def sortWalls(self):
        # Sort walls by distance to eye for drawing.
        def keyfunc(wall):
            c1 = wall.getFirstCoords()
            c2 = wall.getSecondCoords()
            z1 = (c1[0] - self.eye.getX())**2 + (c1[1] - self.eye.getY())**2
            z2 = (c2[0] - self.eye.getX())**2 + (c2[1] - self.eye.getY())**2
            if z1 > z2:
                return z2
            else:
                return z1
        
        self.walls.sort(key=keyfunc, reverse=True)


    def drawWalls(self, painter):
        
        self.sortWalls()
        for wall in self.walls:
            wall.drawWall(painter, self.eye)
            
    def moveEye(self, key):
        # Move eye if move is allowed. Only necessary to check the eight closest walls for collision, 
        # which is easy because the list is already sorted by distance.
        newcoors = self.eye.move(key)
        i = 1
        for wall in reversed(self.walls):
            if wall.getFirstCoords() == [newcoors[0], newcoors[1]] or wall.getSecondCoords() == [newcoors[0], newcoors[1]]:
                return
            i += 1
            if i > 8:
                break
        self.eye.setCoords([newcoors[0], newcoors[1]], newcoors[2])
    
    
    def editWall(self, key):
        point = self.eye.getPoint()
        direction = point[2]
        coords2 = [point[0], point[1]]
        if direction == Direction.North:
            coords2[0] += 1
        elif direction == Direction.East:
            coords2[1] -= 1
        elif direction == Direction.South:
            coords2[0] -= 1
        elif direction == Direction.West:
            coords2[1] += 1
        
        for wall in self.walls:
            if wall.getFirstCoords() == [point[0], point[1]] or wall.getSecondCoords() == [point[0], point[1]]:
                if key == QtCore.Qt.Key_Backspace:
                    self.rmWall(wall)
                    return
                else:
                    if wall.getFirstCoords() == coords2 or wall.getSecondCoords() == coords2:
                        return

        self.addWall(Wall([point[0], point[1]], coords2))
    
    
    def addWall(self, wall):
        self.walls.append(wall)
    
    def rmWall(self, wall):
        self.walls.remove(wall)
Exemplo n.º 30
0
 def __init__(self, fill_color):
     Eye.__init__(self, fill_color)
Exemplo n.º 31
0
 def __init__(self):
     # Initialize Wall list and Eye
     self.walls = []
     self.eye = Eye(0, 0, Direction.North)
Exemplo n.º 32
0
    def run(self):
        """Main loop
        """
        self.startCapture()
        data_collector = DataCollector(self.dataset)

        modeFullFace = 0
        modeOneEye = 1
        modePictures = 2
        modeTwoEyes = 3
        modeImgDB = 4
        modeDemo = 5

        mode = modeDemo
        keepLoop = True
        current_t = time.clock()
        previous_t = current_t
        while keepLoop:
            pressed_key = cv2.waitKey(1)
            current_t = time.clock()
            #print('\nclock : ', current_t - previous_t)
            previous_t = current_t

            img = self.getCameraImage()

            if(mode == modeOneEye):
                ex = 300
                ey = 50
                eh = 200
                ew = 200
                face = Face(img.frame, img.canvas, 0, 0, 640, 480)
                eye = Eye(face.frame, face.canvas, ex, ey, ew, eh)
                eye.draw(face)
                eye.iris.normalizeIris()
            elif(mode == modeTwoEyes):
                face = Face(img.frame, img.canvas, 0, 0, 640, 480)
                left_eye = Eye(face.frame, face.canvas, 50, 50, 200, 200, EyeType.LEFT)
                left_eye.draw(face)
                left_eye.iris.normalizeIris()
                right_eye = Eye(face.frame, face.canvas, 400, 50, 200, 200, EyeType.RIGHT)
                right_eye.draw(face)
                right_eye.iris.normalizeIris()
            elif(mode == modeFullFace):
                face, left_eye, right_eye = img.detectEyes(self.bufferFace, self.bufferLeftEye, self.bufferRightEye)
                if face:
                    face.draw(img)
                if left_eye:
                    left_eye.draw(face)
                    left_eye.iris.normalizeIris()
                if right_eye:
                    right_eye.draw(face)
                    right_eye.iris.normalizeIris()
            elif(mode == modeImgDB):
                img_db = ImageDB("./IR_Database/MMU Iris Database/")
                print(img_db.estimateUser(img_db.bits[0]))
                exit()
            elif(mode == modeDemo):
                path = "./TB_Database/"
                face = Face(img.frame, img.canvas, 0, 0, 640, 480)
                left_eye = Eye(face.frame, face.canvas, 50, 50, 200, 200, EyeType.LEFT)
                left_eye.draw(face)
                left_eye.iris.normalizeIris()
                right_eye = Eye(face.frame, face.canvas, 400, 50, 200, 200, EyeType.RIGHT)
                right_eye.draw(face)
                right_eye.iris.normalizeIris()
                if(ord('0') <= pressed_key & 0xFF <= ord('9')):
                    print('0-9')
                    id_person = chr(pressed_key & 0xFF)
                    while((pressed_key & 0xFF) not in [ord('a'), ord('p')]):
                        pressed_key = cv2.waitKey(50)
                    print(pressed_key & 0xFF)
                    if(pressed_key & 0xFF == ord('a')):
                        cv2.imwrite(path + id_person + '/left/' + str(int(time.time() * 1000)) + '.bmp', left_eye.frame)
                        cv2.imwrite(path + id_person + '/right/' + str(int(time.time() * 1000)) + '.bmp', right_eye.frame)
            else:
                path = "./IR_Database/MMU Iris Database/"
                for dir in os.listdir(path):
                    subpath = path + dir + '/'
                    if(os.path.isdir(subpath)):
                        print(dir)
                        for subdir in os.listdir(subpath):
                            subsubpath = subpath + subdir + '/'
                            if(os.path.isdir(subsubpath)):
                                print('\t', subdir)
                                for fname in os.listdir(subsubpath):
                                    fpath = subsubpath + fname
                                    if(os.path.isfile(fpath) and os.path.splitext(fname)[1] == '.bmp'):
                                        print('\t\t', fname)
                                        img = Image(cv2.imread(fpath))
                                        face = Face(img.frame, img.canvas)
                                        eye = Eye(face.frame, face.canvas, padding=10)
                                        eye.draw(face)
                                        eye.iris.normalizeIris()
                                        img.show()
                                        pressed_key = cv2.waitKey(1000)
                exit()

            # Controls
            if pressed_key & 0xFF == ord('q'):
                keepLoop = False
            #if pressed_key & 0xFF == ord('s'):
            #    self.dataset.save()
            #if pressed_key & 0xFF == ord('l'):
            #    self.dataset.load()
            #if pressed_key & 0xFF == ord('m'):
            #    self.showMoments = not self.showMoments
            #if pressed_key & 0xFF == ord('e'):
            #    self.showEvaluation = not self.showEvaluation

            #data_collector.step(img.canvas, pressed_key, left_eye, right_eye)

            #txt = 'Dataset: {} (s)ave - (l)oad'.format(len(self.dataset))
            #cv2.putText(img.canvas, txt, (21, img.canvas.shape[0] - 29), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (32, 32, 32), 2)
            #cv2.putText(img.canvas, txt, (20, img.canvas.shape[0] - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 126, 255), 2)

            #if left_eye and right_eye:
            #    direction = self.dataset.estimateDirection(left_eye.computeMomentVectors(), right_eye.computeMomentVectors())
            #    txt = 'Estimated direction: {}'.format(direction.name)
            #    cv2.putText(img.canvas, txt, (21, img.canvas.shape[0] - 49), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (32, 32, 32), 2)
            #    cv2.putText(img.canvas, txt, (20, img.canvas.shape[0] - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 126, 255), 2)

            img.show()

            #if self.showEvaluation:
            #    fig = self.dataset.showValidationScoreEvolution()
            #    plt.show()
            #    self.showEvaluation = False

            #if self.showMoments:
            #    fig = self.dataset.drawVectorizedMoments()
            #    plt.show()
            #    # cv2.imshow('moments', self.fig2cv(fig))
            #    # plt.close(fig)
            #    self.showMoments = False

        self.stopCapture()
Exemplo n.º 33
0
 def __init__(self):
     """Eyes constructor"""
     self.left_eye = Eye()
     self.right_eye = Eye()
Exemplo n.º 34
0
def test_look():
    """Test look method"""
    e = Eye()
    e.look((1, 1))
    assert e.direction == (1, 1)
Exemplo n.º 35
0
class Face:
  def __init__(self,resolution,color=(0, 0, 0)):

    self.screen=pygame.display.set_mode(resolution)

    self.background = pygame.Surface(self.screen.get_size())
    self.background = self.background.convert()
    self.background.fill(color)

    center_x=self.background.get_width()/2

    self.left_eye=Eye(center_x-250,250)
    self.right_eye=Eye(center_x+250,250)
    self.mouth=Mouth(center_x,500)
    self.photo=Photo()

    self.draw()

  def draw(self):
    self.screen.blit(self.background,(0,0))
    self.left_eye.draw(self.screen)
    self.right_eye.draw(self.screen)
    self.mouth.draw(self.screen)
    pygame.display.flip()

  
  def surprise(self):
    self.left_eye.draw(self.screen,"up")
    self.right_eye.draw(self.screen,"up")
  def sad(self):
    self.left_eye.draw(self.screen,"brownleft")
    self.right_eye.draw(self.screen,"brownright")
    self.mouth.draw(self.screen,"sad")
  def angry(self):
    self.left_eye.draw(self.screen,"brownright")
    self.right_eye.draw(self.screen,"brownleft")
  def look_left(self):
    self.left_eye.draw(self.screen,"left")
    self.right_eye.draw(self.screen,"left")
  def look_right(self):
    self.left_eye.draw(self.screen,"right")
    self.right_eye.draw(self.screen,"right")
  def blink_left(self):
    self.left_eye.blink(self.screen)
  def blink_right(self):
    self.right_eye.blink(self.screen)
  def close_both(self):
    self.left_eye.draw(self.screen,"close")
    self.right_eye.draw(self.screen,"close")
  def open_both(self):
    self.left_eye.status="open"
    self.right_eye.status="open"
    self.left_eye.draw(self.screen)
    self.right_eye.draw(self.screen)
  def blink_both(self):
    self.close_both()
    time.sleep(0.10)
    self.open_both()
Exemplo n.º 36
0
def test_constructor():
    """Test Eye constructor"""
    e = Eye()
    assert e.direction == (0, 0)
Exemplo n.º 37
0
    def __init__(self, fill_color):
        Eye.__init__(self, fill_color)

        self._pixbuf = svg_str_to_pixbuf(eyelashes_svg())
Exemplo n.º 38
0
    def analyze_color_unconditional_status(self, color):
        """1) List potential eyes (eyes: empty+opponent areas flood filled):
              all empty points must be adjacent to those neighbour blocks with given color it gives eye.
           2) List all blocks with given color
              that have at least 2 of above mentioned areas adjacent
              and has empty point from it as liberty.
           3) Go through all potential eyes. If there exists neighbour
              block with less than 2 eyes: remove this this eye from list.
           4) If any changes in step 3, go back to step 2.
           5) Remaining blocks of given color are unconditionally alive and
              and all opponent blocks inside eyes are unconditionally dead.
           6) Finally update status of those blocks we know.
           7) Analyse dead group status.

           See test.py for testcases
        """
        #find potential eyes
        eye_list = []
        not_ok_eye_list = [] #these might still contain dead groups if totally inside live group
        eye_colors = EMPTY + other_side[color]
        for block in self.iterate_blocks(EMPTY+WHITE+BLACK):
            block.eye = None
        for block in self.iterate_blocks(eye_colors):
            if block.eye: continue
            current_eye = Eye()
            eye_list.append(current_eye)
            blocks_to_process = [block]
            while blocks_to_process:
                block2 = blocks_to_process.pop()
                if block2.eye: continue
                block2.eye = current_eye
                current_eye.parts.append(block2)
                for pos in block2.neighbour:
                    block3 = self.blocks[pos]
                    if block3.color in eye_colors and not block3.eye:
                        blocks_to_process.append(block3)
        #check that all empty points are adjacent to our color
        ok_eye_list = []
        for eye in eye_list:
            prev_our_blocks = None
            eye_is_ok = False
            for stone in eye.iterate_stones():
                if self.goban[stone]!=EMPTY:
                    continue
                eye_is_ok = True
                our_blocks = []
                for pos in self.iterate_neighbour(stone):
                    block = self.blocks[pos]
                    if block.color==color and block not in our_blocks:
                        our_blocks.append(block)
                #list of blocks different than earlier
                if prev_our_blocks!=None and prev_our_blocks != our_blocks:
                    ok_our_blocks = []
                    for block in our_blocks:
                        if block in prev_our_blocks:
                            ok_our_blocks.append(block)
                    our_blocks = ok_our_blocks
                #this empty point was not adjacent to our block or there is no block that has all empty points adjacent to it
                if not our_blocks:
                    eye_is_ok = False
                    break
                    
                prev_our_blocks = our_blocks
            if eye_is_ok:
                ok_eye_list.append(eye)
                eye.our_blocks = our_blocks
            else:
                not_ok_eye_list.append(eye)
                #remove reference to eye that is not ok
                for block in eye.parts:
                    block.eye = None
        eye_list = ok_eye_list

        #first we assume all blocks to be ok
        for block in self.iterate_blocks(color):
            block.eye_count = 2

        #main loop: at end of loop check if changes
        while True:
            changed_count = 0
            for block in self.iterate_blocks(color):
                #not really needed but short and probably useful optimization
                if block.eye_count < 2:
                    continue
                #count eyes
                block_eye_list = []
                for stone in block.neighbour:
                    eye = self.blocks[stone].eye
                    if eye and eye not in block_eye_list:
                        block_eye_list.append(eye)
                #count only those eyespaces which have empty point(s) adjacent to this block
                block.eye_count = 0
                for eye in block_eye_list:
                    if block in eye.our_blocks:
                        block.eye_count = block.eye_count + 1
                if block.eye_count < 2:
                    changed_count = changed_count + 1
            #check eyes for required all groups 2 eyes
            ok_eye_list = []
            for eye in eye_list:
                eye_is_ok = True
                for block in self.iterate_neighbour_eye_blocks(eye):
                    if block.eye_count < 2:
                        eye_is_ok = False
                        break
                if eye_is_ok:
                    ok_eye_list.append(eye)
                else:
                    changed_count = changed_count + 1
                    not_ok_eye_list.append(eye)
                    #remove reference to eye that is not ok
                    for block in eye.parts:
                        block.eye = None
                eye_list = ok_eye_list
            if not changed_count:
                break

        #mark alive and dead blocks
        for block in self.iterate_blocks(color):
            if block.eye_count >= 2:
                block.status = UNCONDITIONAL_LIVE
        for eye in eye_list:
            eye.mark_status(color)

        #for heuristical death search
        if self.assumed_unconditional_alive_list:
            for pos in self.assumed_unconditional_alive_list:
                block = self.blocks[pos]
                block.status = UNCONDITIONAL_LIVE
                extend_color = block.color

            blocks2analyse = []
            for block in self.iterate_blocks(extend_color):
                if block.status==UNCONDITIONAL_LIVE:
                    blocks2analyse.append(block)
            while blocks2analyse:
                block1 = blocks2analyse.pop()
                for block2 in self.iterate_blocks(extend_color):
                    if block2.status==UNCONDITIONAL_UNKNOWN and \
                           len(self.block_connection_status(block1.get_origin(), block2.get_origin()))>=2:
                        blocks2analyse.append(block2)
                        block2.status = UNCONDITIONAL_LIVE

        #Unconditional dead part:
        #Mark all groups with only 1 potential empty point and completely surrounded by live groups as dead.
        #All empty points adjacent to live group are not counted.
        for eye_group in not_ok_eye_list:
            eye_group.dead_analysis_done = False
        for eye_group in not_ok_eye_list:
            if eye_group.dead_analysis_done: continue
            eye_group.dead_analysis_done = True
            true_eye_list = []
            false_eye_list = []
            eye_block = Block(eye_colors)
            #If this is true then creating 2 eyes is impossible or we need to analyse false eye status.
            #If this is false, then we are unsure and won't mark it as dead.
            two_eyes_impossible = True
            has_unconditional_neighbour_block = False
            maybe_dead_group = Eye()
            blocks_analysed = []
            blocks_to_analyse = eye_group.parts[:]
            while blocks_to_analyse and two_eyes_impossible:
                block = blocks_to_analyse.pop()
                if block.eye:
                    block.eye.dead_analysis_done = True
                blocks_analysed.append(block)
                if block.status==UNCONDITIONAL_LIVE:
                    if block.color==color:
                        has_unconditional_neighbour_block = True
                    else:
                        two_eyes_impossible = False
                    continue
                maybe_dead_group.parts.append(block)
                for pos in block.stones:
                    eye_block.add_stone(pos)
                    if block.color==EMPTY:
                        eye_type = self.analyse_eye_point(pos, color)
                    elif block.color==color:
                        eye_type = self.analyse_opponent_stone_as_eye_point(pos)
                    else:
                        continue
                    if eye_type==None:
                        continue
                    if eye_type==True:
                        if len(true_eye_list) == 2:
                            two_eyes_impossible = False
                            break
                        elif len(true_eye_list) == 1:
                            if self.are_adjacent_points(pos, true_eye_list[0]):
                                #Second eye point is adjacent to first one.
                                true_eye_list.append(pos)
                            else: #Second eye point is not adjacent to first one.
                                two_eyes_impossible = False
                                break
                        else: #len(empty_list) == 0
                            true_eye_list.append(pos)
                    else: #eye_type==False
                        false_eye_list.append(pos)
                if two_eyes_impossible:
                    #bleed to neighbour blocks that are at other side of blocking color block:
                    #consider whole area surrounded by unconditional blocks as one group
                    for pos in block.neighbour:
                        block = self.blocks[pos]
                        if block not in blocks_analysed and block not in blocks_to_analyse:
                            blocks_to_analyse.append(block)
                
            #must be have some neighbour groups:
            #for example board that is filled with stones except for one empty point is not counted as unconditionally dead
            if two_eyes_impossible and has_unconditional_neighbour_block:
                if (true_eye_list and false_eye_list) or \
                   len(false_eye_list) >= 2:
                    #Need to do false eye analysis to see if enough of them turn to true eyes.
                    both_eye_list = true_eye_list + false_eye_list
                    stone_block_list = []
                    #Add holes to eye points
                    for eye in both_eye_list:
                        eye_block.remove_stone(eye)

                    #Split group by eyes.
                    new_mark = 2 #When stones are added they get by default value True (==1)
                    for eye in both_eye_list:
                        for pos in self.iterate_neighbour(eye):
                            if pos in eye_block.stones:
                                self.flood_mark(eye_block, pos, new_mark)
                                splitted_block = self.split_marked_group(eye_block, new_mark)
                                stone_block_list.append(splitted_block)

                    #Add eyes to block neighbour.
                    for eye in both_eye_list:
                        for pos in self.iterate_neighbour(eye):
                            for block in stone_block_list:
                                if pos in block.stones:
                                    block.neighbour[eye] = True

                    #main false eye loop: at end of loop check if changes
                    while True:
                        changed_count = 0
                        #Remove actual false eyes from list.
                        for block in stone_block_list:
                            if len(block.neighbour)==1:
                                 neighbour_list = block.neighbour.keys()
                                 eye = neighbour_list[0]
                                 both_eye_list.remove(eye)
                                 #combine this block and eye into other blocks by 'filling' false eye
                                 block.add_stone(eye)
                                 for block2 in stone_block_list[:]:
                                     if block!=block2 and eye in block2.neighbour:
                                         block.add_block(block2)
                                         stone_block_list.remove(block2)
                                 del block.neighbour[eye]
                                 changed_count =  changed_count + 1
                                 break #we have changed stone_block_list, restart

                        if not changed_count:
                            break

                    #Check if we have enough eyes.
                    if len(both_eye_list) > 2:
                        two_eyes_impossible = False
                    elif len(both_eye_list) == 2:
                        if not self.are_adjacent_points(both_eye_list[0], both_eye_list[1]):
                            two_eyes_impossible = False
                #False eye analysis done: still surely dead
                if two_eyes_impossible:
                    maybe_dead_group.mark_status(color)
Exemplo n.º 39
0
class Target:
    
    IMAGE_WIDTH = 352
    IMAGE_HEIGHT = 288
    
    INITIAL_STARE_COUNT = 5 # how many frames without proximate movement before we start tracking a new blob
    TRACKING_PROXIMITY = 20.0 # blobs further away than this are considered not part of the tracked object
    
    def __init__(self):
        self.capture = cv.CaptureFromCAM(0)
        cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, self.IMAGE_WIDTH)
        cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, self.IMAGE_HEIGHT)
        # cv.NamedWindow("Target", 1)
        # cv.NamedWindow("Intermediate", 1)
        self.theGiantEye = Eye()
        self.interest = 0.0 # how interested we are, 0 - 100

    def drawRect(self, image, rect):
        pt1 = (rect[0], rect[1])
        pt2 = (rect[0] + rect[2], rect[1] + rect[3])                
        cv.Rectangle(image, pt1, pt2, cv.CV_RGB(255,0,0), 1)

    def bullsEye(self, image, point):        
        cv.Circle(image, point, 40, cv.CV_RGB(255, 255, 255), 1)
        cv.Circle(image, point, 30, cv.CV_RGB(255, 100, 0), 1)
        cv.Circle(image, point, 20, cv.CV_RGB(255, 255, 255), 1)
        cv.Circle(image, point, 10, cv.CV_RGB(255, 100, 0), 5)
        
    def calcAzimuth(self, point):
        xoffs = point[0] - self.image_centre[0]
        yoffs = point[1] - self.image_centre[1]       
        return 180.0 - 180.0 * math.atan2(yoffs, xoffs) / math.pi

    def calcAltitude(self, point):
        # outside of image donut is horizontal-ish (-20 degrees)
        # inside of image dount is steeply down (-70)
        # for servo, 30 is steep down, 90 is horizontal
        d = self.distance(self.image_centre, point)
        inner_radius = 45.0
        outer_radius = 120.0
        angle_min = 60.0 # steep down
        angle_max = 90.0 # nearly horizontal

        if d < inner_radius:
            return angle_min
        elif d > outer_radius:
            return angle_max
        else:
            return (d - inner_radius) / (outer_radius - inner_radius) * (angle_max - angle_min) + angle_min

    def area(self, rect):
        return rect[2] * rect[3]
    
    def centre(self, rect):
        return (rect[0] + rect[2] / 2, rect[1] + rect[3] / 2)

    def distance(self, p1, p2):
        return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)

    def chooseTrackingPoint(self, rectangles, last):
        
        if len(rectangles) == 0:
            return None
        
        # given non-empty list of rectangles
        # ideas: choose the rectangle closest to the last one; if no last one, choose the biggest
        # if all rectangles are too far away, return None
        # return the centre point of the chosen rectangle
        
        def proximity(rect):
            c = self.centre(rect)           
            return self.distance(c, last)
        
        if last:
            choice = sorted(rectangles, key=proximity)[0] # we want the nearest
            
           
            if proximity(choice) > 50.0: # but forget it if too far away
                # print "ignoring blob at distance ", proximity(choice)
                choice = None
            # else:
                # print "tracking blob ", choice, "at distance ", proximity(choice) 
        else:
            choice = sorted(rectangles, key=self.area)[0] # we want the biggest
            # print "biggest blob  is ", choice
        
        return self.centre(choice) if choice else None

    def applyMask(self, image):
	cv.Circle(image, self.image_centre, 45, cv.CV_RGB(127, 127, 127), -1)
	cv.Circle(image, self.image_centre, 150, cv.CV_RGB(127, 127, 127), 100)

    def incInterest(self):
        if self.interest < 100.0:
            self.interest += 5.0

    def decInterest(self):
        if self.interest > 0.0:
            self.interest -= 5.0

    def loseInterest(self):
        self.interest = 0.0
                
    
    def calibrate(self):
        # Set the servos to known positions so we can assemble the hardware
        # Set alt to level
        self.theGiantEye.setAltitude(90)
        #Set azimuth to straigh ahead
        self.theGiantEye.setAzimuth(90)
        # set the pupil to min interest, all the way out
        self.theGiantEye.setPupil(0)

    def run(self):
        # Capture first frame to get size
        frame = cv.QueryFrame(self.capture)
        frame_size = cv.GetSize(frame)
        self.image_centre = (frame_size[0] / 2, frame_size[1] / 2)
        self.applyMask(frame)
                
        difference = cv.CloneImage(frame)
        temp = cv.CloneImage(frame)
        
        grey_image = cv.CreateImage(frame_size, cv.IPL_DEPTH_8U, 1)
        
        moving_average = cv.CreateImage(frame_size, cv.IPL_DEPTH_32F, 3)      
        cv.ConvertScale(frame, moving_average, 1.0, 0.0)

        print 'Size: ', frame_size
        
        stare_count = self.INITIAL_STARE_COUNT
        tracking_point = None
        
        while True:
            # Capture frame from webcam
            color_image = cv.QueryFrame(self.capture)
            self.applyMask(frame)
            
            # Smooth to get rid of false positives
            # cv.Smooth(color_image, color_image, cv.CV_GAUSSIAN, 3, 0)
            
            # third parameter is weight, originally 0.020
            cv.RunningAvg(color_image, moving_average, 0.1, None)
            
            # Convert the scale of the moving average.
            cv.ConvertScale(moving_average, temp, 1.0, 0.0)
            
            # Minus the current frame from the moving average.
            cv.AbsDiff(color_image, temp, difference)
            
            # Convert the image to grayscale.
            cv.CvtColor(difference, grey_image, cv.CV_RGB2GRAY)
            
            # Convert the image to black and white. Threshold was  originally 70
            cv.Threshold(grey_image, grey_image, 30, 255, cv.CV_THRESH_BINARY)
            
            # cv.ShowImage("Intermediate", grey_image)

            # Dilate and erode to get object blobs
            cv.Dilate(grey_image, grey_image, None, 18)
            cv.Erode(grey_image, grey_image, None, 10)
            
            # Calculate movements
            storage = cv.CreateMemStorage(0)
            contour = cv.FindContours(grey_image, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
                       
            # contour is a CVSeq object: http://docs.opencv.org/modules/core/doc/dynamic_structures.html#cvseq
            # it represents a sequence of contours; each contour is a vector of points
            # cvseq object is itself an iterable over the first vector in the sequence
            
            rectangles = []
            
            while contour:
                # Draw rectangles
                bound_rect = cv.BoundingRect(list(contour))
                # bound_rect is (x, y, width, height)
                # print "Rectangle: ", bound_rect
                
                # move to next contour in the sequence
                contour = contour.h_next()
                
                self.drawRect(color_image, bound_rect)
                rectangles.append(bound_rect)
            
            candidate = self.chooseTrackingPoint(rectangles, tracking_point)                 
                            
            if candidate:
                tracking_point = candidate
                stare_count = self.INITIAL_STARE_COUNT
                self.incInterest()
            else:
                # idea: count down a few frames before forgetting the tracking point
                if stare_count:
                    stare_count -= 1
                    self.decInterest()
                else:
                    tracking_point = None
                    self.loseInterest()

            if tracking_point:
                # draw bull's eye
                self.bullsEye(color_image, tracking_point)              

                azimuth = self.calcAzimuth(tracking_point)
                print "Azimuth: ", azimuth
                self.theGiantEye.setAzimuth(azimuth)  

                altitude = self.calcAltitude(tracking_point)
                print "Altitude: ", altitude
                self.theGiantEye.setAltitude(altitude)

            # always display the interest level
            print "Interest: ", self.interest
            self.theGiantEye.setPupil(self.interest)

            # if lost interest, stare into the distance
            if self.interest < 5.0:
                self.theGiantEye.setAltitude(90.0)

            # Display frame to user
            # cv.ShowImage("Target", color_image)
            
            time.sleep(0.001)

            # Listen for ESC or ENTER key
            c = cv.WaitKey(7) % 0x100
            if c == 27 or c == 10:
                break
Exemplo n.º 40
0
Arquivo: agent.py Projeto: e0en/See
class Agent:
    def __init__(self, queue_world, queue_monitor=None):
        self.queue_world = queue_world
        self.queue_monitor = queue_monitor

    def _init_model(self):
        self.eye = Eye()
        self.A = gnp.zeros((5000,5000))

    def run_model(self, input_data):
        d_x = random.randint(-16, 16)
        d_y = random.randint(-16, 16)
        d_angle = random.randint(-15, 15)
        d_scale = 2**random.uniform(-0.5, 0.5)
        return (d_x, d_y, d_angle, d_scale)

    def move_eye(self, output_data):
        d_x, d_y, d_angle, d_scale = output_data
        self.eye_pos = (self.eye_pos[0] + d_x*self.eye_scale, self.eye_pos[1] + d_y*self.eye_scale)
        self.eye_scale *= d_scale
        self.eye_angle += d_angle

        self.eye_pos = \
                (min(max(self.eye_pos[0], 0), self.world_size[0]-1),
                        min(max(self.eye_pos[1], 0), self.world_size[1]-1))
        self.eye_scale = min(self.eye_scale, 1.0*min(self.world_size[0], self.world_size[1])/self.eye.mask_size)
        self.eye_scale = min(max(self.eye_scale, 0.5), 4)
        self.eye_angle = min(max(self.eye_angle, -90), 90)

    def run(self):
        self._init_model()

        while 1:
            if not self.queue_world.empty():
                world_data = self.queue_world.get()
                self.world_image, self.world_size = world_data['image_string'], world_data['size']
                self.world_id = world_data['id']
                break
        self.eye_pos = (self.world_size[0]/2, self.world_size[1]/2)
        self.eye_angle = 0.0
        self.eye_scale = 1.0

        while 1:
            if not self.queue_world.empty():
                world_data = self.queue_world.get()
                self.world_image, self.world_size = world_data['image_string'], world_data['size']
                self.world_id = world_data['id']
            self.image = Image.fromstring("RGB", self.world_size, self.world_image)

            self.fovea = self.eye.img2fovea(self.image, self.eye_pos, self.eye_angle, self.eye_scale)

            self.move_eye(self.run_model(self.fovea))

            self.fovea_img = self.eye.fovea2img()

            if self.queue_monitor != None and self.queue_monitor.empty():
                monitor_data = {
                        'fovea_img': self.fovea_img.tostring(),
                        'fovea_size': self.fovea_img.size,
                        'eye_pos': self.eye_pos,
                        'eye_scale': self.eye_scale,
                        'eye_angle': self.eye_angle,
                        }

                self.queue_monitor.put(monitor_data)
Exemplo n.º 41
0
    def analyze_color_unconditional_status(self, color):
        """1) List potential eyes (eyes: empty+opponent areas flood filled):
              all empty points must be adjacent to those neighbour blocks with given color it gives eye.
           2) List all blocks with given color
              that have at least 2 of above mentioned areas adjacent
              and has empty point from it as liberty.
           3) Go through all potential eyes. If there exists neighbour
              block with less than 2 eyes: remove this this eye from list.
           4) If any changes in step 3, go back to step 2.
           5) Remaining blocks of given color are unconditionally alive and
              and all opponent blocks inside eyes are unconditionally dead.
           6) Finally update status of those blocks we know.
           7) Analyse dead group status.

           See test.py for testcases
        """
        #find potential eyes
        eye_list = []
        not_ok_eye_list = [
        ]  #these might still contain dead groups if totally inside live group
        eye_colors = EMPTY + other_side[color]
        for block in self.iterate_blocks(EMPTY + WHITE + BLACK):
            block.eye = None
        for block in self.iterate_blocks(eye_colors):
            if block.eye: continue
            current_eye = Eye()
            eye_list.append(current_eye)
            blocks_to_process = [block]
            while blocks_to_process:
                block2 = blocks_to_process.pop()
                if block2.eye: continue
                block2.eye = current_eye
                current_eye.parts.append(block2)
                for pos in block2.neighbour:
                    block3 = self.blocks[pos]
                    if block3.color in eye_colors and not block3.eye:
                        blocks_to_process.append(block3)
        #check that all empty points are adjacent to our color
        ok_eye_list = []
        for eye in eye_list:
            prev_our_blocks = None
            eye_is_ok = False
            for stone in eye.iterate_stones():
                if self.goban[stone] != EMPTY:
                    continue
                eye_is_ok = True
                our_blocks = []
                for pos in self.iterate_neighbour(stone):
                    block = self.blocks[pos]
                    if block.color == color and block not in our_blocks:
                        our_blocks.append(block)
                #list of blocks different than earlier
                if prev_our_blocks != None and prev_our_blocks != our_blocks:
                    ok_our_blocks = []
                    for block in our_blocks:
                        if block in prev_our_blocks:
                            ok_our_blocks.append(block)
                    our_blocks = ok_our_blocks
                #this empty point was not adjacent to our block or there is no block that has all empty points adjacent to it
                if not our_blocks:
                    eye_is_ok = False
                    break

                prev_our_blocks = our_blocks
            if eye_is_ok:
                ok_eye_list.append(eye)
                eye.our_blocks = our_blocks
            else:
                not_ok_eye_list.append(eye)
                #remove reference to eye that is not ok
                for block in eye.parts:
                    block.eye = None
        eye_list = ok_eye_list

        #first we assume all blocks to be ok
        for block in self.iterate_blocks(color):
            block.eye_count = 2

        #main loop: at end of loop check if changes
        while True:
            changed_count = 0
            for block in self.iterate_blocks(color):
                #not really needed but short and probably useful optimization
                if block.eye_count < 2:
                    continue
                #count eyes
                block_eye_list = []
                for stone in block.neighbour:
                    eye = self.blocks[stone].eye
                    if eye and eye not in block_eye_list:
                        block_eye_list.append(eye)
                #count only those eyespaces which have empty point(s) adjacent to this block
                block.eye_count = 0
                for eye in block_eye_list:
                    if block in eye.our_blocks:
                        block.eye_count = block.eye_count + 1
                if block.eye_count < 2:
                    changed_count = changed_count + 1
            #check eyes for required all groups 2 eyes
            ok_eye_list = []
            for eye in eye_list:
                eye_is_ok = True
                for block in self.iterate_neighbour_eye_blocks(eye):
                    if block.eye_count < 2:
                        eye_is_ok = False
                        break
                if eye_is_ok:
                    ok_eye_list.append(eye)
                else:
                    changed_count = changed_count + 1
                    not_ok_eye_list.append(eye)
                    #remove reference to eye that is not ok
                    for block in eye.parts:
                        block.eye = None
                eye_list = ok_eye_list
            if not changed_count:
                break

        #mark alive and dead blocks
        for block in self.iterate_blocks(color):
            if block.eye_count >= 2:
                block.status = UNCONDITIONAL_LIVE
        for eye in eye_list:
            eye.mark_status(color)

        #for heuristical death search
        if self.assumed_unconditional_alive_list:
            for pos in self.assumed_unconditional_alive_list:
                block = self.blocks[pos]
                block.status = UNCONDITIONAL_LIVE
                extend_color = block.color

            blocks2analyse = []
            for block in self.iterate_blocks(extend_color):
                if block.status == UNCONDITIONAL_LIVE:
                    blocks2analyse.append(block)
            while blocks2analyse:
                block1 = blocks2analyse.pop()
                for block2 in self.iterate_blocks(extend_color):
                    if block2.status==UNCONDITIONAL_UNKNOWN and \
                           len(self.block_connection_status(block1.get_origin(), block2.get_origin()))>=2:
                        blocks2analyse.append(block2)
                        block2.status = UNCONDITIONAL_LIVE

        #Unconditional dead part:
        #Mark all groups with only 1 potential empty point and completely surrounded by live groups as dead.
        #All empty points adjacent to live group are not counted.
        for eye_group in not_ok_eye_list:
            eye_group.dead_analysis_done = False
        for eye_group in not_ok_eye_list:
            if eye_group.dead_analysis_done: continue
            eye_group.dead_analysis_done = True
            true_eye_list = []
            false_eye_list = []
            eye_block = Block(eye_colors)
            #If this is true then creating 2 eyes is impossible or we need to analyse false eye status.
            #If this is false, then we are unsure and won't mark it as dead.
            two_eyes_impossible = True
            has_unconditional_neighbour_block = False
            maybe_dead_group = Eye()
            blocks_analysed = []
            blocks_to_analyse = eye_group.parts[:]
            while blocks_to_analyse and two_eyes_impossible:
                block = blocks_to_analyse.pop()
                if block.eye:
                    block.eye.dead_analysis_done = True
                blocks_analysed.append(block)
                if block.status == UNCONDITIONAL_LIVE:
                    if block.color == color:
                        has_unconditional_neighbour_block = True
                    else:
                        two_eyes_impossible = False
                    continue
                maybe_dead_group.parts.append(block)
                for pos in block.stones:
                    eye_block.add_stone(pos)
                    if block.color == EMPTY:
                        eye_type = self.analyse_eye_point(pos, color)
                    elif block.color == color:
                        eye_type = self.analyse_opponent_stone_as_eye_point(
                            pos)
                    else:
                        continue
                    if eye_type == None:
                        continue
                    if eye_type == True:
                        if len(true_eye_list) == 2:
                            two_eyes_impossible = False
                            break
                        elif len(true_eye_list) == 1:
                            if self.are_adjacent_points(pos, true_eye_list[0]):
                                #Second eye point is adjacent to first one.
                                true_eye_list.append(pos)
                            else:  #Second eye point is not adjacent to first one.
                                two_eyes_impossible = False
                                break
                        else:  #len(empty_list) == 0
                            true_eye_list.append(pos)
                    else:  #eye_type==False
                        false_eye_list.append(pos)
                if two_eyes_impossible:
                    #bleed to neighbour blocks that are at other side of blocking color block:
                    #consider whole area surrounded by unconditional blocks as one group
                    for pos in block.neighbour:
                        block = self.blocks[pos]
                        if block not in blocks_analysed and block not in blocks_to_analyse:
                            blocks_to_analyse.append(block)

            #must be have some neighbour groups:
            #for example board that is filled with stones except for one empty point is not counted as unconditionally dead
            if two_eyes_impossible and has_unconditional_neighbour_block:
                if (true_eye_list and false_eye_list) or \
                   len(false_eye_list) >= 2:
                    #Need to do false eye analysis to see if enough of them turn to true eyes.
                    both_eye_list = true_eye_list + false_eye_list
                    stone_block_list = []
                    #Add holes to eye points
                    for eye in both_eye_list:
                        eye_block.remove_stone(eye)

                    #Split group by eyes.
                    new_mark = 2  #When stones are added they get by default value True (==1)
                    for eye in both_eye_list:
                        for pos in self.iterate_neighbour(eye):
                            if pos in eye_block.stones:
                                self.flood_mark(eye_block, pos, new_mark)
                                splitted_block = self.split_marked_group(
                                    eye_block, new_mark)
                                stone_block_list.append(splitted_block)

                    #Add eyes to block neighbour.
                    for eye in both_eye_list:
                        for pos in self.iterate_neighbour(eye):
                            for block in stone_block_list:
                                if pos in block.stones:
                                    block.neighbour[eye] = True

                    #main false eye loop: at end of loop check if changes
                    while True:
                        changed_count = 0
                        #Remove actual false eyes from list.
                        for block in stone_block_list:
                            if len(block.neighbour) == 1:
                                neighbour_list = block.neighbour.keys()
                                eye = neighbour_list[0]
                                both_eye_list.remove(eye)
                                #combine this block and eye into other blocks by 'filling' false eye
                                block.add_stone(eye)
                                for block2 in stone_block_list[:]:
                                    if block != block2 and eye in block2.neighbour:
                                        block.add_block(block2)
                                        stone_block_list.remove(block2)
                                del block.neighbour[eye]
                                changed_count = changed_count + 1
                                break  #we have changed stone_block_list, restart

                        if not changed_count:
                            break

                    #Check if we have enough eyes.
                    if len(both_eye_list) > 2:
                        two_eyes_impossible = False
                    elif len(both_eye_list) == 2:
                        if not self.are_adjacent_points(
                                both_eye_list[0], both_eye_list[1]):
                            two_eyes_impossible = False
                #False eye analysis done: still surely dead
                if two_eyes_impossible:
                    maybe_dead_group.mark_status(color)
Exemplo n.º 42
0
Arquivo: agent.py Projeto: e0en/See
 def _init_model(self):
     self.eye = Eye()
     self.A = gnp.zeros((5000,5000))