Example #1
0
    def _drawKeys(self, dc):
        blackPen = wx.Pen('black')
        whiteBrush = wx.Brush('white')

        # set the font
        self.font = wx.Font(self._fontSize, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                       wx.FONTWEIGHT_BOLD, False, 'Arial Rounded MT Bold')
        dc.SetFont(self.font)

        for displayKey in self._displayKeys.values():

            # draw key shadow
            shadowRect = Rect(*displayKey.scaled)
            shadowRect.OffsetXY(1, 1)
            dc.SetPen(wx.Pen('light grey', 3.5))
            dc.DrawRoundedRectangleRect(shadowRect.Get(), -.075)

            # handle selections
            if self._isKeySelected(displayKey.handle):
                if self.FindFocus() == self:
                    # TODO: Generalize this magic number from system settings.
                    #       Currently is Mac selection blue.
                    dc.SetPen(wx.Pen('#3e75d6', 2))
                else:
                    dc.SetPen(wx.Pen('dark grey', 2))
                dc.SetBrush(wx.Brush('light grey'))
            else:
                dc.SetPen(blackPen)
                dc.SetBrush(whiteBrush)

            # draw key outline
            dc.DrawRoundedRectangleRect(displayKey.scaled.Get(), -.075)

            # draw label
            self._drawLabels(dc, displayKey.labelRect, displayKey)
Example #2
0
 def __init__(self, parent, sourceKey):
     KeyDisplayPane.__init__(self,
                             parent,
                             border=10,
                             displayMode=DISPLAY_MODE_WRAPPED)
     self._displayKeys = {}
     KeyDisplayPane._initKeys(self)
     self.Bind(wx.EVT_PAINT, self.OnPaint)
     self._keySize = Size(6.0, 2.5)
     self._keySpacing = Size(0.2, 0.2)
     keyRect = Rect(0, 0, *self._keySize)
     handle = None
     if sourceKey.usage:
         handle = sourceKey.usage.MakeHandle()
     elif sourceKey.mode:
         handle = "mode:%s" % sourceKey.mode
     elif len(sourceKey.macro) > 0:
         for (i, macroKey) in enumerate(sourceKey.macro):
             handle = macroKey.MakeHandle(i)
             self._displayKeys[handle] = DisplayKey(handle, keyRect)
             self._orderedKeyHandles.append(handle)
         handle = None
     if handle is not None:
         dispKey = DisplayKey(handle, keyRect)
         self._displayKeys[handle] = dispKey
         self._orderedKeyHandles.append(handle)
         self._updateKeys()
Example #3
0
    def __init__(self, parent, displayMode, border):
        wx.ScrolledWindow.__init__(self, parent)
        self._displayKeys = {}
        self._orderedHeyHandles = []
        self._keySize = wx.Size(4, 4)
        self._keySpacing = wx.Size(1, 1)
        self._border = border
        self._selectedKeyHandle = None
        self._contentSize = Size(200, 200)
        self._displayMode = displayMode
        self._scroll = wx.Size(0, 0)
        self._scrollUnit = wx.Size(0, 0)
        self._tooltip = wx.ToolTip("")
        self._zoom = 1
        if displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
            self._zoom = 10  # 25
        self._dragStart = None
        self._dragMode = DRAG_MODE_NONE
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.SetToolTip(self._tooltip)
        self.SetScrollRate(1, 1)

        displayRect = self._getDisplayRect()
        print "displayRect: %s" % displayRect
        #           dc.SetMapMode(wx.MM_TEXT)
        dc.SetMapMode(wx.MM_METRIC)
        contentRect = Rect(dc.DeviceToLogicalX(displayRect.x),
                           dc.DeviceToLogicalY(displayRect.y),
                           dc.DeviceToLogicalXRel(displayRect.width),
                           dc.DeviceToLogicalYRel(displayRect.height))
