Best Python code snippet using hypothesis
tracker.py
Source:tracker.py  
...273        marc_gris = brightness_contrast(image,274                                        self._image["brightness"],275                                        self._image["contrast"])276        277        self.do_draw(marc_gris, gray=True)278        279    280    def _contrast_change(self, value):281        self._image["contrast"] = int(value)282        if self._video == None: return283        284        image = self._video.frame()285        marc_gris = brightness_contrast(image,286                                        self._image["brightness"],287                                        self._image["contrast"])288        289        self.do_draw(marc_gris, gray=True)290        291    292    def _threshold_change(self, value):293        self._image["threshold"] = int(value)294        if self._video == None: return295        296        image = self._video.frame()297        marc_gris = brightness_contrast(image,298                                        self._image["brightness"],299                                        self._image["contrast"])300        301        marc_gris = threshold(marc_gris, self._image["threshold"])302        303        304        self.do_draw(marc_gris, gray=True)305        306    def _ruler_change(self, value):307        if self._video == None: return308        309        310        if not(self._onTrack):311            value = int(value)312            img = self._video.goto(value)313            self.do_draw(img, ruler=True)314        #self._axes.clear()315        #self._axes.imshow(img)316        #self._canvas.show()317        318    def load_marker(self):319        options = {"filetypes"   : [("marker files","*.mrk")]}320        321        #filename = asksaveasfilename(**options)322        filename = askopenfilename(**options)323        if filename=="":324            return325        326        327        with open(filename, 'r') as outfile:328            content = outfile.read()329            marker = json.loads(content)330            331        #storing the marker in the list332        mrkr_name = filename.split(os.sep)[-1]333        self._markers[mrkr_name] = marker334        335        #Setting the new marker as current336        self._curmarker.set(mrkr_name)337        # Creating a new menu for the new marker338        self._markermenu.add_radiobutton(label=mrkr_name,339                                         command = self.select_marker,340                                         variable=self._curmarker)341        342        #marker343        344        # Drawing the new marker345        self.draw_marker()346            347        348#        cols = ("M1VX", "M1VY", "M1VZ")349#        self._table["columns"] = cols350#        351#        for c in cols:352#            self._table.column(c, width=60, anchor='c')353#            self._table.heading(c, text=c)354#        355#        self._table["show"] = "headings"356    def select_marker(self):357        self.draw_marker()358    359    def go_start(self):360        361        # If there is no video, we move out362        if self._video == None: return363        364        img = self._video.goto_start()365        self.do_draw(img)366        367        368                    369    def go_end(self):370        # If there is no video, we move out371        if self._video == None: return372        img = self._video.goto_end()373        self.do_draw(img)374    375    def go_prev(self):376        # If there is no video, we move out377        if self._video == None: return378        img = self._video.goto_prev()379        self.do_draw(img)380    381    def go_next(self):382        # If there is no video, we move out383        if self._video == None: return384        img = self._video.goto_next()385        self.do_draw(img)386    387    def go_play(self):388        # If there is no video, we move out389        if self._video == None: return390        391        for img in self._video:392            self.do_draw(img)393        394    def open_video(self):395        #name = askopenfilename()396        name = askdirectory()397        398        self._video = videofile(name)399        self._ruler.config(to=len(self._video)-1)400        img = self._video.frame()401        self.do_draw(img)402       403        404    def mark_start(self):405        valor = int(self._ruler.get())406        self._video.mark_start(valor)407        408    def mark_end(self):409        valor = int(self._ruler.get())410        self._video.mark_end(valor)411    412    def open_callibration(self):413        options = {"filetypes"   : [("calibration files","*.ccb")],414                   "initialfile" : "camera_calibrated.ccb"}415        #filename = asksaveasfilename(**options)416        filename = askopenfilename(**options)417        if filename=="":418            return419        420        421        callib = {}422        with open(filename, 'r') as outfile:423            content = outfile.read()424            callib = json.loads(content)425            426        for k in callib:427            self._callibration[k] = array(callib[k])428            429        #print self._callibration430        431    def export_csv(self):432        options = {"filetypes"   : [("text files","*.csv")],433                   "initialfile" : "results.csv"}434        filename = asksaveasfilename(**options)435        if filename=="":436            return437        438        self._results.to_csv(filename, sep="\t")439            440    def go_exit(self):441        self._parent.destroy()442        443    def do_draw(self, img, ruler=False, gray=False):444        if not(ruler):445            self._ruler.set(self._video._ind)446        self._axes.clear()447        448        if gray:449            self._axes.imshow(img, cmap=get_cmap("gray"))450        else:451            self._axes.imshow(img)452            453        self._canvas.draw()454        self._canvas.flush_events()455        456    def draw_marker(self):457        self._axes2.clear()458        marker = self._markers[self._curmarker.get()]459        self._axes2.imshow(array(marker["marker"])*255)460        self._canvas2.draw()461    462    def track(self):        463        self._onTrack=True464        465        ind = self._curmarker.get()466        marker = self._markers[ind]467        468        mapping = {"X" : 0, "Y" : 1 , "Z" : 2}469        470        res = dict()471        index = []472        473        # Creating an new variable to hold the analysis474        for k in mapping:475            res["M"+str(ind)+"P"+k] = []476            res["M"+str(ind)+"R"+k] = []477        478        # El angulo rotado479        #res["M"+str(ind)+"a"] = []480            481        # The size of the marker482        sizes = (marker["size"], marker["size"])483        484        485        # Iterating every frame486        for frame in self._video:487            488            # Brightness and contrast analysis489            marc_gris = brightness_contrast(frame,490                                            self._image["brightness"],491                                            self._image["contrast"])492            493            marc_bw = threshold(marc_gris, self._image["threshold"])494            495            try:496            497                cnt, dist_Exo, angle, ret = find_marker_in_image(marc_bw,498                                                             marc_gris,499                                                             frame,500                                                             marker["marker"],501                                                             crnr_dist = 50,502                                                             draw_fn=self.do_draw)503                504                #print angle505            except Exception:506                ret = False507                #self._ruler.set(self._video._ind)508                self.do_draw(frame)509                continue510                511            512            try:513                ret, rvecs, tvecs = get_pose(cnt,514                                         self._callibration["matrix"],515                                         self._callibration["distortion"],516                                         angle,517                                         sizes=sizes)518            except Exception as e:519                print(e, "Algo ha salido mal")520                #self._ruler.set(self._video._ind)521                ret = False522                self.do_draw(frame)523                continue524            525            if ret:526                index.append(self._video._ind)527                for k in mapping:528                    res["M"+str(ind)+"P"+k].append(float(tvecs[mapping[k]]))529                    res["M"+str(ind)+"R"+k].append(float(rvecs[mapping[k]]))530                    531                #res["M"+str(ind)+"a"].append(angle)532            533        these_res = pd.DataFrame(res, index=index)534        self._results = pd.concat([self._results, these_res], axis=1)535        print(self._results)536            ...world.py
Source:world.py  
1# Soar (Snakes on a Robot): A Python robotics framework.2# Copyright (C) 2019 Andrew Antonitis. Licensed under the LGPLv3.3#4# soar/sim/world.py5""" Soar World and WorldObject classes/subclasses, for simulating and drawing worlds. """6import random7from math import sin, cos, pi8from soar.sim.geometry import Point, LineSegment, PointCollection9class WorldObject:10    """ An object that can be simulated and drawn in a :class:`soar.sim.world.World` on a11    :class:`soar.gui.canvas.SoarCanvas`.12    Classes that are designed to work with a World in Soar may either subclass from this class or implement its methods13    and attributes to be considered valid.14    Attributes:15        do_draw (bool): Used by a `World` to decide whether to draw the object on a canvas.16        do_step (bool): Used by a `World` to decide whether to step the object in simulation.17    Args:18        do_draw (bool): Sets the value of the `do_draw` attribute.19        do_step (bool): Sets the value of the `do_step` attribute.20        dummy (bool): Whether the object is a dummy--that is, not intended to be drawn or stepped, but used for21            some intermediate calcuation (usually collision).22        **options: Tkinter options. This may include 'tags', for drawing on a canvas, line thickness, etc.23    """24    _unique_id = 025    def __init__(self, do_draw, do_step, dummy=False, **options):  # TODO: Replace do_draw, do_step with static, dummy, etc in 2.026        self.do_draw = do_draw27        self.do_step = do_step28        self.dummy = dummy29        self.options = options30        if dummy:31            self.tags = None32        elif 'tags' in options:33            self.tags = options['tags']34        else:  # If tags are not specified, make sure this object has a unique tag35            self.tags = self.__class__.__name__ + str(self.__class__._unique_id)36            self.__class__._unique_id += 137        self.options['tags'] = self.tags38    def draw(self, canvas):39        """ Draw the object on a canvas.40        Args:41            canvas: A Tkinter Canvas or a subclass, typically a :class:`soar.gui.canvas.SoarCanvas`,42                on which the object will be drawn.43        """44        pass45    def delete(self, canvas):  # TODO: Deprecate this in 2.046        """ Delete the object from a canvas.47        Args:48            canvas: A Tkinter Canvas or a subclass, typically a :class:`soar.gui.canvas.SoarCanvas`, from which the49                object will be deleted.50        """51        if not self.dummy:52            canvas.delete(self.tags)53    def on_step(self, step_duration):54        """ Simulate the object for a step of a specified duration.55        Args:56            step_duration: The duration of the step, in seconds.57        """58        pass59    def collision(self, other, eps=1e-8):60        """ Determine whether two `WorldObject` (s) collide.61        Objects that subclass `WorldObject` should implement collision detection for every applicable class from which62        they inherit.63        Args:64            other: A supported `WorldObject` subclass with which this object could potentially collide.65            eps (float, optional): The epsilon within which to consider a collision to have occurred, different for66                each subclass.67        Returns:68            list: A list of `(x, y)` tuples consisting of all the collision points with `other`, or `None`69            if there weren't any.70        """71        pass72class Wall(WorldObject, LineSegment):73    """ A straight wall with Tk options and collision detection.74    Note that these walls are infinitely thin, so on-edge collision cannot occur.75    Args:76        p1: An `(x, y)` tuple or a :class:`soar.sim.geometry.Point` as the first endpoint of the wall.77        p1: An `(x, y)` tuple or a :class:`soar.sim.geometry.Point` as the second endpoint of the wall.78        eps (float): The epsilon within which to consider a wall vertical or horizontal.79        **options: Tkinter options.80    """81    def __init__(self, p1, p2, eps=1e-8, **options):82        WorldObject.__init__(self, do_draw=True, do_step=False, **options)83        LineSegment.__init__(self, p1, p2, eps)84        if 'width' not in options:85            self.options['width'] = 2.0  # By default walls are 2 pixels wide86    def draw(self, canvas):87        """ Draw the object on a canvas.88        Args:89            canvas: A Tkinter Canvas or a subclass, typically a :class:`soar.gui.canvas.SoarCanvas`, on which the90                object will be drawn.91        """92        if not self.dummy:93            canvas.create_line(self.p1[0], self.p1[1], self.p2[0], self.p2[1], **self.options)94            self.do_draw = False  # For a line drawn each frame, subclass this class95    def collision(self, other, eps=1e-8):96        """ Determine whether two walls intersect.97        Args:98            other: A `Wall`, or other `LineSegment` subclass.99            eps (float): The epsilon within which to consider two parallel lines the same line.100        Returns:101            A list of `(x, y)` tuples consisting of the intersection(s), or `None` if the segments do not intersect.102        """103        if isinstance(other, LineSegment):104            intersects = LineSegment.intersection(self, other, eps)105            return intersects106class Ray(Wall):107    """ A ray of a specified length, origin and direction.108    Args:109        pose: An `(x, y, theta)` tuple or :class:`soar.sim.geometry.Pose` as the origin of the ray.110        length (float): The length of the ray.111        **options: Tkinter options.112    """113    def __init__(self, pose, length, eps=1e-8, **options):114        x0, y0, theta = pose115        x1, y1 = x0+cos(theta)*length, y0+sin(theta)*length116        Wall.__init__(self, (x0, y0), (x1, y1), eps=eps, **options)117        self.length = length118class Polygon(PointCollection, WorldObject):119    """ A movable polygon with Tkinter options.120    Args:121        points: A list of `(x, y)` tuples or :class:`soar.sim.geometry.Point`.122        center: An `(x, y)` tuple or :class:`soar.sim.geometry.Point` as the pivot or center of the collection.123        **options: Tkinter options.124    """125    def __init__(self, points, center=None, **options):126        PointCollection.__init__(self, points, center)127        WorldObject.__init__(self, do_draw=True, do_step=False, **options)128    @property129    def borders(self):  # Build perimeter lines for collision detection130        return [LineSegment(self.points[i-1], self.points[i]) for i in range(len(self.points))]131    def draw(self, canvas):132        """ Draw the object on a canvas.133        Args:134            canvas: A Tkinter Canvas or a subclass, typically a :class:`soar.gui.canvas.SoarCanvas`, on which the135                object will be drawn.136        """137        if not self.dummy:138            flat_points = [p for pair in self.points for p in pair]139            canvas.create_polygon(*flat_points, **self.options)140            self.do_draw = False141    def collision(self, other, eps=1e-8):142        """ Determine whether the polygon intersects with another `WorldObject`.143        Args:144            other: Either a `Polygon` or a `Wall` as the other object.145            eps (float, optional): The epsilon within which to consider a collision to have occurred.146        """147        if isinstance(other, Polygon):  # Might be able to do this better I suppose148            intersects = []149            for i in self.borders:150                for j in other.borders:151                    line_intersects = i.intersection(j, eps=eps)152                    if line_intersects:153                        intersects.extend(line_intersects)154            return intersects if len(intersects) > 0 else None155        elif isinstance(other, Wall):156            intersects = []157            for i in self.borders:158                line_intersects = i.intersection(other, eps=eps)159                if line_intersects:160                    intersects.extend(line_intersects)161            return intersects if len(intersects) > 0 else None162class Block(Polygon):163    """ An arbitrarily thick wall centered on a line.164    Useful when infinitely-thin lines are causing issues with collision detection.165    Args:166        p1: An `(x, y)` tuple or :class:`soar.sim.geometry.Point` as the first endpoint of the line segment.167        p1: An `(x, y)` tuple or :class:`soar.sim.geometry.Point` as the second endpoint of the line segment.168        thickness (float): The thickness of the block to expand out from the line on which it is centered.169        **options: Tkinter options.170    """171    def __init__(self, p1, p2, thickness=0.002, **options):172        self.thickness = thickness173        # Build the perimeter of the wall as points174        p1 = Point(*p1)175        p2 = Point(*p2)176        mid = p1.midpoint(p2)177        points = []178        for endpoint in [p1, p2]:179            temp = endpoint.scale(1.0+thickness/endpoint.distance(mid), mid)180            pivot = temp.midpoint(endpoint)181            temp2 = temp.rotate(pivot, -pi / 2)182            temp = temp.rotate(pivot, pi/2)183            points.extend([temp, temp2])184        Polygon.__init__(self, points, center=None, **options)185        if 'fill' not in options:186            options.update({'fill': 'black'})187    @property188    def borders(self):  # Build perimeter lines dynamically189        return [Wall(self.points[i-1], self.points[i], **self.options) for i in range(len(self.points))]190    def draw(self, canvas):191        """ Draw the object on a canvas.192        Args:193            canvas:  A Tkinter Canvas or a subclass, typically a :class:`soar.gui.canvas.SoarCanvas`, on which the194                object will be drawn.195        """196        if not self.dummy:197            for wall in self.borders:198                wall.draw(canvas)199            self.do_draw = False200class World:201    """ A simulated world containing objects that can be simulated stepwise and drawn on a202    :class:`soar.gui.canvas.SoarCanvas`.203    Attributes:204        dimensions (tuple): An `(x, y)` tuple representing the worlds length and height.205        initial_position: An `(x, y, theta)` or :class:`soar.sim.geometry.Pose` representing the robot's206                          initial position in the world.207        objects (list): A list of (`WorldObject`, layer) tuples containing all of the world's objects.208        layer_max (int): The highest layer currently allocated to an object in the world.209        canvas: An instance of :class:`soar.gui.canvas.SoarCanvas`, if the world is being drawn, otherwise `None`.210    Args:211        dimensions (tuple): An `(x, y)` tuple representing the worlds length and height.212        initial_position: An `(x, y, theta)` or :class:`soar.sim.geometry.Pose` representing the robot's213                          initial position in the world.214        objects (list): The initial `WorldObject` (s) to add to the world215    """216    def __init__(self, dimensions, initial_position, objects=None):217        self.dimensions = dimensions218        self.initial_position = initial_position219        self.objects = []220        self.layer_max = -1221        self.canvas = None222        if objects:223            for obj in objects:224                self.add(obj)225        # Build boundary walls226        x, y = self.dimensions227        for wall in [Wall((0, 0), (x, 0)), Wall((x, 0), (x, y)), Wall((x, y), (0, y)), Wall((0, y), (0, 0))]:228            self.add(wall)229    def __getitem__(self, item):230        """ Iterating over a world is the same as iterating over the (sorted) object list. """231        return self.objects[item][0]232    def add(self, obj, layer=None):233        """ Add an object to the world, with an optional layer specification.234        Args:235            obj: A `WorldObject` (or a subclass instance).236            layer (int): The layer on which the object is to be drawn. Objects are drawn in order from smallest to237                largest layer. If this argument is `None`, the object's layer will be set to one higher than the238                highest layer in the objects list.239        """240        if layer is None:241            layer = self.layer_max + 1242            self.layer_max += 1243        elif layer > self.layer_max:244            self.layer_max = layer245        self.objects.append((obj, layer))246        self.objects.sort(key=lambda tup: tup[1])  # Sort the list of objects by layer priority247        setattr(obj, 'world', self)  # Ensure that every object has a back reference to the world248    def draw(self, canvas):249        """ Draw the world on a canvas.250        Objects are drawn in order from the lowest to highest layer if their `do_draw` attribute is True.251        Args:252            canvas: The :class:`soar.gui.canvas.SoarCanvas` on which to draw the world. How each object is drawn is up253                to the object.254        """255        self.canvas = canvas256        for obj, layer in self.objects:  # The list of objects is already sorted by layer257            if obj.do_draw:258                obj.draw(canvas)259    def delete(self, canvas):  # TODO: Deprecate this in 2.0260        """ Delete the world from a canvas, by deleting each object at a time.261        Args:262            canvas: The :class:`soar.gui.canvas.SoarCanvas` from which to delete.263        """264        for obj, layer in self.objects:265            if obj.do_draw:  # Objects only need to be deleted if they were drawn266                obj.delete(canvas)267    def on_step(self, step_duration):268        """ Perform a single step on the world's objects.269        Args:270            step_duration (float): The duration of the step in seconds.271        """272        for obj, layer in self.objects:273            if obj.do_step:274                obj.on_step(step_duration)275    def find_all_collisions(self, obj, eps=1e-8, condition=None):276        """ Finds all the collisions of a `WorldObject` subclass with objects in the world.277        Args:278            obj: A `WorldObject` or subclass instance. Objects in the world must know how to collide with it.279            eps (float, optional): An optional epsilon within which to consider a collision to have occurred. What that280                means differs between `WorldObject` subclasses.281            condition (optional): A function to apply to each object in the world that must be `True` in order for it282                to be considered.283        Returns:284            list: A list of `(world_obj, p)` tuples, where `world_obj` is the object that collided and `p` is the285            :class:`soar.sim.geometry.Point` at which the collision occurred. If multiple collision points occurred with286            the same object, each will be listed separately. If no collisions occurred, returns `None`.287        """288        collisions = []289        for world_obj in self:290            if condition is None or condition(world_obj):  # True if no condition or if the object matches291                obj_collisions = world_obj.collision(obj, eps)292                if obj_collisions:293                    for single_collision in obj_collisions:294                        collisions.append((world_obj, single_collision))...callibration.py
Source:callibration.py  
...165        166        if not(self._onCallibrate):167            value = int(value)168            img = self._video.goto(value)169            self.do_draw(img, ruler=True)170        #self._axes.clear()171        #self._axes.imshow(img)172        #self._canvas.show()173        174    def define_chess(self):175        #d = DefineChess(self._parent)176        d = DefineChess(self._parent,177                        self._chess["shape"],178                        self._chess["size"])179        180        try:181            shape, thesize= d.result182        except TypeError:183            return184        185        print(shape, thesize)186        self._chess = { "shape" : shape,187                        "size"  : thesize}188        189    def go_start(self):190        191        # If there is no video, we move out192        if self._video == None: return193        194        img = self._video.goto_start()195        self.do_draw(img)196        197        198                    199    def go_end(self):200        # If there is no video, we move out201        if self._video == None: return202        img = self._video.goto_end()203        self.do_draw(img)204    205    def go_prev(self):206        # If there is no video, we move out207        if self._video == None: return208        img = self._video.goto_prev()209        self.do_draw(img)210    211    def go_next(self):212        # If there is no video, we move out213        if self._video == None: return214        img = self._video.goto_next()215        self.do_draw(img)216    217    def go_play(self):218        # If there is no video, we move out219        if self._video == None: return220        221        for img in self._video:222            self.do_draw(img)223        224    def open_video(self):225        #name = askopenfilename()226        name = askdirectory()227        228        self._video = videofile(name)229        self._ruler.config(to=len(self._video)-1)230        img = self._video.frame()231        self.do_draw(img)232        233        234    def mark_start(self):235        valor = int(self._ruler.get())236        self._video.mark_start(valor)237        238    def mark_end(self):239        valor = int(self._ruler.get())240        self._video.mark_end(valor)241    242    def save_callibration(self):243        options = {"filetypes"   : [("calibration files","*.ccb")],244                   "initialfile" : "camera_calibrated.ccb"}245        filename = asksaveasfilename(**options)246        if filename=="":247            return248        249        with open(filename, 'w') as outfile:250            json.dump(self._callibration, outfile)251            #matrix = self._callibration["matrix"].tolist()252            #json.dump(matrix, outfile)253            #distortion = self._callibration["distortion"].tolist()254            #json.dump(distortion, outfile)255            256    def go_exit(self):257        self._parent.destroy()258        259    def do_draw(self, img, ruler=False):260        if not(ruler):261            self._ruler.set(self._video._ind)262        self._axes.clear()263        self._axes.imshow(img)264        self._canvas.draw()265        self._canvas.flush_events()266    267    def callibrate(self):268        self._onCallibrate=True269        ret,mtx,dist,rvecs,tvecs = callibration(self._video,270                                                self._chess["shape"],271                                                self.do_draw,272                                                the_size=self._chess["size"])273        self._onCallibrate=False...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
