Пример #1
0
class ResourceBox(Rect):
    """A rect matched up with a resource, which also decides the box's color"""

    # used in creating larger white box in background to show when box is selected
    outer_box_margin = 1.2

    def __init__(self, x, y, size, resource):
        super().__init__(resource.value, size, size, (x, y))
        self.resource = resource
        self.selection_box = Rect(common.WHITE,
                                  size * ResourceBox.outer_box_margin,
                                  size * ResourceBox.outer_box_margin, (x, y))
        self.selected = False

    def draw(self, screen):
        if self.selected:
            self.selection_box.draw(screen)
        super().draw(screen)

    def select(self):
        self.selected = True

    def deselect(self):
        self.selected = False

    def check_for_mouse(self, mouse_pos):
        if self.rect.collidepoint(mouse_pos):
            return self
        else:
            # don't auto-deselect as selection state might need to be saved
            return None
Пример #2
0
 def __init__(self, x, y, size, resource):
     super().__init__(resource.value, size, size, (x, y))
     self.resource = resource
     self.selection_box = Rect(common.WHITE,
                               size * ResourceBox.outer_box_margin,
                               size * ResourceBox.outer_box_margin, (x, y))
     self.selected = False
Пример #3
0
def populate():
    # define zulus
    for i in range(1, 160):
        x = random.uniform(1, 1280)
        y = random.uniform(1, 800)
        shp = Rect(2, 2)
        pos = [x, y, 0.0]
        a = 0  # angle
        r = random.uniform(0, 1.0)
        g = random.uniform(0, 1.0)
        b = random.uniform(0, 1.0)
        a = random.uniform(0, 1.0)
        col = [r, g, b, a]
        z = Zulu(shp, pos, a, col)

        #Define as many rules as necessary
        r1 = Slide((random.uniform(-120, 120), random.uniform(-80, 80)))

        # append zulus to rules
        r1.add(z)
    for i in range(1, 160):
        x = random.uniform(1, 1200)
        y = random.uniform(1, 800)
        shp = Rect(20, 20)
        pos = [x, y, 0.0]
        a = 0  # angle
        r = random.uniform(0, 1.0)
        g = random.uniform(0, 1.0)
        b = random.uniform(0, 1.0)
        a = random.uniform(0, 1.0)
        col = [r, g, b, a]
        z = Zulu(shp, pos, a, col)
Пример #4
0
 def mousePressEvent(self, event):   # отслеживание кликов по мыши и добавление фигуры в список
     if self.instrument == 'brush':
         self.objects.append([])
         self.objects[-1].append(BrushPoint(event.x(), event.y(), self.thickness, self.color))
         self.update()
     elif self.instrument == 'line':
         self.objects.append(Line(event.x(), event.y(), event.x(), event.y(), self.thickness, self.color))
         self.update()
     elif self.instrument == 'circle':
         self.objects.append(Circle(event.x(), event.y(), event.x(), event.y(), self.thickness, self.color))
         self.update()
     elif self.instrument == 'rubber':
         self.objects.append([])
         self.objects[-1].append(BrushPoint(event.x(), event.y(), self.thickness, QColor(240, 240, 240)))
         self.update()
     elif self.instrument == 'rect':
         self.objects.append(Rect(event.x(), event.y(), 0, 0, self.thickness, self.color))
         self.update()
     elif self.instrument == 'square':
         self.objects.append(Rect(event.x(), event.y(), 0, 0, self.thickness, self.color))
         self.update()
     elif self.instrument == 'triangle':
         self.objects.append(Triangle(event.x(), event.y(), event.x(), event.y(), self.thickness, self.color))
         self.update()
     elif self.instrument == 'sqtriangle':
         self.objects.append(SqTriangle(event.x(), event.y(), event.x(), event.y(), self.thickness, self.color))
         self.update()
Пример #5
0
Файл: main.py Проект: msarch/py
def populate():
    # define zulus
    for i in range(1, 2000):
        x = random.uniform(1, 1280)
        y = random.uniform(1, 800)
        shp = Rect(20, 20)
        pos = [x, y, 0.0]
        r = random.uniform(0, 1.0)
        g = random.uniform(0, 1.0)
        b = random.uniform(0, 1.0)
        a = random.uniform(0, 1.0)
        col = [r, g, b, a]
        z = Zulu(shp, pos, col)

        #Define as many rules as necessary
        vx = random.uniform(-120, 120)
        vy = random.uniform(-80, 80)
        r1 = Slide(vx, vy)

        # append zulus to rules
        r1.add(z)
    for i in range(1, 100):
        x = random.uniform(1, 1200)
        y = random.uniform(1, 800)
        shp = Rect(20, 20)
        pos = [x, y, 0.0]
        r = random.uniform(0, 1.0)
        g = random.uniform(0, 1.0)
        b = random.uniform(0, 1.0)
        a = random.uniform(0, 1.0)
        col = [r, g, b, a]
        z = Zulu(shp, pos, col)