Example #4
0
    def update(self, dt):
        # print(1 / dt)
        for obj in self._objects:
            obj.pos += obj.velocity * dt
            x1, y1 = obj.rect.topleft
            x2, y2 = obj.rect.bottomright
            x1 = round(x1)
            x2 = round(x2)
            y1 = round(y1)
            y2 = round(y2)
            points = [(x, y) for x in range(x1 - 2, x2 + 2) for y in range(y1 - 2, y2 + 2)]
            obj.one_ground = False
            for r in list(obj.rect.collidelistall([tuple(self.get_block(p).rect) for p in points if self.get_block(p).has_collision])):
                r: Rect = Rect(r)
                n = obj.pos - r.center
                n = n.unit

                if n.x > 0.5:
                    obj.rect.left = r.right + 0.05
                    obj.velocity.x = 0
                    obj.one_wall = True
                elif n.x < -0.5:
                    obj.rect.right = r.left - 0.05
                    obj.velocity.x = 0
                    obj.one_wall = True
                else:
                    if n.y > 0:
                        obj.rect.top = r.bottom
                        obj.velocity.y = 0
                        obj.one_ground = True
                    elif n.y < 0:
                        obj.rect.bottom = r.top
                        obj.velocity.y = 0
                        obj.one_ground = False
            obj.velocity += self.gravity * dt
Example #5
0
 def _refreshKey(self, displayKey):
     """
     Calculate the appropriate region of the screen to refresh based
     on the given displayKey.
     """
     refreshRect = Rect(*displayKey.scaled)
     refreshRect.Inflate(2, 2)
     self.RefreshRect(refreshRect.Get())
Example #6
0
 def _getDrawingArea(self):
     """
     Return a Rect encompassing the allowable drawing area of the current client window,
     in device units.
     """
     drawingArea = Rect(*self.GetClientRect())
     drawingArea.Deflate(self._border, self._border)
     return drawingArea
Example #7
0
 def rect_iter(self):
     for ind in xrange(len(self.bbox_array)):
         rect = Rect(self.bbox_array[ind][0],  
                   self.bbox_array[ind][1], 
                   self.bbox_array[ind][2], 
                   self.bbox_array[ind][3], 
                   label = self.label_array[ind])
         yield rect
Example #8
0
    def _updateKeys(self):
        """
        Adjust position and scale of each display key based on current display rect.
        """
        drawingArea = self._getDrawingArea()
        self._scroll.width = self._scroll.height = 0
        self._scrollUnit = drawingArea.size
        scale = self._getScale(drawingArea)

        if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
            contentArea = self._getContentArea()
            for displayKey in self._displayKeys.values():
                displayKey.scaled = displayKey.unscaled * scale
                displayKey.scaled.Offset(contentArea.origin)
                displayKey.labelRect = Rect(*displayKey.unscaled)
                displayKey.labelRect.Deflate(0.2, 0.2)
                displayKey.labelRect *= scale
                displayKey.labelRect.Offset(contentArea.origin)
            self._fontSize = scale * 0.37

        else:
            maxWidth = drawingArea.width / scale
            origin = Point(0, 0)
            for displayKeyHandle in self._orderedKeyHandles:
                displayKey = self._displayKeys[displayKeyHandle]
                if origin.x + self._keySize.width > maxWidth:
                    origin.x = 0
                    origin.y += self._keySize.height + self._keySpacing.height
                displayKey.unscaled.x = origin.x
                displayKey.unscaled.y = origin.y
                displayKey.scaled = displayKey.unscaled * scale
                self._scroll.width = max(self._scroll.width, displayKey.scaled.x + displayKey.scaled.width)
                self._scroll.height = max(self._scroll.height, displayKey.scaled.y + displayKey.scaled.height)
                displayKey.scaled.Offset(drawingArea.origin)
                displayKey.labelRect = Rect(*displayKey.unscaled)
                displayKey.labelRect.Deflate(0.2, 0.2)
                displayKey.labelRect *= scale
                displayKey.labelRect.Offset(drawingArea.origin)
                origin.x += self._keySize.width + self._keySpacing.width
                self._scrollUnit.width = min(self._scrollUnit.width, displayKey.scaled.width)
                self._scrollUnit.height = min(self._scrollUnit.height, displayKey.scaled.height)
            self._scroll.width  += self._border * 2
            self._scroll.height += self._border * 2
            self._scrollUnit.width  += self._keySpacing.width  * scale
            self._scrollUnit.height += self._keySpacing.height * scale
Example #9
0
def generate_goal_area(*, snake: Snake, field: Field) -> Rect:
    collision = True
    possible_goal: Rect = Rect(x=0, y=0, w=0, h=0)
    while collision:
        possible_goal = random_rect(size=9, area=field.client_area())
        collision = False
        for point in snake:
            if rect_contains_point(possible_goal, point):
                collision = True
    return possible_goal
