def init(self, position, label, function): self.function = function self.position = position self.background = Rectangle(self.game, position, [48,16], [32,32,32]) pygame.font.init() self.font = pygame.font.Font('assets/fonts/Munro.ttf', 14) self.textSurface = self.font.render(label, False, (255, 255, 255))
class TestRectangle(TestCase): def setUp(self): self.rect = Rectangle(Point(3,4), 6, 5) def test_grow(self): self.rect.grow(1, 3) self.assertEqual(Rectangle(Point(3,4), 7, 8), self.rect) def test_move(self): self.rect.move(2, -3) self.assertEqual(Rectangle(Point(5, 1), 6, 5), self.rect) def test_area(self): self.assertEqual(30, self.rect.area()) def test_perimeter(self): self.assertEqual(22, self.rect.perimeter()) def test_flip(self): self.rect.flip() self.assertEqual(Rectangle(Point(3, 4), 5, 6), self.rect) def test_contains(self): r = Rectangle(Point(0, 0), 10, 5) self.assertTrue(r.contains(Point(0, 0))) self.assertTrue(r.contains(Point(3, 3))) self.assertFalse(r.contains(Point(3, 7))) self.assertTrue(r.contains(Point(3, 5))) self.assertTrue(r.contains(Point(3, 4.99999))) self.assertFalse(r.contains(Point(-3, -3))) def test_intersect(self): self.assertTrue(self.rect.intersect(Rectangle(Point(4,5), 1, 2))) self.assertTrue(self.rect.intersect(Rectangle(Point(1,2), 7, 5))) self.assertFalse(self.rect.intersect(Rectangle(Point(1,2), 1, 1)))
def __init__(self) -> None: self.game = Game() messages.on_log += self.on_log blt.open() self.root = DisplayElement.DisplayDict(vec(0, 0)) half_width = blt.state(blt.TK_WIDTH) // 2 half_height = blt.state(blt.TK_HEIGHT) // 2 half_window = vec(half_width, blt.state(blt.TK_HEIGHT)) quarter_window = vec(half_width, half_height) event_log = DisplayElement.PrintArgs( text='', xy=vec(0, 0), bbox=half_window, align_v=DisplayElement.TextAlignmentV.Bottom) self.root.elements['events'] = DisplayElement.Clickable( event_log, Rectangle(vec(0, 0), half_window)) hta_origin = vec(half_width, 0) hta_display = DisplayElement.DisplayList(hta_origin) self.root.elements[self.game.hta] = DisplayElement.Clickable( hta_display, Rectangle(hta_origin, quarter_window)) self.on_tableau_altered(self.game.hta) htb_origin = quarter_window htb_display = DisplayElement.DisplayList(htb_origin) self.root.elements[self.game.htb] = DisplayElement.Clickable( htb_display, Rectangle(htb_origin, quarter_window)) self.on_tableau_altered(self.game.htb)
class Button(): def __init__(self, game, position, label, function): self.game = game self.init(position, label, function) def init(self, position, label, function): self.function = function self.position = position self.background = Rectangle(self.game, position, [48,16], [32,32,32]) pygame.font.init() self.font = pygame.font.Font('assets/fonts/Munro.ttf', 14) self.textSurface = self.font.render(label, False, (255, 255, 255)) def update(self, deltaTime, events): for event in events: if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: pos = self.game.cursor.get_pos() if self.background.rect.collidepoint(pos): self.function() def draw(self, screen): self.background.draw(screen) screen.blit(self.textSurface, (self.position[0] + 2, self.position[1] + 1)) def destroy(self): pass
def load_from_metadata(self, filename): #loads this image from a metadata file file = open(filename, 'r') data = file.read() file.close() data = data.replace("false", "False") data = data.replace("true", "True") data = data.replace("null", "0") f = eval(str(data)) top = f["boundBox"]["top"] bottom = f["boundBox"]["bottom"] left = f["boundBox"]["left"] right = f["boundBox"]["right"] cx = (left + right) / 2 cy = (top + bottom) / 2 self.imagePath = f["imagePath"]["path"] if not os.path.isfile(self.imagePath): alt_path = filename.replace("_metadata.txt", ".tif") if not os.path.isfile(alt_path): raise IOError( "Metadata points to non-existent file: {}".format( self.imagePath)) self.imagePath = alt_path self.format = f["imagePath"]["format"] self.boundBox = Rectangle(left, right, top, bottom)
def get_acceptable_rectangles(self, width, height, index): points = [] # сюда будем складывать все точки, куда можно поставить следующий прямоугольник raycast_points = [] points.append(self.rectangles[0].b) for rect in self.rectangles: points += rect.points() for edge in rect.edges(): found, nearest_point, distance, horizontal, i = \ Rectangle.get_nearest_rayast_point(edge, self.rectangles) if found: raycast_points.append((nearest_point, distance, horizontal)) all_rectangles = [] for p in points: all_rectangles += Rectangle.create_rectangles_from_point(p, width, height, index=index) for p in raycast_points: if p[1] > 0: if p[2]: all_rectangles += Rectangle.create_rectangles_from_point(p, width, height, p[1], 0, index=index) else: all_rectangles += Rectangle.create_rectangles_from_point(p, width, height, 0, p[1], index=index) acceptable_rectangles = [] for r in all_rectangles: accept = True for rectangle in self.rectangles: if Rectangle.check_cross(r, rectangle): accept = False if accept: acceptable_rectangles.append(r) return acceptable_rectangles
def cardinal_system_direction(a: Rectangle, b: Rectangle) -> Direction: corners = b.get_corners() vip = a.get_corners() vip = vip[0] right = 0 left = 0 down = 0 up = 0 for corner in corners: if vip[0] <= corner[0]: right += 1 if vip[0] >= corner[0]: left += 1 if vip[1] <= corner[1]: down += 1 if vip[1] >= corner[1]: up += 1 if right == 4: return Direction(1, 0) elif left == 4: return Direction(-1, 0) elif down == 4: return Direction(0, 1) elif up == 4: return Direction(0, -1) return get_weighted_random_move(a.get_center(), a.get_direction())
class GraphicApp: def __init__(self): self.rect = Rectangle(x=1, y=1, side=1) def draw(self): self.rect.draw()
def main(): radius = int(input()) width = int(input()) height = int(input()) color1 = input() filled1 = input() color2 = input() filled2 = input() circle = Circle(radius) circle.setColor(color1) circle.setFilled(filled1) print("Circle:") print("Radius is", circle.getRadius()) print("Diameter is", circle.getDiameter()) print("Area is", circle.getArea()) print("Perimeter is", circle.getPerimeter()) print(circle) print() rectangle = Rectangle(width, height) rectangle.setColor(color2) rectangle.setFilled(filled2) print("Rectangle:") print("Width is", rectangle.getWidth()) print("Height is", rectangle.getHeight()) print("Area is", rectangle.getArea()) print("Perimeter is", rectangle.getPerimeter()) print(rectangle)
def test_distance(self): """Basic test ensuring that the distance of a point from a rectangle is calculated correctly""" r1 = Rectangle(0, 2, 0, 2) point1 = (3, 1) point2 = (3, 3) self.assertEqual(1.0, r1.distance(point1)) self.assertEqual(math.sqrt(2), r1.distance(point2))
def main(): print( "################### Test #1: Testing Rectangle Class ####################" ) r = Rectangle(10, 10, 10, 10) assert ((r.x, r.y, r.height, r.width) == (10, 10, 10, 10)) r = Rectangle(-1, 1, 1, 1) assert ((r.x, r.y, r.height, r.width) == (0, 1, 1, 1)) r = Rectangle(1, -1, 1, 1) assert ((r.x, r.y, r.height, r.width) == (1, 0, 1, 1)) r = Rectangle(1, 1, -1, 1) assert ((r.x, r.y, r.height, r.width) == (1, 1, 0, 1)) r = Rectangle(1, 1, 1, -1) assert ((r.x, r.y, r.height, r.width) == (1, 1, 1, 0)) print(r) print("Test Complete!") print( "################### Test #2: Test Surface Class ####################" ) s = Surface("myimage.png", 10, 10, 10, 10) assert ((s.rect.x, s.rect.y, s.rect.height, s.rect.width) == (10, 10, 10, 10)) assert ((s.getRect().x, s.getRect().y, s.getRect().height, s.getRect().width) == (10, 10, 10, 10)) assert (s.image == "myimage.png") print("Test Complete!")
def setup(self): arcade.schedule(self.update, 1 / 30) (_w, _h) = arcade.get_window().get_size() w = int(_w / Const.BODY_SIZE) * Const.BODY_SIZE h = int(_h / Const.BODY_SIZE) * Const.BODY_SIZE Const.RIGHT = _w Const.TOP = Const.GAME_HEIGHT = h Const.SIDE_BAR = _w - w + Const.SIDE_BAR Const.GAME_WIDTH = _w - Const.SIDE_BAR Const.GRID_NR_W = int(Const.GAME_WIDTH / Const.BODY_SIZE) Const.GRID_NR_H = int(h / Const.BODY_SIZE) play_button = SmallButton('Menu', Const.RIGHT - Const.SIDE_BAR / 2, 200, 15, self.play_method) quit_button = SmallButton('Quit', Const.RIGHT - Const.SIDE_BAR / 2, 165, 15, self.quit_method) self.side_bar = Rectangle(_w - Const.SIDE_BAR, 0, Const.SIDE_BAR, Const.TOP, arcade.color.DARK_GRAY) self.button_list.append(play_button) self.button_list.append(quit_button) self.spawn_food() self.menu.setup() self.ghost_walk_indicator = GhostWalk.GhostWalkIndicator()
def OverlapTextBBox(self, ipTextComp, ip_list): merge = Merger() ((SX, SY, EX, EY), ipop, ipprob, iptextID) = ipTextComp final_list = ip_list.copy() for ((startX, startY, endX, endY), op, prob, textID) in ip_list: if merge._is_rectangles_overlapped( Rectangle.from_2_pos(startX, startY, endX, endY), Rectangle.from_2_pos(SX, SY, EX, EY)): rec = merge._merge_2_rectangles( Rectangle.from_2_pos(startX, startY, endX, endY), Rectangle.from_2_pos(startX, startY, endX, endY)) mergeOp = " ".join(ipop.split() + list(set(op.split()) - set(ipop.split()))) mergeProb = (ipprob + prob) / 2 mergeID = textID final_list.remove( ((startX, startY, endX, endY), op, prob, textID)) final_list.append(((rec.x1, rec.y1, rec.x2, rec.y2), mergeOp, mergeProb, mergeID)) return True, final_list return False, None
def __init__(self, xDim, yDim, n_rockets, lifespan): # init game self.gameSize = (xDim, yDim) self.lifespan = lifespan self.generation = 0 pygame.init() self.font = pygame.font.Font(None, 30) self.screen = pygame.display.set_mode(self.gameSize, 0, 32) self.screen.fill((0, 0, 0)) # fill black # FPS = Frames Per Second self.FPSCLOCK = pygame.time.Clock() # init target self.targetPos = (500, 100) # init obstacle(s) self.obstacles = [] self.obstacles.append(Rectangle(500, 700, 25, 300, 0)) self.obstacles.append(Rectangle(200, 550, 25, 200, 0)) self.obstacles.append(Rectangle(800, 550, 25, 200, 0)) # init rockets self.n_rockets = n_rockets self.success = 0 self.total_success = 0 self.rockets = [] for i in range(n_rockets): self.rockets.append( Rocket(self.screen, self.gameSize, DNA(lifespan), lifespan, self.targetPos, self.obstacles)) self.maxFit = 0
def can_fit(self, point, furniture, idx): """Desciption: Validate that if the new Furniture object can fitin the room without overlapping any other furniture object. Rectangle class is used in this function Paramters: point(Point) : New point object where furniture is to be placed furniture(Furniture) : Furniture object that is to be fitted in new place idx : Index of furniture in room objects list Returns: True if object can fit else false """ # print(point.x + furniture.top_right.x , self.top_right.x , point.y+furniture.top_right.y , self.top_right.y) if point.x + furniture.top_right.x > self.top_right.x or point.y + furniture.top_right.y > self.top_right.y: return False for item in self.redAreas: if item["id"] is not idx: temp = Rectangle( item["point"], Point(item["point"].x + item["furniture"].top_right.x, item["point"].y + item["furniture"].top_right.y)) if temp.intersects( Rectangle( point, Point(point.x + furniture.top_right.x, point.y + furniture.top_right.y))): return False return True
def mergeOrAppend(self, c, shape, component, conf, imcpy, merge=0): hull = cv2.convexHull(c) x, y, width, height = cv2.boundingRect(c) area = cv2.contourArea(c) hullarea = cv2.contourArea(hull) solidity = float(area) / float(hullarea) merger = Merger() mergable_index = [] if merge == 1: mergable_index = self.getMergeIndex(component, c) if solidity > 0.4: if len(mergable_index) != 0: for ind in mergable_index: mergable_conponent = component[ind] x1, y1, w1, h1 = cv2.boundingRect(c) x2, y2, w2, h2 = cv2.boundingRect(mergable_conponent) merge_rec = merger._merge_2_rectangles( Rectangle.from_2_pos(x1, y1, x1 + w1, y1 + h1), Rectangle.from_2_pos(x2, y2, x2 + w2, y2 + h2)) merge_contour = np.array([[[merge_rec.x1, merge_rec.y1]], [[merge_rec.x2, merge_rec.y1]], [[merge_rec.x2, merge_rec.y2]], [[merge_rec.x1, merge_rec.y2]]], dtype=np.int32) component.pop(ind) prev_conf = conf.pop(ind) component.insert(ind, merge_contour) conf.insert(ind, max(prev_conf, solidity)) else: if shape == 'line': cv2.drawContours(imcpy, [c], 0, (255, 255, 0), 2) component.append(c) conf.append(solidity) elif shape == 'rectangle' or shape == 'square': cv2.drawContours(imcpy, [c], 0, (0, 255, 255), 2) component.append(c) conf.append(solidity) elif shape == 'pentagon' or shape == 'hexagon': cv2.drawContours(imcpy, [c], 0, (0, 0, 255), 2) component.append(c) conf.append(solidity) elif shape == 'circle': # or shape =='ellipse': cv2.drawContours(imcpy, [c], 0, (0, 255, 0), 2) component.append(c) conf.append(solidity) elif shape == 'triangle': cv2.drawContours(imcpy, [c], 0, (255, 0, 255), 2) component.append(c) conf.append(solidity) return (component, conf)
def main(): juxing1 = Rectangle() juxing1.setWidth(4) juxing1.setHeight(40) print("the width is", juxing1.getWidth()) print("the height is", juxing1.getHeight()) print("the Perimeter is", juxing1.getPerimeter()) print("the Area is", juxing1.getArea())
def main1(): juxing2 = Rectangle() juxing2.setWidth(3.5) juxing2.setHeight(35.7) print("the width is", juxing2.getWidth()) print("the height is", juxing2.getHeight()) print("the Perimeter is", juxing2.getPerimeter()) print("the Area is", juxing2.getArea())
def test_make4_rectangle(self): self.assertEqual( Rectangle(0, 0, 4, 4).make4(), [ Rectangle(0, 0, 2.0, 2.0), Rectangle(2.0, 0, 4, 2.0), Rectangle(0, 2.0, 2.0, 4), Rectangle(2.0, 2.0, 4, 4) ])
def rectangle(): if request.method == "GET": return jsonify({"area":"undefined"}) elif request.method == "POST": amazing = request.json["amazing"] height = request.json["height"] this_rectangle = Rectangle(amazing, height) area = this_rectangle.area() return jsonify({"rectangle_area":area})
def __init__(self, x, y, w, h, capacity): self.bounds = Rectangle(Point(x, y), w, h) self.points = [] self.tl = None self.tr = None self.bl = None self.br = None self.split = False self.capacity = capacity
def main(): rectangle1 = Rectangle(4, 40) rectangle2 = Rectangle(3.5, 35.7) print(f"Rectangle 1: Width = {rectangle1.getWidth()},", \ f"Height = {rectangle1.getHeight()}, Area = {rectangle1.getArea()}, " \ f"Perimeter = {rectangle1.getPerimeter()}") print(f"Rectangle 2: Width = {rectangle2.getWidth()}, " \ f"Height = {rectangle2.getHeight()}, Area = {round(rectangle2.getArea(), 2)}," \ f"Perimeter = {rectangle2.getPerimeter()}")
def main(): #Prompts the user to enter the length and width length = input("Enter the length: ") width = input("Enter the width: ") #Creates an object of the class my_rectangle = Rectangle(length, width) #Print the length and width print("length:", my_rectangle.get_length()) print("width:", my_rectangle.get_width())
def main(cls, args): width = 2 length = 3 rectangle = Rectangle(width, length) print "Rectangle width:", width, "and length:", length, "Area:", rectangle.area( ), "Perimeter:", rectangle.perimeter() radius = 10 circle = Circle(radius) print "Circle radius:", radius, "Area:", circle.area( ), "Perimeter:", circle.perimeter()
def closest_Linf(a: Rectangle, b: Rectangle) -> int: a_corners = a.get_corners() b_corners = b.get_corners() minimum = 10000 for first in a_corners: for second in b_corners: current = Linf(first, second) minimum = min(current, minimum) return minimum
def sensing_direction(a: Rectangle, b: Rectangle, r: int) -> \ Tuple[Direction, bool]: a_center = a.get_center() corners = b.get_corners() for corner in corners: if r < L2(a_center, corner): return get_weighted_random_move(a.get_center(), a.get_direction()), False return direction_to_point(a_center, b.get_center()), True
def __init__(self, x, y, width, height, resources, object_id=0): Rectangle.__init__(self, x, y, width, height) self.resources = resources self.is_destroyed = False if object_id != 0: self.id = object_id else: self.id = GameObject.GAME_OBJECT_ID GameObject.GAME_OBJECT_ID += 1
def main(): circle = Circle(1.5) print("A circle", circle) print("The radius is", circle.getRadius()) print("The area is", circle.getArea()) print("The diameter is", circle.getDiameter()) rectangle = Rectangle(2, 4) print("\nA rectangle", rectangle) print("The area is", rectangle.getArea()) print("The perimeter is", rectangle.getPerimeter())
def test_vector_to_list(self): # given expected_list = [6784, 6784] # when vector = np.array([[6784], [6784]]) rectangle = Rectangle() actual_list = rectangle.vector_to_list(vector) # that self.assertEqual(actual_list , expected_list)
def test_rotation_matrix(self): # given expected_rotation_matrix = np.array([[1, -0], [0, 1]]) # when angle = 0 rectangle = Rectangle() actual_rotation_matrix = rectangle.rotation_matrix(angle) # that self.assertEqual((actual_rotation_matrix == expected_rotation_matrix).all(), True)
def smart_collide(character: Rectangle, foods: List[Rectangle]) -> List[int]: indexes = [] lim = character.get_limits() for i in range(len(foods)): f_lim = foods[i].get_limits() if f_lim.x_max < lim.x_min: continue elif f_lim.x_min > lim.x_max: return indexes if character.collides(foods[i]): indexes.append(i) return indexes
def calculate_clicked(): if txtHeight != "" and txtWidth != "": w = txtWidth.get() h = txtHeight.get() if (not w.isdigit() or not h.isdigit): result.delete(0, 'end') result.insert(0, "width or height not a number") return r = Rectangle(int(w), int(h)) newDimensions = "x".join( [str(x) for x in r.getNearestDivisibleWidth()]) result.delete(0, 'end') result.insert(0, newDimensions)
def test_to_vector(self): # given x = 6784 y = 6784 expected_vector = np.array([[6784], [6784]]) # when rectangle = Rectangle() actual_vector = rectangle.to_vector(x, y) # that self.assertEqual((actual_vector == expected_vector).all(), True)
def main(): rect = Rectangle() sq = square(6) tri = Triangle() rect.breadth = 5 rect.length = 30 sq.length = 6 tri = Triangle() result1 = rect.area() result2 = tri.area() result3 = sq.area() #always observe the object used final = result3 + result2 + result1 print("behold... the reuslt", final)
class Test(unittest.TestCase): def setUp(self): self.rect = Rectangle(x=1, y=1, side=5) def test_init(self): self.assertTrue(self.rect.x==1 and self.rect.y==1 and self.rect.side==5) def test_draw(self): self.assertTrue(self.rect.state == "not drawed") self.rect.draw() self.assertTrue(self.rect.state == "drawed") def test_area(self): self.assertTrue(self.rect.area() == 25)
class ShapeMaker: """Facade class""" def __init__(self): self.__circle = Circle() self.__rectangle = Rectangle() self.__square = Square() def drawCircle(self): self.__circle.draw() def drawRectangle(self): self.__rectangle.draw() def drawSquare(self): self.__square.draw()
def __init__(self, position=Coordinate(), size=1.0, id=None, classes=None): """Keyword arguments: @param position: a Coordinate defining the position in the SVG document @type position: Coordinate @param size: the size of the square, i.e. the length of each side @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ if isinstance(position, Coordinate): Rectangle.__init__(self, position, size, size, id=id, classes=classes) else: raise TypeError("position must be of type 'Coordinate'")
class GeometricApp: def __init__(self): self.rect = Rectangle(x=1, y=1, side=5) def use(self): area = self.rect.area()
def __init__( self, X, Y, W, H, HASSTROKE, STROKE, HASFILL, FILL): # BRICK PROPERTIES self.rectangle = Rectangle(W, H, HASSTROKE, STROKE, HASFILL, FILL) self.rectangle.setPosition(X, Y) self.imAlive = True self.respawns = False self.timeToRespawn = 60 # time is in frames self.frame = 0
def _make_cutout_rect(self, rect): """ If rect intersects container, return a rectangle to cut out the container on the side """ if self._board_bbox.encloses(rect): return None cut = rect for axis in xrange(2): if rect.low(axis) < self._board_bbox.low(axis): #left/bottom cut move = np.array([0,0]) move[axis] = -self._thickness_xy*2 cut = Rectangle.union(cut, rect.copy().move(move)) # print cut if rect.high(axis) > self._board_bbox.high(axis): #right/top cut move = np.array([0,0]) move[axis] = self._thickness_xy*2 cut = Rectangle.union(cut, rect.copy().move(move)) # print cut return cut
def __init__ (self, frameWidth): """ set up the parameters of the paddle (which is really just a rectangle) """ self.frameWidth = frameWidth self.width = 60 self.height = 5 self.hasStroke = False self.strokeColor = color(255,255,255) self.hasFill = True self.fillColor = color(255,255,255) self.x = frameWidth/2 self.y = 270 self.rectangle = Rectangle(self.width, self.height, self.hasStroke, self.strokeColor, self.hasFill, self.fillColor) self.rectangle.setPosition(self.x, self.y)
class Brick: def __init__( self, X, Y, W, H, HASSTROKE, STROKE, HASFILL, FILL): # BRICK PROPERTIES self.rectangle = Rectangle(W, H, HASSTROKE, STROKE, HASFILL, FILL) self.rectangle.setPosition(X, Y) self.imAlive = True self.respawns = False self.timeToRespawn = 60 # time is in frames self.frame = 0 def display( self ): if (self.imAlive): self.rectangle.display() else: if (self.respawns): self.frame += 1 if(self.frame > self.timeToRespawn): # rise up from your grave, brick self.imAlive = True def die( self ) : self.imAlive = False self.frame = 0
def add_image_to_display(self,data,bbox): #make the bounding box of the entire image collection include this bounding box #if there is no big box, make one! if self.bigBox is None: self.bigBox = Rectangle(0,0,0,0) bbox.copyTo(self.bigBox) #otherwise make what we have bigger if necessary else: self.bigBox.expand_to_include(bbox) #use our handy rectangle method to do this self.axis.hold(True) #matplotlib axis #plot the image theimg=self.axis.imshow(data,cmap='gray',extent=[bbox.left,bbox.right,bbox.bottom,bbox.top]) self.matplot_images.append(theimg) #make sure all the other images stay in the field of view #self.set_view_home() theimg.set_clim(0,self.maxvalue) self.axis.set_xlabel('X Position (um)') self.axis.set_ylabel('Y Position (um)')
def __init__(self, pointlist, colour=OBSTACLE_COLOUR): self.pointlist = pointlist self.vector_list = [] for point in pointlist: self.vector_list.append(Vector(point)) self.colour = colour x_min = pointlist[0][0] x_max = pointlist[0][0] y_min = pointlist[0][1] y_max = pointlist[0][1] for point in pointlist: if point[0] < x_min: x_min = point[0] if point[0] > x_max: x_max = point[0] if point[1] < y_min: y_min = point[1] if point[1] > y_max: y_max = point[1] self.bounding_box = Rectangle([x_min, y_min], [x_max, y_max])
def load_from_metadata(self,filename): #loads this image from a metadata file file = open(filename,'r') data = file.read() file.close() data = data.replace("false","False") data = data.replace("true","True") data = data.replace("null","0") f = eval(str(data)) top=f["boundBox"]["top"] bottom=f["boundBox"]["bottom"] left=f["boundBox"]["left"] right=f["boundBox"]["right"] cx=(left+right)/2; cy=(top+bottom)/2; self.imagePath=f["imagePath"]["path"] self.format=f["imagePath"]["format"] self.boundBox=Rectangle(left,right,top,bottom)
class Region(object): """ This is the top level scraping tool. """ def __init__(self, pos, size, tool=None, color=None): self.rect = Rectangle(pos, size) self.tool = tool self.color = color self.last_value = None def take_snapshot(self, screen): """ screen:image -> cropped_area:image """ self.last_snapshot = screen.crop(self.rect.as_quad()) return self.last_snapshot def scrape(self, screen): """ screen:image -> contents:(Maybe str) """ self.take_snapshot(screen) self.last_value = self.tool.recognize(self.last_snapshot) return self.last_value
class Paddle: def __init__ (self, frameWidth): """ set up the parameters of the paddle (which is really just a rectangle) """ self.frameWidth = frameWidth self.width = 60 self.height = 5 self.hasStroke = False self.strokeColor = color(255,255,255) self.hasFill = True self.fillColor = color(255,255,255) self.x = frameWidth/2 self.y = 270 self.rectangle = Rectangle(self.width, self.height, self.hasStroke, self.strokeColor, self.hasFill, self.fillColor) self.rectangle.setPosition(self.x, self.y) def display( self, recX ): self.updatePosition(recX) self.rectangle.setPosition(self.x, self.y) self.rectangle.display() def updatePosition( self, recX ) : self.x = mouseX-recX-self.rectangle.width/2 self.x = constrain(self.x, 0, self.frameWidth-self.rectangle.width)
def set_boundBox(self,left,right,top,bottom): self.boundBox=Rectangle(left,right,top,bottom)
class Polygon: """Used for Obstacles that are polygons.""" def __init__(self, pointlist, colour=OBSTACLE_COLOUR): self.pointlist = pointlist self.vector_list = [] for point in pointlist: self.vector_list.append(Vector(point)) self.colour = colour x_min = pointlist[0][0] x_max = pointlist[0][0] y_min = pointlist[0][1] y_max = pointlist[0][1] for point in pointlist: if point[0] < x_min: x_min = point[0] if point[0] > x_max: x_max = point[0] if point[1] < y_min: y_min = point[1] if point[1] > y_max: y_max = point[1] self.bounding_box = Rectangle([x_min, y_min], [x_max, y_max]) def draw(self, screen, camera): draw_list = [] for vector in self.vector_list: draw_vector = vector - camera draw_list.append(draw_vector.values) pygame.draw.polygon(screen, self.colour, draw_list) def contains(self, point): if not self.bounding_box.contains(point): return False length = len(self.vector_list) # magic for loop: A point is inside the polygon when it's on the same side of an edge as an other vertex. # the following for loop checks this for every edge. This works, don't change unless # the implementation of a point changes. # Dependent on this function: Unit.check_collision for i in range(length): a = self.vector_list[i] b = self.vector_list[(i+1) % length] c = self.vector_list[(i+2) % length] vector1 = Vector([a.values[1] - b.values[1], b.values[0] - a.values[0]]) vector2 = point - a vector3 = c - a if vector1.inner(vector2) * vector1.inner(vector3) < 0: return False return True def handle_collision(self, player): new_position = player.position + player.speed length = len(self.vector_list) point1, point2 = 0, 0 for i in range(length): a = self.vector_list[i] b = self.vector_list[(i+1) % length] vector1 = Vector([a.values[1] - b.values[1], b.values[0] - a.values[0]]) vector2 = player.position - a vector3 = new_position - a if vector1.inner(vector2) * vector1.inner(vector3) < 0: point1 = a point2 = b if point1 == 0 and point2 == 0: print("TIME TO TURN ON THE DEBUGGER") player.speed = player.speed.scalar(-1) parallel, perpendicular = player.speed.split(point1 - point2) new_speed = (parallel - perpendicular).scalar(.5) player.set_speed(new_speed.values[0], new_speed.values[1])
def test_rectangle_area(self): rect = Rectangle('non-square', 5, 12) self.assertEqual(rect.get_area(), 60)
class MyImage(): def __init__(self,imagePath=None,boundBox=None): self.boundBox = boundBox #should be a class Rectangle self.imagePath = imagePath def save_metadata(self,filename): d = {"boundBox":{"top":self.boundBox.top,"bottom":self.boundBox.bottom, "left":self.boundBox.left,"right":self.boundBox.right}, "imagePath":{"path":self.imagePath,"format":".tif"} } meta = json.dumps(d) metafile = open(filename,'w') metafile.write(meta) metafile.close() def load_from_metadata(self,filename): #loads this image from a metadata file file = open(filename,'r') data = file.read() file.close() data = data.replace("false","False") data = data.replace("true","True") data = data.replace("null","0") f = eval(str(data)) top=f["boundBox"]["top"] bottom=f["boundBox"]["bottom"] left=f["boundBox"]["left"] right=f["boundBox"]["right"] cx=(left+right)/2; cy=(top+bottom)/2; self.imagePath=f["imagePath"]["path"] self.format=f["imagePath"]["format"] self.boundBox=Rectangle(left,right,top,bottom) def set_boundBox(self,left,right,top,bottom): self.boundBox=Rectangle(left,right,top,bottom) def get_cutout(self,box): ''' Expected that the int() will occasionally produce rounding error - making cutout size unstable. ''' if self.boundBox.contains_rect(box): #load image from file #todo img=Image.open(self.imagePath,mode='r') (width,height)=img.size rel_box=self.boundBox.find_relative_bounds(box) left=int(rel_box.left*width) right=int(rel_box.right*width) top=int(rel_box.top*height) bottom=int(rel_box.bottom*height) c_img=img.crop([left,top,right,bottom]) thedata=c_img.getdata() (cutwidth,cutheight)=c_img.size cut=np.reshape(np.array(thedata,np.dtype('uint8')),(cutheight,cutwidth)) return cut else: Raise_Error("cutout not in image") def get_ext(self): return ".tif" def file_has_metadata(self,path): (base,theext)=os.path.splitext(path) print "need a better way to tell if this is a metadata file" return 'txt' in theext def save_data(self,data): #img = Image.fromarray(data) #img.save(self.imagePath) imsave(self.imagePath,data) def contains_rect(self,box): return self.boundBox.contains_rect(box) def contains_point(self,x,y): return self.boundBox.contains_point(x,y) def get_data(self): img=Image.open(self.imagePath,mode='r') thedata=img.getdata() (width,height)=img.size data=np.reshape(np.array(thedata,np.dtype('uint8')),(height,width)) return data
class ImageCollection(): def __init__(self,rootpath,imageClass=MyImage,imageSource=None,axis=None,working_area = Rectangle(left=-30000,right=36000,top=-6100,bottom=16000)): self.rootpath=rootpath #rootpath to save images self.imageClass=imageClass #the class of image that this image collection should be composed of, # must conform to myImage interface self.imageSource = imageSource #a source for new data usually a microscope, could be a virtual file #needs to implement numpy2darray=imageSource.take_image(x,y) self.images = [] #list of image objects self.imgCount=0 #counter of number of images in collection self.axis=axis #matplotlib.axis to plot images self.bigBox = None #bounding box to include all images self.matplot_images=[] self.minvalue=0 self.maxvalue=512 self.working_area = working_area def display8bit(self,image, display_min, display_max): image = np.array(image, copy=True) image.clip(display_min, display_max, out=image) image -= display_min image = image / ((display_max - display_min + 1) / 256.) return image.astype(np.uint8) def lut_convert16as8bit(self,image, display_min, display_max) : lut = np.arange(2**16, dtype='uint16') lut = self.display8bit(lut, display_min, display_max) return np.take(lut, image) def get_pixel_size(self): return self.imageSource.get_pixel_size() def get_image_size_um(self): (fw,fh)=self.imageSource.get_frame_size_um() return (fw,fh) def set_view_home(self,box=None): if box==None: self.axis.set_xlim(left=self.working_area.left,right=self.working_area.right) self.axis.set_ylim(bottom=self.working_area.bottom,top=self.working_area.top) else: self.axis.set_xlim(left=box.left,right=box.right) self.axis.set_ylim(bottom=box.bottom,top=box.top) def crop_to_images(self,evt): if not self.images: self.axis.set_xlim(left=self.working_area.left,right=self.working_area.right) self.axis.set_ylim(bottom=self.working_area.bottom,top=self.working_area.top) else: self.boundary = self.get_image_size_um()[0] self.axis.set_xlim(left=self.bigBox.left-self.boundary,right=self.bigBox.right+self.boundary) self.axis.set_ylim(bottom=self.bigBox.bottom+self.boundary,top=self.bigBox.top-self.boundary) #self.axis.set_xlim(left=self.bigBox.left,right=self.bigBox.right) #self.axis.set_ylim(bottom=self.bigBox.bottom,top=self.bigBox.top) def get_cutout(self,box): #from the collection of images return the pixels contained by the Rectangle box #look for an image which contains the desired cutout for image in self.images: if image.contains_rect(box): return image.get_cutout(box) #TODO #if you don't find the cutout in one image, see if you can get it from two #TODO #can you assemble the cutout from all overlapping images (probably harder than its worth) #if you can't get it from two, go get a new image from source if self.imageSource is not None: return self.get_cutout_from_source(box) return None #we give up as we can't find the cutout for them.. sad def add_covered_point(self,x,y): for image in self.images: if image.contains_point(x,y): return True self.add_image_at(x,y) return False def oh_snap(self): (x, y) = self.imageSource.get_xy() self.add_image_at(x,y) def add_image_at(self,x,y): #go get an image at x,y try: (thedata,bbox)=self.imageSource.take_image(x,y) if thedata.dtype == np.uint16: print "converting" maxval=self.imageSource.get_max_pixel_value() thedata=self.lut_convert16as8bit(thedata,0,60000) except: #todo handle this better print "ahh no! imageSource failed us" traceback.print_exc(file=sys.stdout) print "hmm.. bbox is" bbox.printRect() print "x,y is",x,y #add this image to the collection theimage=self.add_image(thedata,bbox) return theimage def get_cutout_from_source(self,box): print "getting cutout from source" if self.imageSource is not None: #figure out the x,y of the center of the bounding box (x,y)=box.get_center() theimage=self.add_image_at(x,y) if theimage.contains_rect(box): return theimage.get_cutout(box) else: #todo.. should raise error here... source didn't return print "the source didn't contain the desired cutout" print box.printRect() return None else: print "there is no image source!" return None def add_image(self,thedata,bbox): #determine the file path of this image thefile=os.path.join(self.rootpath,"%010d"%self.imgCount + ".tif") themetafile=os.path.join(self.rootpath,"%010d"%self.imgCount + "_metadata.txt") print "imgCount:%d"%self.imgCount self.imgCount+=1 #initialize the new image and save the data theimage=self.imageClass(thefile,bbox) theimage.save_data(thedata) theimage.save_metadata(themetafile) #append this image to the list of images self.images.append(theimage) #update the display self.add_image_to_display(thedata,bbox) return theimage def update_clim(self,max=512,min=0): self.maxvalue=max self.minvalue=min for theimg in self.matplot_images: theimg.set_clim(min,max) def add_image_to_display(self,data,bbox): #make the bounding box of the entire image collection include this bounding box #if there is no big box, make one! if self.bigBox is None: self.bigBox = Rectangle(0,0,0,0) bbox.copyTo(self.bigBox) #otherwise make what we have bigger if necessary else: self.bigBox.expand_to_include(bbox) #use our handy rectangle method to do this self.axis.hold(True) #matplotlib axis #plot the image theimg=self.axis.imshow(data,cmap='gray',extent=[bbox.left,bbox.right,bbox.bottom,bbox.top]) self.matplot_images.append(theimg) #make sure all the other images stay in the field of view #self.set_view_home() theimg.set_clim(0,self.maxvalue) self.axis.set_xlabel('X Position (um)') self.axis.set_ylabel('Y Position (um)') def save_image_collection(self): #do all the saving #todo self.save_all_the_things() def print_bounding_boxes(self): print "printing bounding boxes" for image in self.images: image.boundBox.printRect() def load_image_collection(self): #list all metadata files in rootdir testimage=self.imageClass() if not os.path.isdir(self.rootpath): os.makedirs(self.rootpath) metafiles=[os.path.join(self.rootpath,f) for f in os.listdir(self.rootpath) if f.endswith('.txt') ] print "loading metadata" #loop over files reading in metadata, and initializing Image objects, reading images to update display for file in metafiles: print file theimage=self.imageClass() theimage.load_from_metadata(file) self.images.append(theimage) data=theimage.get_data() self.add_image_to_display(data,theimage.boundBox) self.imgCount+=1 del(testimage) # filename="C:\Users\Smithlab\Documents\ASI_LUM_RETIGA_CRISP.cfg" # imgsrc=imageSource(filename) # channels=imgsrc.get_channels() # imgsrc.set_channel('Violet') # imgsrc.set_exposure(250) # plt.axis() # rootPath='C:\\Users\\Smithlab\\Documents\\ImageCollectTest\\' # figure = plt.figure(1,figsize=(5,14)) # axes = figure.get_axes() # ic=ImageCollection(rootpath=rootPath,imageSource=imgsrc,axis=axes[0]) # ic.load_image_collection() # box=Rectangle(-50,50,-50,50) # data2=ic.get_cutout(box) # box=Rectangle(-140,-90,0,50) # data2=ic.get_cutout(box) # box=Rectangle(-340,-240,0,50) # data2=ic.get_cutout(box) # box=Rectangle(-740,-740,0,50) # data2=ic.get_cutout(box) # plt.show()
def __init__(self): self.rect = Rectangle(x=1, y=1, side=5)
def test_draw(self): rect = Rectangle(x=1, y=1, side=5) self.assertTrue(rect.state == "not drawed") rect.draw() self.assertTrue(rect.state == "drawed")
from Rectangle import Rectangle if __name__ == "__main__": rect = Rectangle(50,50) rect_two = Rectangle(50,50) print("Area of rect: ",rect.get_area()) print("Is rect equal to rect_two ? ",rect.equal_to(rect_two))
def setUp(self): self.rect = Rectangle(x=1, y=1, side=5)
#!/usr/bin/env python from Shape import Shape # include Shape.py from Triangle import Triangle # include Triangle.py from Rectangle import Rectangle # include Rectangle.py # create new objects and initialize data shapeObject = Shape() triangleObject = Triangle(4, 5) rectangleObject = Rectangle(4, 5) print('Shapeless area is: %24.1f' % (shapeObject.get_area())) print('Triangle (base=%d, height=%d) area is: %6.1f' % (4, 5, triangleObject.get_area())) print('Rectangle (width=%d, height=%d) area is: %4.1f' % (4, 5, rectangleObject.get_area()))
''' @author: Erwin Alvarez C ''' from Rectangle import Rectangle if __name__ == '__main__': rectangle = Rectangle(200, 300) print(rectangle.area()) rectangle.draw()
def __init__(self, pos, size, tool=None, color=None): self.rect = Rectangle(pos, size) self.tool = tool self.color = color self.last_value = None
h = int(labRect[3]) # print("printing rectangle: {0}.{1}: ({2},{3},{4},{5})".format(imageNum,expectedObjects,x,y,w,h)) # if colorspace =='lab' or 'luv': # groundColor = (0, 0, 255) # else: groundColor = (0, 0, 255) cv2.rectangle(colorCVT, (x, y), (x+w, y+h), groundColor, 1) # Draw detected objects for (detx, dety, detectedWidth, detectedHeight) in detected_objects: # use the opencv returned rectangle and create our own. detected_rectangle = Rectangle(detx, dety, detectedHeight, detectedWidth) # we use sliding windows of similar proportions to car sides # within the feature hypothesis, to compare the hypothesis # with the groundtruths when testing side car classifiers. # If the comparison is better than with the original hypothesis, # then we use that result. # We do this because when we compare to JI, it wont be similar # because ground truths are cropped to the car and the collated features # return us square (assumed to bound the features). # TODO: this assumption should be checked, how the minneighbors # collates features in opencv. # By considering rectangles # sometimes the first check will be better and quite good, # and we will waste computation and time by checking others.