Пример #6
0
Файл: main.py Проект: msarch/py
def definitions():
#    # define zulus
    #for i in range (1,160):
        #x=random.uniform(1,1280)
        #y=random.uniform(1,800)
        #body=Rect(20,20)
        #anchor=[x,y,0.0]
        #angle=0 # angle
        #r=random.uniform(0,1.0)
        #g=random.uniform(0,1.0)
        #b=random.uniform(0,1.0)
        #a=random.uniform(0,1.0)
        #color=[r,g,b,a]
        #z= Zulu(body,anchor,angle,color)

    ##Define as many rules as necessary
        #r1=Slide((random.uniform(-120,120),random.uniform(-80,80)))

    ## append zulus to rules
        #r1.add(z)
    #for i in range (1,160):
        #x=random.uniform(1,1200)
        #y=random.uniform(1,800)
        #shp=Rect(20,20)
        #pos=[x,y,0.0]
        #a=0 # angle
        #r=random.uniform(0,1.0)
        #g=random.uniform(0,1.0)
        #b=random.uniform(0,1.0)
        #a=random.uniform(0,1.0)
        #col=[r,g,b,a]
        #z= Zulu(shp,pos,a,col)


    egg_white = [
        -10, -25,
        -20, -15,
        +10, -25,
        -20, +15,
        +20, -15,
        -10, +25,
        +20, +15,
        +10, +25,
    ]
    egg_yellow = [
        -10, -10,
        -10, +10,
        +10, -10,
        +10, +10,
    ]
    sh = Body([
        Prim(egg_white, Color.white).offset(+200, +105),
        Prim(egg_yellow, Color.orange).offset(+300, +200),
        Rect(100,100,120,200, Color.red).offset(100,200),
        Rect(100,100,120,200, Color.red).rotate(10).offset(200,600)
    ])
    toto= Zulu(body=sh)
    rule1=Slide((random.uniform(-12,12),random.uniform(-8,8)))
    engine.ruleset.add(rule1,toto)
Пример #7
0
    def find_eyes(self):
        """Try to detect eyes and return if successful."""
        if self.face is None:
            return False

        # Only search eyes in the upper half of the face
        bottom = self.face.top + 1. / 2. * self.face.height

        if self.nose:
            bottom = min(bottom, self.nose.top)

        # If no eyes at all
        if self.eyes[0] is None and self.eyes[1] is None:

            # Search them both
            face_patch = self.frame[self.face.top:bottom,
                                    self.face.left:self.face.right]
            eyes = self.eyeCascade.detectMultiScale(face_patch,
                                                    1.2,
                                                    2,
                                                    minSize=(5, 2),
                                                    maxSize=(200, 200))

            # We found 2 eyes. Sort eyes by x coordinate
            if len(eyes) >= 2:
                eyes = [
                    Rect._make(eye).translate(dx=self.face.left,
                                              dy=self.face.top) for eye in eyes
                ]
                if eyes[0].center.x > eyes[1].center.x:
                    eyes[0], eyes[1] = eyes[1], eyes[0]
                self.eyes = eyes
                return True

            # We found an eye, but which one?
            # Let's compare its position to the face center
            elif len(eyes) == 1:
                eye = Rect._make(eyes[0]).translate(self.face.left,
                                                    self.face.top)
                if eye.center.x < self.face.center.x:
                    self.eyes[0] = eye
                else:
                    self.eyes[1] = eye
                return True

            else:
                return False

        else:
            # Handle both eyes on their own
            self.find_single_eye(0)
            self.find_single_eye(1)
Пример #8
0
    def find_mustache(self):
        """Try to find suitable mustache position and return if successful."""
        if self.face is not None and \
                (self.nose is not None or self.mouth is not None):

            # We can use nose, mouth or a combination to find the right spot
            # for a mustache.
            if self.mouth is not None and self.nose is not None:
                x = (self.mouth.center.x + self.nose.center.x) / 2
                y = (2 * self.nose.center.y + self.mouth.center.y) / 3
                width = max(self.nose.width, self.mouth.width)
                height = abs(self.nose.center.y - self.mouth.center.y) / 3
            else:
                chosen = self.mouth or self.nose
                x = chosen.center.x
                y = chosen.bottom if chosen == self.nose else chosen.top
                width = chosen.width
                height = 20

            left = int(x - .5 * width)
            right = int(x + .5 * width)
            top = int(y - .5 * height)
            bottom = int(y + .5 * height)

            self.mustache = Rect(left, top, right - left, bottom - top)

            # Apply filter on position relative towards face position
            if self.moustache_filter is not None:
                rel = self.mustache.translate(-self.face.center.x,
                                              -self.face.center.y)
                self.moustache_filter.correct(
                    np.array([rel.left, rel.right, rel.top, rel.bottom]))
                left, right, top, bottom = self.moustache_filter.predict()
                rel = Rect(left, top, right - left, bottom - top)
                self.mustache = rel.translate(self.face.center.x,
                                              self.face.center.y)

            return True
        else:
            # Since we might have lost track of mustache completely, we forget
            # it ever existed.
            self.mustache = None
            self.reset_filter()
            return False