Example #10
0
 def __init__(self, parent, sourceKey):
     KeyDisplayPane.__init__(self,
                             parent,
                             border=10,
                             displayMode=DISPLAY_MODE_DYNAMIC_RESIZE)
     self._sourceKey = sourceKey
     self._dispKey = DisplayKey(sourceKey.handle, Rect(0, 0, 1.8, 1.8))
     self._displayKeys = {sourceKey.handle: self._dispKey}
     self._updateKeys()
     KeyDisplayPane._initKeys(self)
Example #11
0
 def _initKeys(self):
     KeyDisplayPane._initKeys(self)
     self._displayKeys = {
         'left_shift': DisplayKey('left_shift', Rect(0.0, 0.0, 2.8, 1.8)),
         'left_ctrl': DisplayKey('left_ctrl', Rect(0.0, 2.0, 2.8, 1.8)),
         'left_alt': DisplayKey('left_alt', Rect(0.0, 4.0, 2.8, 1.8)),
         'left_gui': DisplayKey('left_gui', Rect(0.0, 6.0, 2.8, 1.8)),
         'right_shift': DisplayKey('right_shift', Rect(3.0, 0.0, 2.8, 1.8)),
         'right_ctrl': DisplayKey('right_ctrl', Rect(3.0, 2.0, 2.8, 1.8)),
         'right_alt': DisplayKey('right_alt', Rect(3.0, 4.0, 2.8, 1.8)),
         'right_gui': DisplayKey('right_gui', Rect(3.0, 6.0, 2.8, 1.8))
     }
     self._updateKeys()
Example #12
0
 def _getContentArea(self):
     """
     Based on the content size, in logical units, return, in device units,
     the rectangle encompassing the extents of the content to be drawn.
     """
     drawingArea = self._getDrawingArea()
     scale = self._getScale(drawingArea)
     contentSize = self._getContentSize() * scale
     contentArea = Rect(drawingArea.x, drawingArea.y, contentSize.width, contentSize.height)
     contentArea = contentArea.CenterIn(drawingArea)
     return contentArea
Example #13
0
    def __init_rect_list(self, ind, min_prob=0.5):
        """
        Returns list of Rect instances from output of neural network for a single image.

        Args
            bottom_height (int): height of image (bottom layer)
            bottom_width (int): width of image
            bbox_label_pred (ndarray): spatial map of predicted bounding 
                box coordinates at the top of neural network
            label_pred (ndaray): spatial map of probabilities of the 
                different labels
        
        """
        #bbox_label_pred = self.net.tops['bbox_label'].data[ind]
        #binary_pred = self.net.tops['binary_label'].data[ind]
        bottom_height = self.image_height
        bottom_width = self.image_width
        bbox_label_pred = self.net.tops['bbox_pred'].data[ind]
        binary_pred = self.net.tops['binary_softmax'].data[ind]
        label_pred = self.net.tops['label_softmax'].data[ind]

        (_, top_height, top_width) = bbox_label_pred.shape
        y_mul = bottom_height * 1. / top_height
        x_mul = bottom_width * 1. / top_width
        rect_list = []
        for y in xrange(top_height):
            for x in xrange(top_width):
                # corresponds to indices in original image
                cx_orig = x_mul * (x + 0.5)
                cy_orig = y_mul * (y + 0.5)

                # we predict a symbol here if p(no label) < x
                if binary_pred[0, y, x] < 0.5:
                    k = np.argmax(label_pred[:, y, x])
                    #if label_pred[k, y, x] < 0.2: continue

                    # apply offsets to get positions in original image
                    cx = cx_orig + bbox_label_pred[0, y, x]
                    cy = cy_orig + bbox_label_pred[1, y, x]
                    w = bbox_label_pred[2, y, x]
                    h = bbox_label_pred[3, y, x]
                    xmin = cx - w / 2.0
                    ymin = cy - h / 2.0
                    rect = Rect(xmin,
                                ymin,
                                xmin + w,
                                ymin + h,
                                label=k,
                                prob=label_pred[k, y, x])
                    rect_list.append(rect)

        return rect_list
