Best Python code snippet using fMBT_python
BBoxTest.py
Source:BBoxTest.py  
1#!/usr/bin/env python234"""5Test code for the BBox Object67"""89import unittest1011from BBox import *1213class testCreator(unittest.TestCase):14    def testCreates(self):15        B = BBox(((0,0),(5,5)))16        self.failUnless(isinstance(B, BBox))1718    def testType(self):19        B = N.array(((0,0),(5,5)))20        self.failIf(isinstance(B, BBox))2122    def testDataType(self):23        B = BBox(((0,0),(5,5)))24        self.failUnless(B.dtype == N.float)2526    def testShape(self):27        B = BBox((0,0,5,5))28        self.failUnless(B.shape == (2,2))29        30    def testShape2(self):31        self.failUnlessRaises(ValueError, BBox, (0,0,5) )32        33    def testShape3(self):34        self.failUnlessRaises(ValueError, BBox, (0,0,5,6,7) )3536    def testArrayConstruction(self):37        A = N.array(((4,5),(10,12)), N.float_)38        B = BBox(A)39        self.failUnless(isinstance(B, BBox))40        41    def testMinMax(self):42        self.failUnlessRaises(ValueError, BBox, (0,0,-1,6) )4344    def testMinMax2(self):45        self.failUnlessRaises(ValueError, BBox, (0,0,1,-6) )4647    def testMinMax(self):48        # OK to have a zero-sized BB49        B = BBox(((0,0),(0,5)))50        self.failUnless(isinstance(B, BBox))5152    def testMinMax2(self):53        # OK to have a zero-sized BB54        B = BBox(((10.0,-34),(10.0,-34.0)))55        self.failUnless(isinstance(B, BBox))5657    def testMinMax3(self):58        # OK to have a tiny BB59        B = BBox(((0,0),(1e-20,5)))60        self.failUnless(isinstance(B, BBox))6162    def testMinMax4(self):63        # Should catch tiny difference64        self.failUnlessRaises(ValueError, BBox, ((0,0), (-1e-20,5)) )6566class testAsBBox(unittest.TestCase):6768    def testPassThrough(self):69        B = BBox(((0,0),(5,5)))70        C = asBBox(B)71        self.failUnless(B is C)7273    def testPassThrough2(self):74        B = (((0,0),(5,5)))75        C = asBBox(B)76        self.failIf(B is C)77    78    def testPassArray(self):79        # Different data type80        A = N.array( (((0,0),(5,5))) )81        C = asBBox(A)82        self.failIf(A is C)83    84    def testPassArray2(self):85        # same data type -- should be a view86        A = N.array( (((0,0),(5,5))), N.float_ )87        C = asBBox(A)88        A[0,0] = -1089        self.failUnless(C[0,0] == A[0,0])90    91class testIntersect(unittest.TestCase):9293    def testSame(self):94        B = BBox(((-23.5, 456),(56, 532.0)))95        C = BBox(((-23.5, 456),(56, 532.0)))96        self.failUnless(B.Overlaps(C) )97    98    def testUpperLeft(self):99        B = BBox( ( (5, 10),(15, 25) ) )100        C = BBox( ( (0, 12),(10, 32.0) ) )101        self.failUnless(B.Overlaps(C) )102    103    def testUpperRight(self):104        B = BBox( ( (5, 10),(15, 25) ) )105        C = BBox( ( (12, 12),(25, 32.0) ) )106        self.failUnless(B.Overlaps(C) )107    108    def testLowerRight(self):109        B = BBox( ( (5, 10),(15, 25) ) )110        C = BBox( ( (12, 5),(25, 15) ) )111        self.failUnless(B.Overlaps(C) )112    113    def testLowerLeft(self):114        B = BBox( ( (5, 10),(15, 25) ) )115        C = BBox( ( (-10, 5),(8.5, 15) ) )116        self.failUnless(B.Overlaps(C) )117        118    def testBelow(self):119        B = BBox( ( (5, 10),(15, 25) ) )120        C = BBox( ( (-10, 5),(8.5, 9.2) ) )121        self.failIf(B.Overlaps(C) )122        123    def testAbove(self):124        B = BBox( ( (5, 10),(15, 25) ) )125        C = BBox( ( (-10, 25.001),(8.5, 32) ) )126        self.failIf(B.Overlaps(C) )127        128    def testLeft(self):129        B = BBox( ( (5, 10),(15, 25) ) )130        C = BBox( ( (4, 8),(4.95, 32) ) )131        self.failIf(B.Overlaps(C) )132        133    def testRight(self):134        B = BBox( ( (5, 10),(15, 25) ) )135        C = BBox( ( (17.1, 8),(17.95, 32) ) )136        self.failIf(B.Overlaps(C) )137138    def testInside(self):139        B = BBox( ( (-15, -25),(-5, -10) ) )140        C = BBox( ( (-12, -22), (-6, -8) ) )141        self.failUnless(B.Overlaps(C) )142        143    def testOutside(self):144        B = BBox( ( (-15, -25),(-5, -10) ) )145        C = BBox( ( (-17, -26), (3, 0) ) )146        self.failUnless(B.Overlaps(C) )147    148    def testTouch(self):149        B = BBox( ( (5, 10),(15, 25) ) )150        C = BBox( ( (15, 8),(17.95, 32) ) )151        self.failUnless(B.Overlaps(C) )152        153    def testCorner(self):154        B = BBox( ( (5, 10),(15, 25) ) )155        C = BBox( ( (15, 25),(17.95, 32) ) )156        self.failUnless(B.Overlaps(C) )157        158    def testZeroSize(self):159        B = BBox( ( (5, 10),(15, 25) ) )160        C = BBox( ( (15, 25),(15, 25) ) )161        self.failUnless(B.Overlaps(C) )162        163    def testZeroSize2(self):164        B = BBox( ( (5, 10),(5, 10) ) )165        C = BBox( ( (15, 25),(15, 25) ) )166        self.failIf(B.Overlaps(C) )167        168    def testZeroSize3(self):169        B = BBox( ( (5, 10),(5, 10) ) )170        C = BBox( ( (0, 8),(10, 12) ) )171        self.failUnless(B.Overlaps(C) )172173    def testZeroSize4(self):174        B = BBox( ( (5, 1),(10, 25) ) )175        C = BBox( ( (8, 8),(8, 8) ) )176        self.failUnless(B.Overlaps(C) )177178179180class testEquality(unittest.TestCase):181    def testSame(self):182        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )183        C = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )184        self.failUnless(B == C)185        186    def testIdentical(self):187        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )188        self.failUnless(B == B)189        190    def testNotSame(self):191        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )192        C = BBox( ( (1.0, 2.0), (5.0, 10.1) ) )193        self.failIf(B == C)194        195    def testWithArray(self):196        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )197        C = N.array( ( (1.0, 2.0), (5.0, 10.0) ) )198        self.failUnless(B == C)199        200    def testWithArray2(self):201        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )202        C = N.array( ( (1.0, 2.0), (5.0, 10.0) ) )203        self.failUnless(C == B)204        205    def testWithArray2(self):206        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )207        C = N.array( ( (1.01, 2.0), (5.0, 10.0) ) )208        self.failIf(C == B)209        210class testInside(unittest.TestCase):211    def testSame(self):212        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )213        C = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )214        self.failUnless(B.Inside(C))215216    def testPoint(self):217        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )218        C = BBox( ( (3.0, 4.0), (3.0, 4.0) ) )219        self.failUnless(B.Inside(C))220221    def testPointOutside(self):222        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )223        C = BBox( ( (-3.0, 4.0), (0.10, 4.0) ) )224        self.failIf(B.Inside(C))225226    def testUpperLeft(self):227        B = BBox( ( (5, 10),(15, 25) ) )228        C = BBox( ( (0, 12),(10, 32.0) ) )229        self.failIf(B.Inside(C) )230    231    def testUpperRight(self):232        B = BBox( ( (5, 10),(15, 25) ) )233        C = BBox( ( (12, 12),(25, 32.0) ) )234        self.failIf(B.Inside(C) )235    236    def testLowerRight(self):237        B = BBox( ( (5, 10),(15, 25) ) )238        C = BBox( ( (12, 5),(25, 15) ) )239        self.failIf(B.Inside(C) )240    241    def testLowerLeft(self):242        B = BBox( ( (5, 10),(15, 25) ) )243        C = BBox( ( (-10, 5),(8.5, 15) ) )244        self.failIf(B.Inside(C) )245        246    def testBelow(self):247        B = BBox( ( (5, 10),(15, 25) ) )248        C = BBox( ( (-10, 5),(8.5, 9.2) ) )249        self.failIf(B.Inside(C) )250        251    def testAbove(self):252        B = BBox( ( (5, 10),(15, 25) ) )253        C = BBox( ( (-10, 25.001),(8.5, 32) ) )254        self.failIf(B.Inside(C) )255        256    def testLeft(self):257        B = BBox( ( (5, 10),(15, 25) ) )258        C = BBox( ( (4, 8),(4.95, 32) ) )259        self.failIf(B.Inside(C) )260        261    def testRight(self):262        B = BBox( ( (5, 10),(15, 25) ) )263        C = BBox( ( (17.1, 8),(17.95, 32) ) )264        self.failIf(B.Inside(C) )265266class testPointInside(unittest.TestCase):267    def testPointIn(self):268        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )269        P = (3.0, 4.0)270        self.failUnless(B.PointInside(P))271272    def testUpperLeft(self):273        B = BBox( ( (5, 10),(15, 25) ) )274        P = (4, 30)275        self.failIf(B.PointInside(P))276    277    def testUpperRight(self):278        B = BBox( ( (5, 10),(15, 25) ) )279        P = (16, 30)280        self.failIf(B.PointInside(P))281    282    def testLowerRight(self):283        B = BBox( ( (5, 10),(15, 25) ) )284        P = (16, 4)285        self.failIf(B.PointInside(P))286    287    def testLowerLeft(self):288        B = BBox( ( (5, 10),(15, 25) ) )289        P = (-10, 5)290        self.failIf(B.PointInside(P))291        292    def testBelow(self):293        B = BBox( ( (5, 10),(15, 25) ) )294        P = (10, 5)295        self.failIf(B.PointInside(P))296        297    def testAbove(self):298        B = BBox( ( (5, 10),(15, 25) ) )299        P  = ( 10, 25.001)300        self.failIf(B.PointInside(P))301        302    def testLeft(self):303        B = BBox( ( (5, 10),(15, 25) ) )304        P = (4, 12)305        self.failIf(B.PointInside(P))306        307    def testRight(self):308        B = BBox( ( (5, 10),(15, 25) ) )309        P = (17.1, 12.3)310        self.failIf(B.PointInside(P))311312    def testPointOnTopLine(self):313        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )314        P = (3.0, 10.0)315        self.failUnless(B.PointInside(P))316317    def testPointLeftTopLine(self):318        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )319        P = (-3.0, 10.0)320        self.failIf(B.PointInside(P))321322    def testPointOnBottomLine(self):323        B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )324        P = (3.0, 5.0)325        self.failUnless(B.PointInside(P))326327    def testPointOnLeft(self):328        B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) )329        P = (-10, -5.0)330        self.failUnless(B.PointInside(P))331332    def testPointOnRight(self):333        B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) )334        P = (-1, -5.0)335        self.failUnless(B.PointInside(P))336337    def testPointOnBottomRight(self):338        B = BBox( ( (-10.0, -10.0), (-1.0, -1.0) ) )339        P = (-1, -10.0)340        self.failUnless(B.PointInside(P))341342class testFromPoints(unittest.TestCase):343344    def testCreate(self):345        Pts = N.array( ((5,2),346                (3,4),347                (1,6),348                ), N.float_ )349        B = fromPoints(Pts)350        #B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )351        self.failUnless(B[0,0] == 1.0 and352                        B[0,1] == 2.0 and353                        B[1,0] == 5.0 and354                        B[1,1] == 6.0355                        )356    def testCreateInts(self):357        Pts = N.array( ((5,2),358                (3,4),359                (1,6),360                ) )361        B = fromPoints(Pts)362        self.failUnless(B[0,0] == 1.0 and363                        B[0,1] == 2.0 and364                        B[1,0] == 5.0 and365                        B[1,1] == 6.0366                        )367368    def testSinglePoint(self):369        Pts = N.array( (5,2), N.float_ )370        B = fromPoints(Pts)371        self.failUnless(B[0,0] == 5.0 and372                        B[0,1] == 2.0 and373                        B[1,0] == 5.0 and374                        B[1,1] == 2.0375                        )376377    def testListTuples(self):378        Pts = [ (3, 6.5),379                (13, 43.2),380                (-4.32, -4),381                (65, -23),382                (-0.0001, 23.432),383                ]384        B = fromPoints(Pts)       385        self.failUnless(B[0,0] == -4.32 and386                        B[0,1] == -23.0 and387                        B[1,0] == 65.0 and388                        B[1,1] == 43.2389                        )390class testMerge(unittest.TestCase):391    A = BBox( ((-23.5, 456), (56, 532.0)) )392    B = BBox( ((-20.3, 460), (54, 465  )) )# B should be completely inside A393    C = BBox( ((-23.5, 456), (58, 540.0)) )# up and to the right or A394    D = BBox( ((-26.5, 12), (56, 532.0)) )395396    def testInside(self):397        C = self.A.copy()398        C.Merge(self.B)399        self.failUnless(C == self.A)400401    def testFullOutside(self):402        C = self.B.copy()403        C.Merge(self.A)404        self.failUnless(C == self.A)405406    def testUpRight(self):407        A = self.A.copy()408        A.Merge(self.C)409        self.failUnless(A[0] == self.A[0] and A[1] == self.C[1])410411    def testDownLeft(self):412        A = self.A.copy()413        A.Merge(self.D)414        self.failUnless(A[0] == self.D[0] and A[1] == self.A[1])415416class testWidthHeight(unittest.TestCase):417    B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )418    def testWidth(self):419        self.failUnless(self.B.Width == 4.0)420421    def testWidth(self):422        self.failUnless(self.B.Height == 8.0)423424    def attemptSetWidth(self):425        self.B.Width = 6426427    def attemptSetHeight(self):428        self.B.Height = 6429430    def testSetW(self):431        self.failUnlessRaises(AttributeError, self.attemptSetWidth)432        433    def testSetH(self):434        self.failUnlessRaises(AttributeError, self.attemptSetHeight)435        436class testCenter(unittest.TestCase):437    B = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )438    def testCenter(self):439        self.failUnless( (self.B.Center == (3.0, 6.0)).all() )440441    def attemptSetCenter(self):442        self.B.Center = (6, 5)443444    def testSetCenter(self):445        self.failUnlessRaises(AttributeError, self.attemptSetCenter)446        447448class testBBarray(unittest.TestCase):449    BBarray = N.array( ( ((-23.5, 456), (56, 532.0)),450                         ((-20.3, 460), (54, 465  )),451                         ((-23.5, 456), (58, 540.0)),452                         ((-26.5,  12), (56, 532.0)),453                       ),454                       dtype=N.float)455    BB = asBBox( ((-26.5,  12.), ( 58. , 540.)) )456457    def testJoin(self):458        BB = fromBBArray(self.BBarray)459        self.failUnless(BB == self.BB, "Wrong BB was created. It was:\n%s \nit should have been:\n%s"%(BB, self.BB))460461class testNullBBox(unittest.TestCase):462    B1 = NullBBox()463    B2 = NullBBox()464    B3 = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )465466    def testValues(self):467        self.failUnless( N.alltrue(N.isnan(self.B1)) )468    469    def testIsNull(self):470        self.failUnless( self.B1.IsNull )471472    def testEquals(self):473        self.failUnless( (self.B1 == self.B2) == True )474    475    def testNotEquals(self):476        self.failUnless ( (self.B1 == self.B3) == False,477                          "NotEquals failed for\n%s,\n %s:%s"%(self.B1, self.B3, (self.B1 == self.B3)) )    478479    def testNotEquals2(self):480        self.failUnless ( (self.B3 == self.B1) == False,481                          "NotEquals failed for\n%s,\n %s:%s"%(self.B3, self.B1, (self.B3 == self.B1))  )    482        483    def testMerge(self):484        C = self.B1.copy()485        C.Merge(self.B3)486        self.failUnless( C == self.B3,487                         "merge failed, got: %s"%C )488        489    def testOverlaps(self):490        self.failUnless( self.B1.Overlaps(self.B3) == False)491492    def testOverlaps2(self):493        self.failUnless( self.B3.Overlaps(self.B1) == False)494495496class testInfBBox(unittest.TestCase):497    B1 = InfBBox()498    B2 = InfBBox()499    B3 = BBox( ( (1.0, 2.0), (5.0, 10.0) ) )500    NB = NullBBox()501502    def testValues(self):503        self.failUnless( N.alltrue(N.isinf(self.B1)) )504    505#    def testIsNull(self):506#        self.failUnless( self.B1.IsNull )507508    def testEquals(self):509        self.failUnless( (self.B1 == self.B2) == True )510    511    def testNotEquals(self):512        print (self.B1 == self.B3) == False513        self.failUnless ( (self.B1 == self.B3) == False,514                          "NotEquals failed for\n%s,\n %s:%s"%(self.B1, self.B3, (self.B1 == self.B3)) )    515516    def testNotEquals2(self):517        self.failUnless ( (self.B3 == self.B1) == False,518                          "NotEquals failed for\n%s,\n %s:%s"%(self.B3, self.B1, (self.B3 == self.B1))  )    519        520    def testMerge(self):521        C = self.B1.copy()522        C.Merge(self.B3)523        self.failUnless( C == self.B2,524                         "merge failed, got: %s"%C )525526    def testMerge2(self):527        C = self.B3.copy()528        C.Merge(self.B1)529        self.failUnless( C == self.B1,530                         "merge failed, got: %s"%C )531532    def testOverlaps(self):533        self.failUnless( self.B1.Overlaps(self.B2) == True)534535    def testOverlaps2(self):536        self.failUnless( self.B3.Overlaps(self.B1) == True)537        538    def testOverlaps3(self):539        self.failUnless( self.B1.Overlaps(self.B3) == True)540541    def testOverlaps4(self):542        self.failUnless( self.B1.Overlaps(self.NB) == True)543544    def testOverlaps5(self):545        self.failUnless( self.NB.Overlaps(self.B1) == True)546    547    548549if __name__ == "__main__":
...object_detection_helper.py
Source:object_detection_helper.py  
...54    for i, bbox in enumerate(boxes):55        bb = bbox.numpy()56        rect = [bb[1]-bb[3]/2, bb[0]-bb[2]/2, bb[3], bb[2]]57        draw_rect(ax, rect)58def activ_to_bbox(acts, anchors, flatten=True):59    "Extrapolate bounding boxes on anchors from the model activations."60    if flatten:61        acts.mul_(acts.new_tensor([[0.1, 0.1, 0.2, 0.2]]))62        centers = anchors[...,2:] * acts[...,:2] + anchors[...,:2]63        sizes = anchors[...,2:] * torch.exp(acts[...,:2])64        return torch.cat([centers, sizes], -1)65    else: return [activ_to_bbox(act,anc) for act,anc in zip(acts, anchors)]66    return res67def cthw2tlbr(boxes):68    "Convert center/size format `boxes` to top/left bottom/right corners."69    top_left = boxes[:,:2] - boxes[:,2:]/270    bot_right = boxes[:,:2] + boxes[:,2:]/271    return torch.cat([top_left, bot_right], 1)72def intersection(anchors, targets):73    "Compute the sizes of the intersections of `anchors` by `targets`."74    ancs, tgts = cthw2tlbr(anchors), cthw2tlbr(targets)75    a, t = ancs.size(0), tgts.size(0)76    ancs, tgts = ancs.unsqueeze(1).expand(a,t,4), tgts.unsqueeze(0).expand(a,t,4)77    top_left_i = torch.max(ancs[...,:2], tgts[...,:2])78    bot_right_i = torch.min(ancs[...,2:], tgts[...,2:])79    sizes = torch.clamp(bot_right_i - top_left_i, min=0)80    return sizes[...,0] * sizes[...,1]81def IoU_values(anchors, targets):82    "Compute the IoU values of `anchors` by `targets`."83    inter = intersection(anchors, targets)84    anc_sz, tgt_sz = anchors[:,2] * anchors[:,3], targets[:,2] * targets[:,3]85    union = anc_sz.unsqueeze(1) + tgt_sz.unsqueeze(0) - inter86    return inter/(union+1e-8)87def match_anchors(anchors, targets, match_thr=0.5, bkg_thr=0.4):88    "Match `anchors` to targets. -1 is match to background, -2 is ignore."89    ious = IoU_values(anchors, targets)90    matches = anchors.new(anchors.size(0)).zero_().long() - 291    if ious.shape[1] > 0:92        vals,idxs = torch.max(ious,1)93        matches[vals < bkg_thr] = -194        matches[vals > match_thr] = idxs[vals > match_thr]95    #Overwrite matches with each target getting the anchor that has the max IoU.96    #vals,idxs = torch.max(ious,0)97    #If idxs contains repetition, this doesn't bug and only the last is considered.98    #matches[idxs] = targets.new_tensor(list(range(targets.size(0)))).long()99    return matches100def bbox_to_activ(bboxes, anchors, flatten=True):101    "Return the target of the model on `anchors` for the `bboxes`."102    if flatten:103        t_centers = (bboxes[...,:2] - anchors[...,:2]) / anchors[...,2:]104        t_sizes = torch.log(bboxes[...,2:] / anchors[...,2:] + 1e-8)105        return torch.cat([t_centers, t_sizes], -1).div_(bboxes.new_tensor([[0.1, 0.1, 0.2, 0.2]]))106    else: return [activ_to_bbox(act,anc) for act,anc in zip(acts, anchors)]107    return res108def _draw_outline(o:Patch, lw:int):109    "Outline bounding box onto image `Patch`."110    o.set_path_effects([patheffects.Stroke(111        linewidth=lw, foreground='black'), patheffects.Normal()])112def draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):113    "Draw bounding box on `ax`."114    patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))115    _draw_outline(patch, 4)116    if text is not None:117        patch = ax.text(*b[:2], text, verticalalignment='top', color=color, fontsize=text_size, weight='bold')118        _draw_outline(patch,1)119def nms(boxes, scores, thresh=0.5):120    idx_sort = scores.argsort(descending=True)121    boxes, scores = boxes[idx_sort], scores[idx_sort]122    to_keep, indexes = [], torch.LongTensor(range_of(scores))123    while len(scores) > 0:124        #pdb.set_trace()125        to_keep.append(idx_sort[indexes[0]])126        iou_vals = IoU_values(boxes, boxes[:1]).squeeze()127        mask_keep = iou_vals <= thresh128        if len(mask_keep.nonzero()) == 0: break129        idx_first = mask_keep.nonzero().min().item()130        boxes, scores, indexes = boxes[mask_keep], scores[mask_keep], indexes[mask_keep]131    return LongTensor(to_keep)132def show_preds(img, bbox_pred, preds, scores, classes, figsize=(5,5)):133    _, ax = plt.subplots(1, 1, figsize=figsize)134    for bbox, c, scr in zip(bbox_pred, preds, scores):135        img.show(ax=ax)136        txt = str(c.item()) if classes is None else classes[c.item()+1]137        draw_rect(ax, [bbox[1],bbox[0],bbox[3],bbox[2]], text=f'{txt} {scr:.2f}')138def show_results_side_by_side(learn: Learner, anchors, detect_thresh:float=0.2, nms_thresh: float=0.3,  image_count: int=5):139    with torch.no_grad():140        img_batch, target_batch = learn.data.one_batch(DatasetType.Valid, False, False, False)141        prediction_batch = learn.model(img_batch[:image_count])142        class_pred_batch, bbox_pred_batch = prediction_batch[:2]143        bbox_gt_batch, class_gt_batch = target_batch[0][:image_count], target_batch[1][:image_count]144        for img, bbox_gt, class_gt, clas_pred, bbox_pred in list(145                zip(img_batch, bbox_gt_batch, class_gt_batch, class_pred_batch, bbox_pred_batch)):146            if hasattr(learn.data, 'stats'):147                img = Image(learn.data.denorm(img))148            else:149                img = Image(img)150            bbox_pred, scores, preds = process_output(clas_pred, bbox_pred, anchors, detect_thresh)151            if bbox_pred is not None:152                to_keep = nms(bbox_pred, scores, nms_thresh)153                bbox_pred, preds, scores = bbox_pred[to_keep].cpu(), preds[to_keep].cpu(), scores[to_keep].cpu()154            t_sz = torch.Tensor([*img.size])[None].cpu()155            bbox_gt = bbox_gt[np.nonzero(class_gt)].squeeze(dim=1).cpu()156            class_gt = class_gt[class_gt > 0] - 1157            # change gt from x,y,x2,y2 -> x,y,w,h158            bbox_gt[:, 2:] = bbox_gt[:, 2:] - bbox_gt[:, :2]159            bbox_gt = to_np(rescale_boxes(bbox_gt, t_sz))160            if bbox_pred is not None:161                bbox_pred = to_np(rescale_boxes(bbox_pred, t_sz))162                # change from center to top left163                bbox_pred[:, :2] = bbox_pred[:, :2] - bbox_pred[:, 2:] / 2164            show_results(img, bbox_pred, preds, scores, learn.data.train_ds.classes[1:] , bbox_gt, class_gt, (15, 15), titleA="GT", titleB="Prediction")165def show_results(img, bbox_pred, preds, scores, classes, bbox_gt, preds_gt, figsize=(5,5)166                 , titleA: str="", titleB: str=""):167    _, ax = plt.subplots(nrows=1, ncols=2, figsize=figsize)168    ax[0].set_title(titleA)169    ax[1].set_title(titleB)170    # show prediction171    img.show(ax=ax[1])172    if bbox_pred is not None:173        for bbox, c, scr in zip(bbox_pred, preds, scores):174            txt = str(c.item()) if classes is None else classes[c.item()]175            draw_rect(ax[1], [bbox[1],bbox[0],bbox[3],bbox[2]], text=f'{txt} {scr:.2f}')176    # show gt177    img.show(ax=ax[0])178    for bbox, c in zip(bbox_gt, preds_gt):179        txt = str(c.item()) if classes is None else classes[c.item()]180        draw_rect(ax[0], [bbox[1],bbox[0],bbox[3],bbox[2]], text=f'{txt}')181def process_output(clas_pred, bbox_pred, anchors, detect_thresh=0.25):182    bbox_pred = activ_to_bbox(bbox_pred, anchors.to(clas_pred.device))183    clas_pred = torch.sigmoid(clas_pred)184    detect_mask = clas_pred.max(1)[0] > detect_thresh185    if np.array(detect_mask).max() == 0:186        return None, None, None187    bbox_pred, clas_pred = bbox_pred[detect_mask], clas_pred[detect_mask]188    bbox_pred = tlbr2cthw(torch.clamp(cthw2tlbr(bbox_pred), min=-1, max=1))189    scores, preds = clas_pred.max(1)190    return bbox_pred, scores, preds191def rescale_boxes(bboxes, t_sz: Tensor):192    bboxes[:, 2:] = bboxes[:, 2:] * t_sz / 2193    bboxes[:, :2] = (bboxes[:, :2] + 1) * t_sz / 2194    return bboxes195def show_anchors_on_images(data, anchors, figsize=(15,15)):196    all_boxes = []...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!!