Пример #9
0
def populate():
    # define zulus
    z1 = Zulu()
    z1.shape = Rect(100, 100)
    z1.centroid = [0, 0, 0]
    z1.color = [123, 3, 212]
    # Define as many rules as necessary, append zulus to rules
    r1 = Slide(27, 0)
    r1.apply_to(z1)
    r2 = Bounce(land.boundaries)
    r2.apply_to(z1)
Пример #10
0
def register():
    ghost = [
        (-7, -7),  # 0
        (-7.0, 0.0),  # 1
        (-5, -5),  # 22
        (-6.7, 2.0),  # 2
        (-3, -7),  # 21
        (-5.9, 3.8),  # 3
        (-1, -7),  # 20
        (-4.6, 5.3),  # 4
        (-1, -5),  # 19
        (-2.9, 6.4),  # 5
        (1, -5),  # 18
        (-1.0, 6.9),  # 6
        (3, -7),  # 16
        (1.0, 6.9),  # 7
        (5, -5),  # 15
        (2.9, 6.4),  # 8
        (7, -7),  # 14
        (4.6, 5.3),  # 9
        (7.0, 0.0),  # 13
        (4.6, 5.3),  # 10
        (6.7, 2.0),  # 12
        (5.9, 3.8),  # 11
    ]

    s = Shape([
        Primitive(ghost, Color.black).offset(+200, +105),
        Primitive(ghost, Color.orange).offset(+300, +200),
        Rect(100, 100, 120, 200, Color.red).offset(100, 200),
        Rect(100, 100, 120, 200, Color.red).rotate(10).offset(200, 600)
    ])

    g = Actor()
    g.shape = s
    g.tick = tick
    # TODO : prevent identical name conflict
    # TODO : retiurn many
    return ([g])
Пример #11
0
    def find_face(self):
        """Perform face recognition and return if successful"""
        if self.frame is not None:
            faces = self.faceCascade.detectMultiScale(
                self.frame,
                1.2,
                1,
                minSize=(100, 100),
                flags=cv2.cv.CV_HAAR_DO_CANNY_PRUNING)
            if len(faces) > 0:
                face = faces[0]
                self.face = Rect._make(face)
                assert (face is not None)
                return True

        return False
Пример #12
0
    def find_single_eye(self, index):
        """Find one of the eyes.

        index = 0 => left eye
        index = 1 => right eye
        ."""
        assert (0 <= index < 2)

        if self.face is None:
            return False

        # Set search region
        top = self.face.top
        bottom = self.face.top + 1. / 2. * self.face.height
        left = self.face.left
        right = self.face.right

        if self.nose:
            bottom = self.nose.top

        # Adapt search region for individual eyes
        if index == 1:
            left = self.face.center.x
            if self.eyes[0] is not None:
                left = max(left, self.eyes[0].right)
        else:
            right = self.face.center.x
            if self.eyes[1] is not None:
                right = min(right, self.eyes[1].left)

        face_patch = self.frame[top:bottom, left:right]
        if left < right:
            eyes = self.eyeCascade.detectMultiScale(face_patch,
                                                    1.2,
                                                    1,
                                                    minSize=(5, 2),
                                                    maxSize=(200, 200))
        else:
            return False

        if len(eyes) > 0:
            eye = eyes[0]

            self.eyes[index] = Rect._make(eye).translate(left, self.face.top)
            return True
        else:
            return False
Пример #13
0
def populate():
    # define zulus

    for i in range(1, 2000):
        print i
        z = Zulu()
        x = random.randint(1, 1200)
        y = random.randint(1, 800)

        z.shape = Rect(20, 20)
        z.position = [x, y]

        vx = random.randint(-120, 120)
        vy = random.randint(-80, 80)

        #Define as many rules as necessary
        r1 = Slide(vx, vy)
        # append zulus to rules
        r1.add(z)