Example #14
0
def chunkify(m):
    direction = Dir.horizontal
    start_chunk = Rect(0, 0, m.width, m.height)
    start_chunk.room = -1
    chunks = [start_chunk]
    minsize = 13
    minlength = 6
    while m.free_area < m.total_size * 0.2:
        curr = pop_largest(chunks)
        if direction == Dir.vertical and curr.width > minsize:
            start = curr.x + max(minlength, int(curr.width * 0.2))
            end = curr.x + curr.width - max(minlength, int(curr.width * 0.2))
            hallway = random.randint(start, end)
            first = Rect(curr.x, curr.y, hallway - curr.x, curr.height)
            second = Rect(hallway + 1, curr.y, curr.x + curr.width - hallway - 1, curr.height)
            new_direction = Dir.horizontal
        elif direction == Dir.horizontal and curr.height > minsize:  # horizontal
            start = curr.y + max(minlength, int(curr.height * 0.2))
            end = curr.y + curr.height - max(minlength, int(curr.height * 0.2))
            hallway = random.randint(start, end)
            first = Rect(curr.x, curr.y, curr.width, hallway - curr.y)
            second = Rect(curr.x, hallway + 1, curr.width, curr.y + curr.height - hallway - 1)
            new_direction = Dir.vertical
        else:  # chunk too small, done. just re-add the chunk
            chunks.append(curr)
            break

        mark_room(m, first, m.first_unused_room_id)
        chunks.append(first)

        mark_room(m, second, m.first_unused_room_id)
        chunks.append(second)

        mark_hallway(m, curr, hallway, direction)
        direction = new_direction

        # print_map(m)

    return chunks
Example #15
0
    def rect_list(self):
        """
        List[Rect] - instances corresponding to labelled image.
        """
        rect_list_ = []
        for ind in xrange(len(self.bbox_array)):
            rect = Rect(self.bbox_array[ind][0],  
                      self.bbox_array[ind][1], 
                      self.bbox_array[ind][2], 
                      self.bbox_array[ind][3], 
                      label = self.label_array[ind])

            rect_list_.append(rect)
        return rect_list_
Example #16
0
 def _initKeys(self):
     KeyDisplayPane._initKeys(self)
     self._displayKeys.clear()
     self._orderedKeyHandles = self._category.keyHandles
     for keyHandle in self._category.keyHandles:
         if not Model.sourcekeys.has_key(keyHandle):
             raise RuntimeError("Unknown key '%s' in category '%s'" %
                                (keyHandle, self._category.name))
         sourceKey = Model.sourcekeys[keyHandle]
         rect = Rect(0, 0, self._keySize.width, self._keySize.height)
         self._displayKeys[keyHandle] = DisplayKey(keyHandle, rect)
     self._updateKeys()
     self._selectKey(self._orderedKeyHandles[0])
     self._updateScrollbars()
Example #17
0
    def chunkify(m):
        direction = WallDirection.horizontal
        start_chunk = Rect(0, 0, m.width, m.height)
        TowerMapGenerator.mark_room(m, start_chunk, 0)
        chunks = [start_chunk]
        minsize = 13
        minlength = 6
        while TowerMapGenerator.free_area(m) < TowerMapGenerator.total_size(m) * 0.2:
            curr = TowerMapGenerator.pop_largest(chunks)
            if direction == WallDirection.vertical and curr.width > minsize:
                start = curr.x + max(minlength, int(curr.width * 0.2))
                end = curr.x + curr.width - max(minlength, int(curr.width * 0.2))
                hallway = random.randint(start, end)
                first = Rect(curr.x, curr.y, hallway - curr.x, curr.height)
                second = Rect(hallway + 1, curr.y, curr.x + curr.width - hallway - 1, curr.height)
                new_direction = WallDirection.horizontal
            elif direction == WallDirection.horizontal and curr.height > minsize:  # horizontal
                start = curr.y + max(minlength, int(curr.height * 0.2))
                end = curr.y + curr.height - max(minlength, int(curr.height * 0.2))
                hallway = random.randint(start, end)
                first = Rect(curr.x, curr.y, curr.width, hallway - curr.y)
                second = Rect(curr.x, hallway + 1, curr.width, curr.y + curr.height - hallway - 1)
                new_direction = WallDirection.vertical
            else:  # chunk too small, done. just re-add the chunk
                chunks.append(curr)
                break

            TowerMapGenerator.mark_room(m, first, TowerMapGenerator.first_unused_room_id(m))
            chunks.append(first)

            TowerMapGenerator.mark_room(m, second, TowerMapGenerator.first_unused_room_id(m))
            chunks.append(second)

            TowerMapGenerator.mark_hallway(m, curr, hallway, direction)
            direction = new_direction

        return chunks
