Best Python code snippet using fMBT_python
animate_network_detections.py
Source:animate_network_detections.py
1# -*- coding: utf-8 -*-2import matplotlib.pyplot as plt3import matplotlib.animation as animation4import numpy as np5import pandas as pd6def animateDetections(df,frameNames,xlim=(0,960), ylim=(0,540)):7 colors = ['b','g','r','k']#plt.cm.inferno(np.linspace(0.2,0.9,4))8 fig = plt.figure(figsize=(5,3))9# plt.tight_layout(pad=0)10 11 12 ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, \13 xlim=xlim,ylim=ylim)14 fig.set_tight_layout('tight')15# gttp = drawBBox((0,0,0,0),'none')16# 17# dettp = drawBBox((0,0,0,0),'none')18# 19# fp = drawBBox((0,0,0,0),'none')20# 21# fn = drawBBox((0,0,0,0),'none')22 def drawBBox(bbox,boxColor,label):23 x1,y1,x2,y2 = bbox24 ymin,ymax = ylim25 rect = plt.Rectangle((x1,ymax - y2), x2-x1, y2-y1,\26 ec=boxColor,lw=1,fc='none', label = label)27 ax.add_patch(rect)28 29 return rect30 31 32 def removePatches():33 for p in reversed(ax.patches):34 p.remove()35 36 37 def init():38 gttp = drawBBox((0,0,0,0),colors[0],'GT')39 dettp = drawBBox((0,0,0,0),colors[2],'TP')40 fp = drawBBox((0,0,0,0),colors[3],'FP')41 fn = drawBBox((0,0,0,0),colors[1],'FN')42 plt.legend(fontsize=10,ncol=4,loc='upper center', bbox_to_anchor=(0.5,1.15))43 44 return gttp,dettp,fp,fn45 46 def convertToBBox(data):47 if data is not np.nan:48 data = eval(data)49 else:50 data = None51 return data52 53 def animationStep(imageName):54 print(imageName)55 frameDF = df.loc[df['imageName'] == imageName, :]56 57 removePatches()58 59 gttp = drawBBox((0,0,0,0),'none','GT')60 dettp = drawBBox((0,0,0,0),'none','TP')61 fp = drawBBox((0,0,0,0),'none','FP')62 fn = drawBBox((0,0,0,0),'none','FN')63 64 for i in frameDF.index:65 gtBBox = convertToBBox(frameDF.loc[i,'GTBBox'])66 detBBox = convertToBBox(frameDF.loc[i,'DetBBox'])67 if int(frameDF.loc[i,'TP']) == 1:68 # true positive69 gttp = drawBBox(gtBBox,colors[0], 'GT')70 dettp = drawBBox(detBBox,colors[2], 'TP')71 elif int(frameDF.loc[i,'FP']) == 1:72 # false positive73 fp = drawBBox(detBBox,colors[3], 'FP')74 elif int(frameDF.loc[i,'FN']) == 1:75 # false negative76 fn = drawBBox(gtBBox,colors[1], 'FN')77 else:78 print('should not happen')79 80 return gttp,dettp,fp,fn81 ani = animation.FuncAnimation(fig,animationStep,frames=frameNames,blit=True,init_func=init)82 plt.close()83 return ani84def loadCSV(fileName):85 df = pd.read_csv(fileName,index_col=0)86 frameNames = sorted(list(set(df['imageName'])))87 return df,frameNames88if __name__ == '__main__':89 network = ['GOPR9027-mobilenet-124',\90 'GOPR9027-mobilenet-220',\91 'GOPR9027-yolov3-tiny-128',\92 'GOPR9027-yolov3-tiny-224']93 networksLogDF = pd.DataFrame(columns=['TP','FP','FN'])94 resultPath = '../videos/litter-recording/' 95 for n in network:96 fileName = resultPath + n +'/1r1c/analysis/logInfoDF.csv'97 df,frameNames = loadCSV(fileName)98 99 networksLogDF.loc[n.replace('GOPR9027-',''),:] = list(df.loc[:,'TP':'FN'].sum())100 101 102# ani = animateDetections(df,frameNames)103# ani.save(fileName.replace('logInfoDF.csv',n + '.mp4'), fps=50, dpi = 300)104# plt.close()...
imitate.py
Source:imitate.py
1import pandas as pd2from PIL import Image3import torch4from torchvision import transforms5from utils.data_utils import txt_to_bboxinfo, DrawBBox6from utils.bbox_utils import bbox_format_transform, bbox_normalization, convert_yolov1_label, reshape_bbox,convert_yolov1label_to_bbox7from utils.train_utils import getconfigparser89parser = getconfigparser('./config/config.cfg')10CLASSES = parser.get("dataset-config", 'classes').split(',')11df = pd.read_csv('./object.csv')1213resize = (448, 448) # 尺度åæ¢åç大å°14item = 12 # æ ·æ¬åºå·15transformer = transforms.Compose([16 transforms.Resize(resize),17 transforms.ToTensor(),18])1920# å¾ççå¤ç(reshape+totensor)21img_file = Image.open(df['path'][item]) # å¾çPIL对象22h, w = img_file.height, img_file.width23x_train = transformer(img_file)24# bboxå¤ç(reshape,format_trans,normalization)25bboxes_init = txt_to_bboxinfo(df['object_txt_path'][item]) # ä½ç½®ä¿¡æ¯ :format(xa,ya,xb,yb)26scale = (resize[0] / h, resize[1] / w)27bboxes_reshape = [reshape_bbox(bbox, scale) for bbox in bboxes_init]28# DrawBBox(img_file.resize(resize),bboxes_reshape,mode=1) # ç¨drawbboxå½æ°æ£éªä¸ä¸reshapeçbboxåå¾çï¼åç°æ²¡æé®é¢29bboxes_trans = [bbox_format_transform(bbox, mode=1) for bbox in bboxes_reshape]30# DrawBBox(img_file.resize(resize),grid_num=(7,7),bboxes=bboxes_trans, mode=2,fig_save_path='./test.jpg') # ç¨drawbboxå½æ°æ£éªä¸ä¸æ ¼å¼è½¬æ¢çbboxåå¾çï¼åç°æ²¡æé®é¢31bboxes_normal = [bbox_normalization(bbox, resize) for bbox in bboxes_trans] # å½ä¸åæ¯ä¸ºäºåå°è®¡ç®é¾åº¦å¹¶æ¹ä¾¿æ们åç»å°å
¶è½¬ä¸º(px,py,dw,dh)çæ ¼å¼32# # ç®åçbboxæ¯(dx,dy,dw,dh)ââdh,dwæçæ¯bboxçé¿å®½ç¸å¯¹äºå¾ççç¸å¯¹é¿åº¦,dx,dyåç33for i in range(len(bboxes_normal)):34 bboxes_normal[i][0] = CLASSES.index(bboxes_normal[i][0]) # æ ç¾æ°å¼å3536y_train = convert_yolov1_label(bboxes_normal) # (dx,dy,dw,dh) -> (px,py,dw,dh) # 缺ç¹æå¨ï¼å¤ä¸ªç©ä½ä¸å¿ç¹è½å¨åä¸ä¸ªç½æ ¼åªè½æ£æµä¸ä¸ªé®é¢37y_train = torch.Tensor(y_train)383940y_train = y_train.permute((2, 0, 1))4142# å°é¢æµå¼è¿è¡è½¬æ¢-å¼å§è§£ç 4344y_train = y_train.permute((1, 2, 0))4546bboxes_p = convert_yolov1label_to_bbox(y_train) # (px,py,dw,dh) -> (dx,dy,dw,dh)474849bboxes_p[:,0]=bboxes_p[:,0]*resize[1]50bboxes_p[:,1]=bboxes_p[:,1]*resize[0]51bboxes_p[:,2]=bboxes_p[:,2]*resize[1]52bboxes_p[:,3]=bboxes_p[:,3]*resize[0]5354bboxes_p_out=[]55for bbox in bboxes_p:56 if bbox[4] == 1:57 classlist=list(bbox[5:].numpy())58 idlist=[]59 for i in range(len(classlist)):60 if classlist[i]==1:61 idlist.append(i)62 bboxes_p_out.append(idlist[:1]+list(bbox[0:4].numpy()))
...
FrameAnalyzer.py
Source:FrameAnalyzer.py
...7 def __init__(self):8 self.preProcessor = PreProcessor()9 self.mainProcessor = MainProcessor()10 self.postProcessor = PostProcessor()11 self.drawbBox = drawBbox()12 13 def exec(self, frame):14 batch = self.preProcessor.exec(frame)15 # preProcessor return img16 pred = self.mainProcessor.exec(batch)17 # mainProcessor return batch18 # core mainProcessor has no-info19 bbox = self.postProcessor.exec(pred)20 # postProcessor return frame_box21 print(frame)22 drawBbox.exec(frame, bbox)23 #draw bbox with (frame, bbox)24 return bbox25
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!!