Пример #14
0
    def find_nose(self):
        """Perform nose recognition and return if successful."""
        if self.face is not None:
            # Specify region of interest
            left = self.face.left + self.face.width / 4
            right = self.face.right - self.face.width / 4
            top = self.face.top + self.face.height / 6
            bottom = self.face.bottom - self.face.height / 6

            # Nose should be above the mouth
            if self.mouth is not None:
                bottom = self.mouth.top

            # Nose should be below the eyes
            for eye in self.eyes:
                if eye is not None:
                    top = max(top, eye.bottom)

            # Search the nose
            face_patch = self.frame[top:bottom, left:right]
            if face_patch.size > 0:
                noses = self.noseCascade.detectMultiScale(
                    face_patch,
                    1.2,
                    1,
                    minSize=(10, 10),
                    maxSize=(self.face[2] / 4, self.face[3] / 2),
                    flags=cv2.cv.CV_HAAR_DO_CANNY_PRUNING)

                # Convert the found nose back to absolute coordinates
                if (len(noses) > 0):
                    self.nose = Rect._make(noses[0]).translate(left, top)
                    return True

        # If we didn't find anything
        if self.nose_timeout > 0:
            self.nose_timeout -= 1
        else:
            self.nose = None
            self.nose_timeout = 10

        return False
Пример #15
0
    def find_mouth(self):
        """Perform mouth recognition and return if successful."""
        if self.face is not None:

            # Specify region of interest
            left = self.face.left + self.face.width / 3
            right = self.face.right - self.face.width / 3
            top = self.face.top + self.face.height / 2
            bottom = self.face.bottom

            # Mouth should be below the nose
            if self.nose is not None:
                top = self.nose.bottom

            face_patch = self.frame[top:bottom, left:right]

            # Mouth should be wider than nose
            if self.nose is not None:
                minwidth = int(.7 * self.nose.width)
            else:
                minwidth = 30

            # Search for the mouth
            if face_patch.size > 0:
                mouths = self.mouthCascade.detectMultiScale(face_patch,
                                                            1.2,
                                                            1,
                                                            minSize=(minwidth,
                                                                     5))

                # Convert the result
                if len(mouths) > 0:
                    self.mouth = Rect._make(mouths[0]).translate(left, top)
                    return True

        # If we didn't find anything
        if self.mouth_timeout > 0:
            self.mouth_timeout -= 1
        else:
            self.mouth = None
            self.mouth_timeout = 10
        return False
Пример #16
0
Файл: bbw.py Проект: msarch/py
background_color(black)

#--- PATHS / PEGS ------------------------------------------------------------- TODO
#Peg(p2, (50,50)) # check if Peg concept is necessary. Replace w Point?
#Axis
#Grid

#--- SHAPES -------------------------------------------------------------------
g = int(HEIGHT / 85)  # grid Actor size, used to size object relatively
V = HEIGHT  # base speed is one screen-height per second
e = 6 * g
w = 11 * g
h = 33 * g
Blip('b1')

Rect('k1', w=e, h=h, color=blue).offseted(w / 2, w / 2 + e)
Rect('k2', w=e, h=h, color=blue).offseted(-w / 2 - e, w / 2 + e)
Rect('k3', w=e, h=h, color=blue).offseted(w / 2, -h - e - w / 2)
Rect('k4', w=e, h=h, color=blue).offseted(-w / 2 - e, -h - e - w / 2)

Rect('k5', w=h, h=e, color=blue).offseted(w / 2 + e, w / 2)
Rect('k6', w=h, h=e, color=blue).offseted(w / 2 + e, -w / 2 - e)
Rect('k7', w=h, h=e, color=blue).offseted(-h - e - w / 2, w / 2)
Rect('k8', w=h, h=e, color=blue).offseted(-h - e - w / 2, -w / 2 - e)

Rect('s1', w=h, h=w, color=blue).offseted(-h / 2, -w / 2)
Rect('s2', w=w, h=h, color=blue).offseted(-w / 2, -h / 2)