Example #18
0
 def __init__(self):
     self.rect = Rect(0,0,70,80) #this is the *logical* rect
     self.facing = Facing.right
     self.yFacing = Facing.up
     self.velocity = [0,0]
     self.xFriction = 1
     self.yFriction = 2
     self.xAccel = 1
     self.yAccel = 1
     self.xMax = 8
     self.xMin = -8
     self.yMax = 4
     self.yMin = -4
     self.walkMask = None #level will set this
     self.triggerZones = None #level will set this
Example #19
0
    def batch_data(self, image_mean):
        """
        Prepares data for ingestion by Apollo.

        Returns:
            ndarray (trans_img): transposed image in N-C-H-W caffe blob format
            ndarray (bbox_label): target bounding boxes corresponding to image, 
                bbox_label[0]: cx (center x) offset at each position
                bbox_label[1]: cy (center y) offset at each position
                bbox_label[2]: w (width) of bounding box of object at each position
                bbox_label[3]: h (height) of bounding box of object at each position
            ndarray (conf_label): target indices corresponding to different points in image
        """
        # zero label means nothing is there
        conf_label = np.zeros((1, TOP_HEIGHT, TOP_WIDTH), dtype = np.float)
        bbox_label = np.zeros((4, TOP_HEIGHT, TOP_WIDTH), dtype = np.float)
        y_mul = IMG_HEIGHT * 1. / TOP_HEIGHT
        x_mul = IMG_WIDTH * 1. / TOP_WIDTH

        # iterate over all pixels
        for y in range(TOP_HEIGHT):
            for x in range(TOP_WIDTH):
                # current distance to closest object center at coordinate
                best_dist = np.Inf
                # find object closest to coordinate (if one exists)
                for rect in self.rect_iter():
                    # makes box smaller to prevent label ambiguity 
                    # at downsampled resolution (detections get centered)
                    rect.scale_wh(0.5, 0.5)
                    x_orig = x_mul * x
                    y_orig = y_mul * y
                    obs_rect = Rect(x_orig, y_orig, x_orig + x_mul, y_orig + y_mul)
                    if rect.intersects(obs_rect):
                        center_dist = (rect.cx - obs_rect.cx) ** 2 + (rect.cy - obs_rect.cy) ** 2
                        if center_dist < best_dist:
                            best_dist = center_dist
                            conf_label[0, y, x] = rect.label
                            bbox_label[0, y, x] = rect.cx - obs_rect.cx
                            bbox_label[1, y, x] = rect.cy - obs_rect.cy
                            bbox_label[2, y, x] = rect.w
                            bbox_label[3, y, x] = rect.h

        image = self.image.copy()
        image = image.reshape(1, IMG_HEIGHT, IMG_WIDTH)

        return (image, bbox_label, conf_label)
Example #20
0
def main():
    pygame.init()
    screen = pygame.display.set_mode(SIZE)
    clock = pygame.time.Clock()

    noto_sans = pygame.font.Font('NotoSans-Regular.ttf', 12)

    field = Field(area=Rect(x=10, y=50, w=WIDTH - 20, h=HEIGHT - 60))
    snake = Snake(
        starting_point=random_point(offset=100, area=field.client_area()))
    score = Score(font=noto_sans, position=Point(x=10, y=10))
    goal = Goal(area=generate_goal_area(snake=snake, field=field))
    controller = KeyboardController(
        snake=snake,
        start_direction=random_direction(),
        key_map=KeyMap(
            up=pygame.K_UP,
            down=pygame.K_DOWN,
            left=pygame.K_LEFT,
            right=pygame.K_RIGHT
            # up=pygame.K_w, down=pygame.K_s, left=pygame.K_a, right=pygame.K_d
        ))

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            controller.handle_event(event)

        if not running:
            break

        score.update(score=len(snake))

        screen.fill(BLACK)
        for go in [field, snake, score, goal]:
            go.draw_to(screen)
        pygame.display.flip()

        controller.update()
        running = check_collisions(snake, screen, goal, field)
        clock.tick(120)

    print(f'Game over! Your score: {len(snake)}')
    pygame.quit()
