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)
Exemple #2
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')
    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
Exemple #4
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 = []
Exemple #5
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))
Exemple #6
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
Exemple #7
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
     ]
Exemple #8
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}
Exemple #9
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()
Exemple #10
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')
Exemple #11
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
Exemple #12
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
Exemple #13
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
Exemple #15
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)
Exemple #16
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'
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()
Exemple #18
0
 def __init__(self):
     self.left_eye = Eye()
     self.right_eye = Eye()
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()
from network import UnmannedNet
from control import Auto
from eye import Eye
import time
brain = UnmannedNet(768, 60, 2)
auto = Auto([29, 31, 33, 35, 38, 40])
eye = Eye("192.168.10.1")
brain.loadnetwork()
while (1):
    inputdata = self.eye.getResizeImage()
    control = self.brain.prediction(inputdata)
    beta = control[0]
    gamma = control[1]
    auto.control(beta, gamma)
    time.sleep(0.1)
Exemple #21
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()
Exemple #22
0
def test_look():
    """Test look method"""
    e = Eye()
    e.look((1, 1))
    assert e.direction == (1, 1)
Exemple #23
0
def test_constructor():
    """Test Eye constructor"""
    e = Eye()
    assert e.direction == (0, 0)
Exemple #24
0
def test_constructor():
    e = Eye()
    assert e.direction == (0, 0)
Exemple #25
0
def test_look():
    e = Eye()
    e.look((1, 1))
    assert e.direction == (1, 1)
Exemple #26
0
 def __init__(self):
     """Eyes constructor"""
     self.left_eye = Eye()
     self.right_eye = Eye()
    def detect_face(self, frame):
        # grab the frame from the threaded video stream and resize it


        # grab the frame dimensions and convert it to a blob
        self.frame = frame

        (h, w) = frame.shape[:2]
        #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,
            (300, 300), (104.0, 177.0, 123.0))

        # pass the blob through the network and obtain the detections and
        # predictions
        self.net.setInput(blob)
        detections = self.net.forward()
        self.detections = detections


        # loop over the detections
        for i in range(0, detections.shape[2]):
            # extract the confidence (i.e., probability) associated with the
            # prediction
            confidence = detections[0, 0, i, 2]

            # filter out weak detections by ensuring the `confidence` is
            # greater than the minimum confidence
            if confidence < args["confidence"]:
                continue

            # compute the (x, y)-coordinates of the bounding box for the
            # object
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])

            (startX, startY, endX, endY) = box.astype("int")

            face_rect = dlib.rectangle(left=startX, top=startY, right=endX, bottom=endY)

            #dlib_rectangle = dlib.rectangle(left=0, top=int(frameW), right=int(frameW), bottom=int(frameH))
            try:
                landmarks = self._predictor(frame, face_rect)
                self.landmarks = 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
            landmarks_np = face_utils.shape_to_np(landmarks)
            #for (x, y) in landmarks_np:
                #cv2.circle(frame, (x, y), 1, (255, 0, 255), -1)


            # draw the bounding box of the face along with the associated
            # probability
            text = "{:.2f}%".format(confidence * 100)
            y = startY - 10 if startY - 10 > 10 else startY + 10
            """cv2.rectangle(frame, (startX, startY), (endX, endY),
                (0, 0, 255), 2)
            cv2.putText(frame, text, (startX, y),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)"""


            #frame = self.annotated_frame()

            shape = landmarks_np

            self.get_head_pose(frame,shape,h,w)


        return frame
Exemple #28
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)
Exemple #29
0
from eye import Eye

if __name__ == '__main__':
    AnEye = Eye()
    AnEye.see('./images/purple.jpg')