#--- ActorS --------------------------------------------------------------------
'''
shapes are added to the scene via an ordered list of Actors
Пример #17
0
Файл: bbw.py Проект: msarch/py
#Peg(p2, (50,50)) # check if Peg concept is necessary. Replace w Point?
#Axis
#Grid

#--- SHAPES -------------------------------------------------------------------
gu = int(HEIGHT /
         85)  # grid unit size in pixel, used to size object relatively
V = HEIGHT  # base speed is one screen-height per second
W = WIDTH
e = 6 * gu
w = 11 * gu
h = 33 * gu
origin = Blip()
r = Rose()

k1 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(w / 2, w / 2 + e, 0))
k2 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(-w / 2 - e, w / 2 + e, 0))
k3 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(w / 2, -h - e - w / 2, 0))
k4 = Rect(w=e,
          h=h,
          color=random_kapla(),
          peg=Peg(-w / 2 - e, -h - e - w / 2, 0))
k5 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(w / 2 + e, w / 2, 0))
k6 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(w / 2 + e, -w / 2 - e, 0))
k7 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(-h - e - w / 2, w / 2, 0))
k8 = Rect(w=h,
          h=e,
          color=random_kapla(),
          peg=Peg(-h - e - w / 2, -w / 2 - e, 0))

s1 = Rect(w=h, h=w, color=random_kapla(), peg=Peg(-h / 2, -w / 2, 0))
Пример #18
0
 def addRect(self, t):
     rect = Rect(t.get('x'), t.get('y'), t.get('width'), t.get('height'))
     self.processedroot.append(rect)
Пример #19
0
class MustacheRecognizer(object):
    """Model of mustache location

    Actually we want the place to put mustache and assume there is no existing
    one."""
    def __init__(self, black=False):
        """Initialize recognizer.

        black - whether the mustache should be drawn in black. Otherwise hair
        colour is recognised."""
        self.load_resources()
        self.reset()
        self.black = black

    def reset(self):
        """Reset the state the mustache detector is in"""
        self.frame = None
        self.face = None
        self.nose = None
        self.mouth = None
        self.mustache = None
        self.eyes = [None, None]
        self.rotation = 0
        self.skin_color = None
        self.skin_std = None
        self.hair_color = None

        self.reset_filter()

        self.step = 0
        self.features = [
            self.find_face, self.find_nose, self.find_mustache,
            self.find_mouth, self.find_eyes
        ]

        self.nose_timeout = 0
        self.mouth_timeout = 0

    def reset_filter(self):
        """Reset kalman filter."""
        self.moustache_filter = SimpleKalmanFilter(.1)

    def load_resources(self):
        """Load cascades used for recognition and image of mustache."""
        self.mustache_image = cv2.imread(MUSTACHE, -1)

        self.faceCascade = cv2.CascadeClassifier(FACECASCADE)
        self.noseCascade = cv2.CascadeClassifier(NOSECASCADE)
        self.mouthCascade = cv2.CascadeClassifier(MOUTHCASCADE)
        self.eyeCascade = cv2.CascadeClassifier(EYECASCADE)

    def update_camera(self):
        """Read next camera frame and store it."""
        self.frame = self.cam.read()[1]
        return self.frame

    def find_face(self):
        """Perform face recognition and return if successful"""
        if self.frame is not None:
            faces = self.faceCascade.detectMultiScale(
                self.frame,
                1.2,
                1,
                minSize=(100, 100),
                flags=cv2.cv.CV_HAAR_DO_CANNY_PRUNING)
            if len(faces) > 0:
                face = faces[0]
                self.face = Rect._make(face)
                assert (face is not None)
                return True

        return False

    def find_nose(self):
        """Perform nose recognition and return if successful."""
        if self.face is not None:
            # Specify region of interest
            left = self.face.left + self.face.width / 4
            right = self.face.right - self.face.width / 4
            top = self.face.top + self.face.height / 6
            bottom = self.face.bottom - self.face.height / 6

            # Nose should be above the mouth
            if self.mouth is not None:
                bottom = self.mouth.top

            # Nose should be below the eyes
            for eye in self.eyes:
                if eye is not None:
                    top = max(top, eye.bottom)

            # Search the nose
            face_patch = self.frame[top:bottom, left:right]
            if face_patch.size > 0:
                noses = self.noseCascade.detectMultiScale(
                    face_patch,
                    1.2,
                    1,
                    minSize=(10, 10),
                    maxSize=(self.face[2] / 4, self.face[3] / 2),
                    flags=cv2.cv.CV_HAAR_DO_CANNY_PRUNING)

                # Convert the found nose back to absolute coordinates
                if (len(noses) > 0):
                    self.nose = Rect._make(noses[0]).translate(left, top)
                    return True

        # If we didn't find anything
        if self.nose_timeout > 0:
            self.nose_timeout -= 1
        else:
            self.nose = None
            self.nose_timeout = 10

        return False

    def find_mouth(self):
        """Perform mouth recognition and return if successful."""
        if self.face is not None:

            # Specify region of interest
            left = self.face.left + self.face.width / 3
            right = self.face.right - self.face.width / 3
            top = self.face.top + self.face.height / 2
            bottom = self.face.bottom

            # Mouth should be below the nose
            if self.nose is not None:
                top = self.nose.bottom

            face_patch = self.frame[top:bottom, left:right]

            # Mouth should be wider than nose
            if self.nose is not None:
                minwidth = int(.7 * self.nose.width)
            else:
                minwidth = 30

            # Search for the mouth
            if face_patch.size > 0:
                mouths = self.mouthCascade.detectMultiScale(face_patch,
                                                            1.2,
                                                            1,
                                                            minSize=(minwidth,
                                                                     5))

                # Convert the result
                if len(mouths) > 0:
                    self.mouth = Rect._make(mouths[0]).translate(left, top)
                    return True

        # If we didn't find anything
        if self.mouth_timeout > 0:
            self.mouth_timeout -= 1
        else:
            self.mouth = None
            self.mouth_timeout = 10
        return False

    def find_mustache(self):
        """Try to find suitable mustache position and return if successful."""
        if self.face is not None and \
                (self.nose is not None or self.mouth is not None):

            # We can use nose, mouth or a combination to find the right spot
            # for a mustache.
            if self.mouth is not None and self.nose is not None:
                x = (self.mouth.center.x + self.nose.center.x) / 2
                y = (2 * self.nose.center.y + self.mouth.center.y) / 3
                width = max(self.nose.width, self.mouth.width)
                height = abs(self.nose.center.y - self.mouth.center.y) / 3
            else:
                chosen = self.mouth or self.nose
                x = chosen.center.x
                y = chosen.bottom if chosen == self.nose else chosen.top
                width = chosen.width
                height = 20

            left = int(x - .5 * width)
            right = int(x + .5 * width)
            top = int(y - .5 * height)
            bottom = int(y + .5 * height)

            self.mustache = Rect(left, top, right - left, bottom - top)

            # Apply filter on position relative towards face position
            if self.moustache_filter is not None:
                rel = self.mustache.translate(-self.face.center.x,
                                              -self.face.center.y)
                self.moustache_filter.correct(
                    np.array([rel.left, rel.right, rel.top, rel.bottom]))
                left, right, top, bottom = self.moustache_filter.predict()
                rel = Rect(left, top, right - left, bottom - top)
                self.mustache = rel.translate(self.face.center.x,
                                              self.face.center.y)

            return True
        else:
            # Since we might have lost track of mustache completely, we forget
            # it ever existed.
            self.mustache = None
            self.reset_filter()
            return False

    def find_eyes(self):
        """Try to detect eyes and return if successful."""
        if self.face is None:
            return False

        # Only search eyes in the upper half of the face
        bottom = self.face.top + 1. / 2. * self.face.height

        if self.nose:
            bottom = min(bottom, self.nose.top)

        # If no eyes at all
        if self.eyes[0] is None and self.eyes[1] is None:

            # Search them both
            face_patch = self.frame[self.face.top:bottom,
                                    self.face.left:self.face.right]
            eyes = self.eyeCascade.detectMultiScale(face_patch,
                                                    1.2,
                                                    2,
                                                    minSize=(5, 2),
                                                    maxSize=(200, 200))

            # We found 2 eyes. Sort eyes by x coordinate
            if len(eyes) >= 2:
                eyes = [
                    Rect._make(eye).translate(dx=self.face.left,
                                              dy=self.face.top) for eye in eyes
                ]
                if eyes[0].center.x > eyes[1].center.x:
                    eyes[0], eyes[1] = eyes[1], eyes[0]
                self.eyes = eyes
                return True

            # We found an eye, but which one?
            # Let's compare its position to the face center
            elif len(eyes) == 1:
                eye = Rect._make(eyes[0]).translate(self.face.left,
                                                    self.face.top)
                if eye.center.x < self.face.center.x:
                    self.eyes[0] = eye
                else:
                    self.eyes[1] = eye
                return True

            else:
                return False

        else:
            # Handle both eyes on their own
            self.find_single_eye(0)
            self.find_single_eye(1)

    def find_single_eye(self, index):
        """Find one of the eyes.

        index = 0 => left eye
        index = 1 => right eye
        ."""
        assert (0 <= index < 2)

        if self.face is None:
            return False

        # Set search region
        top = self.face.top
        bottom = self.face.top + 1. / 2. * self.face.height
        left = self.face.left
        right = self.face.right

        if self.nose:
            bottom = self.nose.top

        # Adapt search region for individual eyes
        if index == 1:
            left = self.face.center.x
            if self.eyes[0] is not None:
                left = max(left, self.eyes[0].right)
        else:
            right = self.face.center.x
            if self.eyes[1] is not None:
                right = min(right, self.eyes[1].left)

        face_patch = self.frame[top:bottom, left:right]
        if left < right:
            eyes = self.eyeCascade.detectMultiScale(face_patch,
                                                    1.2,
                                                    1,
                                                    minSize=(5, 2),
                                                    maxSize=(200, 200))
        else:
            return False

        if len(eyes) > 0:
            eye = eyes[0]

            self.eyes[index] = Rect._make(eye).translate(left, self.face.top)
            return True
        else:
            return False

    def get_rotation_from_eyes(self):
        """Determine rotation from face.

        Use positions of eyes to get it."""
        if self.eyes[0] is not None and self.eyes[1] is not None:
            p1 = self.eyes[0].center
            p2 = self.eyes[1].center
            rotation = -math.degrees(math.atan2(p2.y - p1.y, p2.x - p1.x))
            self.rotation = rotation
            return rotation

    def get_skin_color(self):
        """Approximate persons (average) skin color."""
        if self.nose:
            nose = self.frame[self.nose.top:self.nose.bottom,
                              self.nose.left:self.nose.right]

            # Determine average color
            self.skin_color = [
                int(nose[:, :, color].mean()) for color in [0, 1, 2]
            ]
            self.skin_std = [
                int(nose[:, :, color].std()) for color in [0, 1, 2]
            ]

    def get_hair_color(self):
        """Approximate the persons (average) hair color."""
        if self.face and self.skin_color is not None:
            hair = self.frame[self.face.top -
                              self.face.height / 50:self.face.top +
                              self.face.height / 50,
                              self.face.left:self.face.right]

            probable = np.any(
                hair[:, :] <
                np.array(self.skin_color) - 2 * np.array(self.skin_std), 2)
            if probable.size > 0 and hair.size > 0:
                hair = hair[probable]
            self.hair_color = [hair[:, color].mean() for color in [0, 1, 2]]
            return True
        else:
            return False

    def draw_mustache(self):
        """Draws a mustache on the found location"""
        if self.mustache is not None:
            _, _, width, height = self.mustache
            scaled_stache = cv2.resize(self.mustache_image,
                                       (int(width), int(height)))

            # Drawing the mustache is trickier than it seems
            if scaled_stache is not None:
                self.get_rotation_from_eyes()
                rotated_stache = ndimage.interpolation.rotate(scaled_stache,
                                                              self.rotation,
                                                              axes=(0, 1),
                                                              order=0,
                                                              reshape=True)

                # The fourth channel is the alpha value. I consider all alpha
                # values above 0.5 to be visible.
                visible = (rotated_stache[:, :, 3] > .5).nonzero()

                # Translate the visible positions towards the position where
                # the mustache should be placed
                visible2 = tuple(visible + np.array(
                    [self.mustache.top, self.mustache.left]).reshape(2, 1))

                # There is a very small probability that it will try drawing
                # the mustache out of the window.
                try:
                    if rotated_stache is not None:
                        if self.hair_color:
                            self.output[visible2] = np.array(
                                self.hair_color).reshape(1, 3)
                        else:
                            self.output[visible2] = rotated_stache[:, :, :3][
                                visible]
                except Exception, e:
                    sys.stderr.write(
                        "I can't draw a mustache at that location\n")
                    sys.stderr.write("{}\n".format(e))
Пример #20
0
#--- PATHS / PEGS ------------------------------------------------------------- TODO
#Peg(p2, (50,50)) # check if Peg concept is necessary. Replace w Point?
#Axis
#Grid

#--- SHAPES -------------------------------------------------------------------
gu = int(HEIGHT /
         85)  # grid unit size in pixel, used to size object relatively
V = HEIGHT  # base speed is one screen-height per second
e = 6 * gu
w = 11 * gu
h = 33 * gu
origin = Blip()
r = Rose()

k1 = Rect(w=e, h=h, color=red, peg=Peg(w / 2, w / 2 + e, 0))
k2 = Rect(w=e, h=h, color=blue50, peg=Peg(-w / 2 - e, w / 2 + e, 0))
k3 = Rect(w=e, h=h, color=blue, peg=Peg(w / 2, -h - e - w / 2, 0))
k4 = Rect(w=e, h=h, color=black, peg=Peg(-w / 2 - e, -h - e - w / 2, 0))

k5 = Rect(w=h, h=e, color=blue, peg=Peg(w / 2 + e, w / 2, 0))
k6 = Rect(w=h, h=e, color=blue, peg=Peg(w / 2 + e, -w / 2 - e, 0))
k7 = Rect(w=h, h=e, color=blue, peg=Peg(-h - e - w / 2, w / 2, 0))
k8 = Rect(w=h, h=e, color=blue, peg=Peg(-h - e - w / 2, -w / 2 - e, 0))

s1 = Rect(w=h, h=w, color=blue, peg=Peg(-h / 2, -w / 2, 0))
s2 = Rect(w=w, h=h, color=blue, peg=Peg(-w / 2, -h / 2, 0))

star = Compound(k1, k2, k3, k4, k5, k6, k7, k8, s1, s2)
mickey = Compound(k1, k2, k3, k4, k5, k6, k7, k8, peg=Peg(100, -100, 45))
Пример #21
0
from cells import Cell, lmnts
from utils.cfg import background_color, blue, orange, red


#--- PATHS / PEGS ------------------------------------------------------------- TODO

#--- SCENE --------------------------------------------------------------------
background_color(orange)
#Peg(p2, (50,50)) # check if Peg concept is necessary. Replace w Point?
#Axis
#Grid

#--- SHAPES -------------------------------------------------------------------
Blip('b1')
Kapla('k1', color=blue).offset(100,200)
Rect('r1', color=(0,1,1,1), w=100, h=300) # or just p2 if p1 = 0
Rect('hslider', color=red, w=100, h=300) # or just p2 if p1 = 0
# CShape(pac, Pacman)
# Shape(line (p1,p2)) # pr just p2 if p1 = 0                                    TODO
#s = Ghost(Color.blue).offset(0,0)                                              TODO

#--- CELLS --------------------------------------------------------------------
# shapes are added to the scene via an ordered list of Cells
# and thus displayed FIFO
Cell('c1', shape='b1')
Cell('c2', shape='b1')
print ''
print 'cells.lmnts viewed from c1', lmnts
#Cell(c2, cshapes='pac', peg=dk)  # possibly give either 2 or 3 coord or peg    TODO

#--- RULES --------------------------------------------------------------------
def smallTest():
    n0 = Node(0, 10, [])
    n1 = Node(1, 10, [])
    n2 = Node(2, 8, [n0, n1])

    n3 = Node(3, 8, [])
    n4 = Node(4, 6, [n3])
    n5 = Node(5, 4, [])
    n6 = Node(6, 2, [n4, n5])

    n7 = Node(7, 0, [n2, n6])
    n7.fillStats()

    tree = heuristics.tetris(n7)

    width = embedTree(tree)
    print("Width: " + str(width))
    print("White: " + str(tree.stats.whitespace))

    s = Shape(tree)
    print("BottomRect: " + str(s.bottomRect))
    print("TopRect: " + str(s.topRect))
    print(str(s.type))

    tree.printMe(0)

    print("Shape tests--------------------------------")

    r0 = Rect(10, 0, 0, 10)
    r1 = Rect(20, 0, 10, 30)

    print(s.getType(r1, r0))
    r0.left = 10
    r0.right = 20
    print(s.getType(r1, r0))
    r0.left = 20
    r0.right = 30
    print(s.getType(r1, r0))
    r0.left = 1
    r0.right = 29
    print(s.getType(r1, r0))
    r0.left = 0
    r0.right = 30
    print(s.getType(r1, r0))
    r1.left = 0
    r1.right = 10
    print(s.getType(r1, r0))
    r1.left = 10
    r1.right = 20
    print(s.getType(r1, r0))
    r1.left = 10
    r1.right = 30
    print(s.getType(r1, r0))
    r1.left = 1
    r1.right = 29
    print(s.getType(r1, r0))
    r1.left = 0
    r1.right = 30
    print(s.getType(r1, r0))
    r1.left = 10
    r1.right = 50
    print(s.getType(r1, r0))
    r0.left = 20
    r0.right = 60
    print(s.getType(r1, r0))
 def __init__(self, screen, x, y, width, height, color, labels, font):
     Rect.__init__(self, screen, x, y, width, height, color)
     self.title = Text(screen, x, y, width, height // 2, color, labels[0],
                       font)
     self.counter = Text(screen, x, y - height // 2, width, height, color,
                         labels[1], font)
Пример #24
0
Файл: bbw.py Проект: msarch/py
e = 6 * gu
w = 11 * gu
h = 33 * gu
origin = Blip()
r = Rose()

k1 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(w/2, w/2+e, 0))
k2 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(-w/2-e, w/2+e, 0))
k3 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(w/2, -h-e-w/2, 0))
k4 = Rect(w=e, h=h, color=random_kapla(), peg=Peg(-w/2 - e, -h-e-w/2, 0))
k5 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(w/2 + e, w/2, 0))
k6 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(w/2 + e, -w/2-e, 0))
k7 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(-h-e-w/2, w/2, 0))
k8 = Rect(w=h, h=e, color=random_kapla(), peg=Peg(-h-e-w/2, -w/2-e, 0))

s1 = Rect(w=h, h=w, color=random_kapla(), peg=Peg(-h/2, -w/2, 0))
s2 = Rect(w=w, h=h, color=random_kapla(), peg=Peg(-w/2, -h/2, 0))

show(k1,k2,k3,k4,k5,k6,k7,k8,s1,s2)

#star=Composite(k1,k2,k3,k4,k5,k6,k7,k8,s1,s2)
#mickey=Composite(k1,k2,k3,k4,k5,k6,k7,k8, peg=Peg(100,-100,45))
#show(star)
#show(mickey)

#--- COLLECT ------------------------------------------------------------------
'''
shapes are added to GROUPS i.e. an ordered? list of stuff
and any attributes can be added to groups as well as shapes
'''
s1.vel=Vel(W,0,0)