Example #21
0
 def __init__(self, pos, data=None):
     self.base_images = {}
     for n, p in self.image_paths.items():
         self.base_images[n] = pygame.image.load(p)
     self._velocity: Vec2d = Vec2d((0, 0))
     self.images: Dict[str, BodyPart] = {}
     for n, v in self.image_parts.items():
         self.images[n] = BodyPart(self.base_images[v[0]].subsurface(v[1]),
                                   v[2])
     self._data: Dict[str, Any] = None
     self._hash = None
     self._image = None
     self._rect = Rect(pos, self.size)
     self._draw_offset = None
     self.data = data or {}
     self.one_ground = False
     self.setup()
Example #22
0
    def _initKeys(self):
        self._keySpacing = wx.Size(self._kb.layout.spacing, self._kb.layout.spacing)
        self._displayKeys = {}
        selectedKey = None
        rows = self._kb.layout.rows
        for row in rows:
            if row is None:
                continue
            for keydef in row.keydefs:
                if keydef.isNullKey:
                    continue
                keyRect = Rect(keydef.origin.x, keydef.origin.y, keydef.size.width, keydef.size.height)
                location = keydef.location
                keyHandle = None
                if self._keymap and self._keymap.keys.has_key(location):
                    keyHandle = self._keymap.keys[location].keyHandle
                self._displayKeys[location] = DestDisplayKey(location, keyHandle, keyRect)
                if selectedKey == None:
                    selectedKey = location

        self._updateKeys()
        self._selectKey(selectedKey)
Example #23
0
 def _render_rect(self):
     self._rect = Rect(
         tuple(self.pos),
         (self._image.get_size()[0] / 16, self._image.get_size()[1] / 16))
Example #24
0
 def get_rect(self):
     return Rect(self.x, self.y, settings.goalie_width,
                 settings.goalie_height)
Example #25
0
def gen_sweep_plane(src_Hs, src_frames):

    max_poly = None  # the bound of the blended image
    bldIm = None  # the blended plane image
    cost_info = None  # An array structure to collect pixel colors of
    # blended frames
    nframes = len(src_frames)
    o = np.array([[0], [0], [1]])  # origin = zero

    # Get max polygon
    for k in range(nframes):
        cpoly = Rect(Point(0, 0),
                     Point(src_frames[k].shape[1],
                           src_frames[k].shape[0])).get_trans_regpoly(
                               src_Hs[k], 10)
        if (k == 0):
            max_poly = cpoly
        else:
            max_poly = max_poly | cpoly
        #end if
    #end for

    (xmin, xmax, ymin, ymax) = max_poly.boundingBox(0)
    max_rec = Rect(Point(xmin, ymin), Point(xmax, ymax))
    #print "Max: " , max_rec, "W: ", max_rec.width(), " H: ", max_rec.height()

    #alocate costs and count matrixes
    cost_info = np.zeros(
        [int(max_rec.height()),
         int(max_rec.width()), nframes, 3],
        dtype=np.int)
    counts = np.zeros(
        [int(max_rec.height()), int(max_rec.width())], dtype=np.int)

    bldIm = cv.CreateMat(int(np.round(max_rec.height())),
                         int(np.round(max_rec.width())), cv.CV_32FC3)
    cv.Zero(bldIm)

    for k in range(nframes):
        cur_H = src_Hs[k]
        cur_o = np.dot(cur_H, o)
        #  translate the warped frame to origin from topleft corner
        disp = np.array([[1, 0, (0 - cur_o[0, 0]) / cur_o[2, 0]],
                         [0, 1, (0 - cur_o[1, 0]) / cur_o[2, 0]], [0, 0, 1]])
        o_H = np.dot(disp, cur_H)
        tpoly = Rect(Point(0, 0),
                     Point(src_frames[k].shape[1],
                           src_frames[k].shape[0])).get_trans_poly(cur_H)
        cpoly = Rect(Point(0, 0),
                     Point(src_frames[k].shape[1],
                           src_frames[k].shape[0])).get_trans_regpoly(
                               cur_H, 10)
        (xmin, xmax, ymin, ymax) = cpoly.boundingBox(0)
        frec = Rect(Point(xmin, ymin), Point(xmax, ymax))

        mask = gen_mask(frec, tpoly)

        #print "Rec: ", frec, "W: ", frec.width(), " H: ", frec.height()

        if k == 0:
            fwarp = cv2.warpPerspective(
                src_frames[k], o_H, (int(frec.width()), int(frec.height())))
            # get blended image
            blend_views(bldIm, fwarp, mask, frec, max_rec)
            # determine costs
            collect_costs_info(cost_info, counts, fwarp, mask, frec, max_rec,
                               k)
        else:
            fwarp = cv2.warpPerspective(
                src_frames[k], o_H, (int(frec.width()), int(frec.height())))

            # get blended image
            blend_views(bldIm, fwarp, mask, frec, max_rec)
            # determine costs
            collect_costs_info(cost_info, counts, fwarp, mask, frec, max_rec,
                               k)
        #end if
    #end for

    bldIm = np.asarray(bldIm)

    # Scale blended image to 8U
    bldIm8U = scaleTo8U(bldIm, counts)

    ## Measure Cost
    costs = None
    costs = calculate_costs(cost_info, counts)

    ##return blended image and costs
    return (bldIm8U, costs, max_rec)
