def __init__(self, pos=Point2D(0, 0), angle=0, velocity=0, maxVelocity=5, bodyWidth=30, bodyLength=60, headlightsOn=False, headlightPower=100): self.pos = pos #type: Point self.velocity = velocity #type: float self.maxVelocity = maxVelocity self.angle = angle #type: float self.headlightsOn = headlightsOn #type: bool self.headlightPower = headlightPower #type: int self.height = bodyWidth #type: int self.width = bodyLength #type: int self.__body = Rectangle(bodyLength, bodyWidth, pos, color=(1, 0, 0)) self.__headlight1 = Sector(Point2D(pos.x, pos.y), angle, inner=40, color=(1, 1, 0.5)) self.__headlight1.hide() self.__headlight2 = Sector(Point2D(pos.x, pos.y), angle, inner=40, color=(1, 1, 0.5)) self.__headlight2.hide()
def add_obstacles(self, num_obs, lgth, wdth, ang=None, max_iter=1e3): """Add num_obs obstacles of certain length and width, within the limits of the current environment. If ang is not specified, will pick a random rectangle angle. """ max_id = max(self.rectangles) added = 0 it = 0 while added < num_obs: it += 1 if it > max_iter: print("Could fit {} such rectangles in the environment.".format(added)) break x, y = GeoTools.sample_in_range(self.x_range) if ang is None: rectangle = Rectangle( max_id + added + 1, x, y, lgth, wdth, np.random.uniform(0, 360) ) else: rectangle = Rectangle(max_id + added + 1, x, y, lgth, wdth, ang) try: assert rectangle.as_poly <= self.as_rectangle().as_poly self.add_rectangle(rectangle, verbose=False) except AssertionError: continue added += 1
def test_rectangle_area_again(): """ Test that we can calculate the area of a rectangle """ rectangle = Rectangle(width=8, height=8) area = rectangle.area() assert area == 64
def fill_zero(x: np.array, rect: Rectangle): assert isinstance(rect, (Shape, list, tuple, set)) if isinstance(rect, Shape): upper, lower, left, right = rect.get_upper(), rect.get_lower( ), rect.get_left(), rect.get_right() if len(x.shape) == 3: x[upper:lower, left:right, :] = 0 else: x[upper:lower, left:right] = 0 else: for r in rect: fill_zero(x, r)
def main(): shapes: list = [ Circle(5), Rectangle(3, 3), Rectangle(4, 4), Triangle(3, 4), ] for shape in shapes: logging.debug( "type: {0}, circumference = {1:.2f}, area = {2:.2f}".format( type(shape), shape.circumference(), shape.area()))
def _process_frame(self, frame, frame_index, pixel_diff_threshold, pixel_count_threshold, beta): # HACK naive implementation of background subtraction foreground = get_foreground(frame, self.background, pixel_diff_threshold) display_foreground = get_foreground(frame, self.display_background, pixel_diff_threshold) # update background with running average self.display_background = self.display_background * beta + frame * ( 1. - beta) # get the two opposite vertices of real bounding box xx, yy = np.nonzero(foreground) upper, lower, left, right = find_bounding_box( xx, yy, pix_count_thres=pixel_count_threshold) vertices = ((left, upper), (right, lower)) # check whether the foreground is located in mute areas for rect in self.mute_rects: fill_zero(foreground, rect) # get the basic stats of foreground with muted areas (points_count, value, area, ratio, obliqueness) value = np.sum(foreground) xx, yy = np.nonzero(foreground) u_l_l_r = find_bounding_box(xx, yy, pix_count_thres=pixel_count_threshold ) # returns upper, lower, left, right bounding_rectangle = Rectangle(*u_l_l_r) area = bounding_rectangle.get_area() ratio = bounding_rectangle.get_ratio() try: coords = coords_within_boundary(xx, yy, *u_l_l_r, zero_mean=True) self.pca_solver.fit(coords) obliqueness = self.pca_solver.explained_variance_ratio_ except: obliqueness = 0.5 # check whether the shape of foreground should trigger the alarm self.parameter_list.append((len(xx), value, area, ratio, obliqueness)) if self.threshold.check(len(xx), value, area, ratio, obliqueness): cv2.rectangle(frame, *vertices, color=(0, 0, 255)) cv2.putText(frame, "WARNING", (left, upper), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255)) self._trigger_alarm(frame_index, frame) else: cv2.rectangle(frame, *vertices, color=(255, 0, 0)) cv2.putText(frame, "Object", (left, upper), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 0, 0)) return frame, display_foreground
def generate_bars(self, sizes): """ creates the bars if they aren't already, else updates them :param sizes: sizes of bars :return: """ bar_width = self.surface.get_rect().size[0] / self.size for i, y in enumerate(sizes): try: bar = self.bars[y] bar.position = Vector2D.custom(self.surface, i * bar_width, y - 1, inverty=True) continue except KeyError: bar = Rectangle(Vector2D.custom(self.surface, i * bar_width, y - 1, inverty=True), Vector2D(bar_width, y), color=Color.lerp(y / self.max, colors.RED, colors.GREEN, colors.BLUE) if self.color is None else self.color) self.bars[y] = bar
def __init__(self, video_path: str, rectangles: (tuple, list), threshold, bg=None): # store input video path self.video_path = video_path # self.image_path = video_path.split('/')[-1] # force_mkdir(os.path.join('.',self.image_path)) self.threshold = threshold # type: BaseThreshold self.alarm_list = [] self.pca_solver = PCA(n_components=1) assert os.path.isfile(self.video_path), "No such file: %s" % video_path cap = cv2.VideoCapture(self.video_path) # obtain background image ret, background = cap.read() cap.release() self.background = image2array( bg) if bg else background # type: np.array self.display_background = np.copy(self.background) self.pixel_count = self.background.shape[0] * self.background.shape[1] # define a list of rectangular areas, where alarms are muted upper, lower, left, right = 0, self.background.shape[ 0], 0, self.background.shape[1] background_rectangle = Rectangle(upper, lower, left, right) self.mute_rects = rectangles for rectangle in rectangles: # type: Rectangle assert rectangle.is_contained_in( background_rectangle), 'rectangle not contained in background' print("all input rectangles for mute area are legal") self.parameter_list = list()
def __init__(self, node, draw_pos, scale, draw_surface): '''Initializes the visual node. The node argument is the a_star node that we will be polling property information from.''' self.node = node #A_Star node self.shape = Rectangle(draw_pos, (255, 255, 255), scale, draw_surface, 0) #Visual drawn to the screen self.is_hoovered = False #True if the mouse is hoovering over the node self.is_start = False #True if the node is the starting node of the algorithm self.is_goal = False #True if the node is the goal node of the algorithm self.is_path = False #True if the node is part of the algorithm path self.is_open = False #True if the node is in the open list self.is_closed = False #True if the node is in the closed list self.show_scores = False #Toggles the node scores to be drawn to the screen self.border = Rectangle( draw_pos, (255, 255, 255), scale, draw_surface, 4) #Highlight border for when the mouse is over the node
def setUp(self): self.init_kwargs = {} self.init_kwargs["xCoord"] = 50 self.init_kwargs["yCoord"] = 50 measurements = {"width": 50, "length": 50} self.init_kwargs["measurements"] = measurements self.area = measurements["width"] * measurements["length"] self.shape = Rectangle(**self.init_kwargs)
def as_rectangle(self): """Return the environment as a Rectangle object.""" return Rectangle( -1, self.x_range[0][0], self.x_range[1][0], self.x_range[0][1] - self.x_range[0][0], self.x_range[1][1] - self.x_range[1][0], 0, )
class RectangleTestCase(TestCase): def setUp(self): self.rectangle = Rectangle(width=7, height=8) def test_rectangle_area(self): """ Test that we can calculate the area of a rectangle """ area = self.rectangle.area() self.assertEqual(area, 56) @mock.patch('shapes.tweet') def test_rectangle_broadcast(self, mock_tweet): """ Tests that we call tweet with a formatted message """ self.rectangle.broadcast() mock_tweet.assert_called_with('My rectangle is 7 by 8')
def add_dicing_marks(self): """ Create dicing marks """ width=100./2 r=self.wafer_r rng=np.floor(self.wafer_r/self.block_size).astype(int) dmarks=Cell('DIC_MRKS') for l in self.cell_layers: for x in np.arange(-rng[0], rng[0]+1)*self.block_size[0]: y=np.sqrt(r**2-x**2) vm=Rectangle((x-width, y), (x+width, -y), layer=l) dmarks.add(vm) for y in np.arange(-rng[1], rng[1]+1)*self.block_size[1]: x=np.sqrt(r**2-y**2) hm=Rectangle((x, y-width), (-x, y+width), layer=l) dmarks.add(hm) self.add(dmarks)
def test_rectangle(self): rectangle = Rectangle(10, 20, (0, 0, 0), 'wood') self.assertEqual('Rectangle -> Comp. 10 lag. 20 Color: (0, 0, 0)'+\ ' Material : wood Max_Temp: 20', str(rectangle)) self.assertEqual(200, rectangle.get_area()) rectangle2 = Rectangle(10, 30, (0, 0, 0), 'wood') self.assertEqual(300, rectangle2.get_area()) self.assertNotEqual(rectangle2, rectangle) rectangle3 = Rectangle(10, 20, (0, 0, 0), 'wood') self.assertEqual(rectangle3, rectangle)
def draw(self): '''Draws all objects that are in the gameobjects list to the screen''' self.screen.fill((0, 0, 0)) yaxis = Line(WHITE, 5) yaxis.draw(self.screen, [ Vector2(0, -(SCREEN_HEIGHT / 2)), Vector2(0, (SCREEN_HEIGHT / 2)) ]) xaxis = Line(WHITE, 5) xaxis.draw( self.screen, [Vector2(-(SCREEN_WIDTH / 2), 0), Vector2(SCREEN_WIDTH / 2, 0)]) mxpos, mypos = pygame.mouse.get_pos() mouse = Rectangle(WHITE, Vector2(25, 25)) mpos = worldtoscreen(Vector2(mxpos, mypos)) mpos = mpos.scale(-1) mouse.draw(self.screen, mpos) for gameobject in self.gameobjects: gameobject.draw(self.screen)
def main() -> None: shape1 = Rectangle(100, 200) shape2 = Square(100) shape3 = Circle(100) print('Shape1 surface: {}'.format(shape1.surface)) print('Shape1 perimiter: {}'.format(shape1.perimeter)) print('Shape2 surface: {}'.format(shape2.surface)) print('Shape2 perimiter: {}'.format(shape2.perimeter)) print('Shape3 surface: {}'.format(shape3.surface)) print('Shape3 perimiter: {}'.format(shape3.perimeter))
def draw(self, shape): # Method drawing a shape on the canvas. self.__canvas.delete(self.__tmp_rendered) rendered_shape = None if shape['type'] == 'rectangle' and shape['mode'] == 'normal': rendered_shape = Rectangle(shape) elif shape['type'] == 'rectangle' and shape['mode'] == 'straight': rendered_shape = Square(shape) elif shape['type'] == 'oval' and shape['mode'] == 'normal': rendered_shape = Oval(shape) elif shape['type'] == 'oval' and shape['mode'] == 'straight': rendered_shape = Circle(shape) elif shape['type'] == 'line' and shape['mode'] == 'normal': rendered_shape = Line(shape) elif shape['type'] == 'line' and shape['mode'] == 'straight': rendered_shape = Diagonal(shape) shape_id = rendered_shape.draw_on(self.__canvas) return shape_id
def test_rectangle(self): rectangle = Rectangle(10, 20, (0, 0, 0), 'wood') self.assertEqual( 'Rectangle -> Comp. 10 Larg. 20 Color: (0, 0, 0) Material: wood max_temperature: 20', str(rectangle)) self.assertEqual(200, rectangle.get_area()) rectangle2 = Rectangle(10, 30 (0, 0, 0), 'wood') self.assertEqual(300, rectangle.get_area()) self.assertNoEqual(rectangle2, rectangle) rectangle3 = Rectangle(10, 20, (0, 0, 0), 'wood') self.assertEqual(rectangle3, rectangle)
def get_ground_truth_from_xml(filename): tree = ET.parse(filename) root = tree.getroot() rect_lb = [] for bb in root.iter("bndbox"): for child in bb: if child.tag == "xmin": xmin = int(child.text) elif child.tag == "ymin": ymin =int(child.text) elif child.tag == "xmax": xmax = int(child.text) elif child.tag == "ymax": ymax = int(child.text) rect_lb.append(Rectangle(xmin, ymin, xmax, ymax)) return rect_lb
def toDXF(self, filename, labels=False, mode="dxf"): from dxfwrite import DXFEngine as dxf if mode == "dxf": from shapes import Rectangle self.append(Rectangle(12 * 25.4, 12 * 25.4, edgetype=Reg()), "outline") dwg = dxf.drawing(filename) for e in self.edges.items(): e[1].toDrawing(dwg, e[0] if labels else "", mode=mode, engine=dxf) dwg.save() if mode == "dxf": self.edges.pop("outline.e0") self.edges.pop("outline.e1") self.edges.pop("outline.e2") self.edges.pop("outline.e3")
def draw(self): """ Draw pillar """ self.col1 = Rectangle(self.x, self.y, self.height, self.thickness) self.col1.draw() x, y = self.col1.top_left self.beam1 = Rectangle(x, y, self.thickness, self.width) self.beam1.draw() x, y = self.col1.bottom_left x = x + self.width - self.thickness self.col2 = Rectangle(x, y, self.height, self.thickness) self.col2.draw()
def createShapes(): shapes = [] for i in range(randint(5, 10)): v = randint(1, 4) x, y = randint(0, 700), randint(0, 700) length = randint(10, 100) width = randint(10, 100) colorChoice = COLORS[randint(0, len(COLORS) - 1)] if v == 1: pass shapes.append(Triangle((x, y), colorChoice, length)) if v == 2: shapes.append(Rectangle((x, y), colorChoice, length, width)) if v == 3: shapes.append(Square((x, y), colorChoice, length)) if v == 4: shapes.append(Circle((x, y), colorChoice, length)) return shapes
def __init__(self, *args, **kargs): """Create an application instance. """ super().__init__(Application.WIDTH, Application.HEIGHT, *args, **kargs) self.game = None self.rects = [[ Rectangle(Application.BORDER + Application.RECT_LEN * r, Application.BORDER + Application.RECT_LEN * c, Application.RECT_LEN - 2 * Application.BORDER, Application.RECT_LEN - 2 * Application.BORDER) for c in range(Minesweeper.COL_SIZE) ] for r in range(Minesweeper.ROW_SIZE)] self.label = pyglet.text.Label( "X", font_size=Application.TOP_FONT_SIZE, x=Application.WIDTH // 2 + Application.TOP_H_OFFSET, y=Application.HEIGHT + Application.TOP_V_OFFSET, font_name='Impact', anchor_x='center', anchor_y='center', color=AlphaColors.RED)
def setUp(self): self.triangle_init_kwargs = {} self.rectangle_init_kwargs = {} self.triangle_init_kwargs["xCoord"] = 50 self.triangle_init_kwargs["yCoord"] = 50 self.rectangle_init_kwargs["xCoord"] = 50 self.rectangle_init_kwargs["yCoord"] = 50 triangle_measurements = {"side": 50} rectangle_measurements = {"width": 50, "length": 50} self.triangle_init_kwargs["measurements"] = triangle_measurements self.rectangle_init_kwargs["measurements"] = rectangle_measurements self.side = 50 self.length = 50 self.width = 50 self.tag = "test" self.area = (4.33 * triangle_measurements["side"]**2) + ( rectangle_measurements["width"] * rectangle_measurements["length"]) triangle = Triangle(**self.triangle_init_kwargs) rectangle = Rectangle(**self.rectangle_init_kwargs) self.components = [triangle, rectangle] self.shape = CompositeShape(tag=self.tag, components=self.components)
def intersection(parm1, parm2): rect1, rect2 = RectangleCollisionDetectorNoRotation._get_rects( [parm1, parm2]) right_most_left_side = max(rect1.left, rect2.left) left_most_right_side = min(rect1.right, rect2.right) bottom_most_top_side = max(rect1.top, rect2.top) top_most_bottom_side = min(rect1.bottom, rect2.bottom) # If the left most ride side is left of the right most left side, no intersection if left_most_right_side <= right_most_left_side: return None # If the bottom most top side is below the top most bottom side, no intersection elif bottom_most_top_side >= top_most_bottom_side: return None else: return Rectangle(x=right_most_left_side, y=bottom_most_top_side, width=left_most_right_side - right_most_left_side, height=top_most_bottom_side - bottom_most_top_side)
def main(reader, reader_args, output_type, zoom_level): """ This is the main function to run the script and finding number of lands Args: reader (str): Name of the function to read and extract data reader_args (list): List of arguments to be passed to reader function output_type (str): Name of the function to visualize the output zoom_level (int): The cartesian coordinates will be multiplied by zoom_level for better visualization """ # get appropriate function to read cartesian coordinates read_func = Function.get(reader) # read data points_list = read_func(*reader_args) # create list of Rectangle objects from given cartesian coordinates rectangle_list = [] for points in points_list: rectangle = Rectangle(points) rectangle_list.append(rectangle) # link each rectangle to its immediate outer neighbour and inner neighbour(s). # Also tag each rectangle as a land or sea based on immediate neighbour tag ll = LinkedList(rectangle_list) result, no_of_lands = ll.bfs() # output number of rectangles tagged as land message = "Found {} land(s)\nout of {} rectangles".format( no_of_lands, len(rectangle_list)) print(message) # output how rectangles are linked with each other print(str(ll)) # if visual display option is activated draw the result if output_type: output_func = Function.get(output_type) output_func(result, message, zoom_level).draw()
from shapes import Paper, Triangle, Rectangle, Oval paper = Paper() rect1 = Rectangle() rect1.set_width(200) rect1.set_height(100) rect1.set_color("blue") rect1.draw() rect2 = Rectangle() rect2.set_x(50) rect2.set_y(30) rect2.set_width(200) rect2.set_height(100) rect2.set_color("orange") rect2.draw() paper.display()
"""Using the 'shapes' module to create shapes and control their attributes""" from shapes import Triangle, Rectangle, Oval # create a rectangle: rect_1 = Rectangle(color=None) # set the attributes: #rect_1.set_width(200) #rect_1.set_height(100) #rect_1.set_color('blue') # draw the rectangle: rect_1.draw() # create an oval: oval_1 = Oval() oval_1.set_width(100) oval_1.set_height(50) oval_1.set_color('yellow') oval_1.set_x(100) oval_1.set_y(200) oval_1.draw() rect_2 = Rectangle() #rect_2.set_width(100) #rect_2.set_height(150) #rect_2.set_color('yellow') #rect_2.set_x(100) #rect_2.set_y(75)
#!/usr/bin/python3 from shapes import Shape from shapes import Rectangle s1 = Shape(4,8) print(s1) r1 = Rectangle(5,10,6,8) print(r1)
from tkinter import Tk, Label, Button from shapes import Triangle, Rectangle, Oval class MyGUI: def __init__(self, master): self.master = master master.title("A simple GUI") self.label = Label(master, text="This is the Root Window") self.label.pack() self.close_button = Button(master, text="Close", command=master.quit) self.close_button.pack() rectangle1 = Rectangle() rectangle1.set_width(200) rectangle1.set_height(100) rectangle1.set_color("blue") rectangle1.set_x(50) rectangle1.set_y(250) triangle1 = Triangle() # triangle1.randomise() triangle1.set_color("red") triangle1.x=150 triangle1.y=150 triangle1.x2=150 triangle1.y2=200 triangle1.x3=200 triangle1.y3=150
def setUp(self): self.rectangle = Rectangle(width=7, height=8)