Example #26
0
 def client_area(self) -> Rect:
     return Rect(self._area.x + 1, self._area.y + 1, self._area.w - 2, self._area.h - 2)
Example #27
0
    def _drawKeys(self, dc):
        blackPen = wx.Pen('black')
        whiteBrush = wx.Brush('white')
        font = wx.Font(10, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL,
                       wx.FONTWEIGHT_NORMAL, False, 'Arial Rounded MT Bold')
        dc.SetFont(font)
        scale = 1

        if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
            displayRect = self._getDisplayRect()
            print "displayRect: %s" % displayRect
            #           dc.SetMapMode(wx.MM_TEXT)
            dc.SetMapMode(wx.MM_METRIC)
            contentRect = Rect(dc.DeviceToLogicalX(displayRect.x),
                               dc.DeviceToLogicalY(displayRect.y),
                               dc.DeviceToLogicalXRel(displayRect.width),
                               dc.DeviceToLogicalYRel(displayRect.height))
            print "contentRect: %s" % contentRect
            scale = self._getScale(contentRect)
            #           dc.SetPen(wx.Pen('black', 1*scale))
            dc.SetMapMode(wx.MM_TEXT)

        for displayKey in self._displayKeys.values():
            #           if self._isKeySelected(displayKey.handle):
            #               if self.FindFocus() == self:
            #                   # TODO: Generalize this magic number from system
            #                   #       settings.  Currently is Mac selection blue.
            #                   dc.SetPen(wx.Pen('#3e75d6', 2))
            #               else:
            #                   dc.SetPen(wx.Pen('dark grey', 2))
            #               dc.SetBrush(wx.Brush('light grey'))
            #           else:
            #               dc.SetPen(blackPen)
            #               dc.SetBrush(whiteBrush)
            label_rect = deepcopy(displayKey.scaled)
            key_rect = deepcopy(displayKey.scaled)

            # make any necessary adjustments
            if self._displayMode == DISPLAY_MODE_DYNAMIC_RESIZE:
                key_rect = key_rect * scale

            # draw key rectangle
            dc.DrawRoundedRectangleRect(key_rect.Get(), -.075)

            # draw label
            if False:
                label_rect.Deflate(5, 2)
                label = self._getLabel(displayKey)
                if label:
                    dc.SetUserScale(scale, scale)
                    (width, height) = dc.GetTextExtent(label)
                    if width > label_rect.width:
                        # TODO: better wrapping
                        #                   extents = dc.GetPartialTextExtents(label)
                        label = fill(label, 5)
                    dc.DrawLabel(label, label_rect.Get(),
                                 wx.ALIGN_LEFT | wx.ALIGN_BOTTOM)
                    if self._isKeySelected(displayKey.handle):
                        dc.SetPen(blackPen)
                        dc.SetBrush(whiteBrush)
                    dc.SetUserScale(1, 1)
Example #28
0
 def helper(name):
     room = Rect(2, 2, 10, 10)
     return get_monster(0, 0, game_map, room, name, [])[0]
Example #29
0
  def get_stick_head(self):
    stick_ball_offset = pygame.Vector2(settings.ball_radius, 0)
    offset_rotated = stick_ball_offset.rotate(-self.angle)

    ball_pos = self.get_ball_pos()
    return Rect(ball_pos[0] + offset_rotated[0], ball_pos[1] + offset_rotated[1], settings.stick_head_width, settings.stick_head_height, self.angle)
Example #30
0
 def get_body_rect(self):
   dy = settings.player_body_adjustment if self.default_angle == 0 else -settings.player_body_adjustment
   return Rect(self.pos[0], self.pos[1] + dy, settings.player_body_width, settings.player_body_height, self.angle)