番茄系統(tǒng)家園 - 免費重裝系統(tǒng)!簡單裝系統(tǒng),人人都是裝機大師!
當(dāng)前位置:首頁>Win7資訊 > pytorch框架yolov3算法訓(xùn)練自己數(shù)據(jù)集 利用yolov3訓(xùn)練自己的數(shù)據(jù)集

pytorch框架yolov3算法訓(xùn)練自己數(shù)據(jù)集 利用yolov3訓(xùn)練自己的數(shù)據(jù)集

來源:番茄系統(tǒng)家園瀏覽:時間:2021-08-14 21:10:18

pytorch框架yolov3算法训练自己数据集 利用yolov3训练自己的数据集

4.测试图片和视频.

--

***(cfg,,,,#inputfolderoutputoutput,#outputfolderfourccmp4v,img_size416,conf_thres0.5,nms_thres0.5,save_txtFalse,save_imagesTrue,webcamFalse):devicetorch_utils.select_device()ifos.path.exists(output):shutil.rmtree(output)#deleteoutputfolderos.makedirs(output)#makenewoutputfolder#InitializemodelifONNX_EXPORT:s(320,192)#onnxmodelimagesize(height,width)modelDarknet(cfg,s)else:modelDarknet(cfg,img_size)#Loadweightsifweights.endswith(.pt):#pytorchformatmodel.load_state_dict(torch.load(weights,map_locationdevice)[model])else:#darknetformat_load_darknet_weights(model,weights)#FuseConv2dBatchNorm2dlayersmodel.fuse()#Evalmodemodel.to(device).eval()ifONNX_EXPORT:imgtorch.zeros((1,3,s[0],s[1]))torch.onnx.export(model,img,weights/export.onnx,verboseTrue)return#SetDataloadervid_path,vid_writerNone,Noneifwebcam:save_imagesTruedataloaderLoadWebcam(img_sizeimg_size)else:dataloaderLoadImages(images,img_sizeimg_size)#Getclassesandcolorsclassesload_classes(parse_data_cfg(data_cfg)[names])colors[[random.randint(0,255)for_inrange(3)]for_inrange(len(classes))]fori,(path,img,im0,vid_cap)inenumerate(dataloader):ttime.time()save_pathstr(Path(output)/Path(path).name)#Getdetectionsimgtorch.from_numpy(img).unsqueeze(0).to(device)pred,_model(img)detnon_max_suppression(pred,conf_thres,nms_thres)[0]ifdetisnotNoneandlen(det)0:#Rescaleboxesfrom416totrueimagesizedet[:,:4]scale_coords(img.shape[2:],det[:,:4],im0.shape).round()#Printresultstoscreenprint(%gx%g%img.shape[2:],end)#printimagesizeforcindet[:,-1].unique():n(det[:,-1]c).sum()print(%g%ss%(n,classes[int(c)]),end,)#Drawboundingboxesandlabelsofdetectionsfor*xyxy,conf,cls_conf,clsindet:ifsave_txt:#Writetofilewithopen(save_path.txt,a)asfile:file.write((%g*6

)%(*xyxy,cls,conf))#Addbboxtotheimagelabel%s%.2f%(classes[int(cls)],conf)plot_one_box(xyxy,im0,labellabel,colorcolors[int(cls)])print(Done.(%.3fs)%(time.time()-t))ifwebcam:#Showlivewebcamcv2.imshow(weights,im0)ifsave_images:#Saveimagewithdetectionsifdataloader.modeimages:cv2.imwrite(save_path,im0)else:ifvid_path!save_path:#newvideovid_pathsave_pathifisinstance(vid_writer,cv2.VideoWriter):vid_writer.release()#releasepreviousvideowriterfpsvid_cap.get(cv2.CAP_PROP_FPS)widthint(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))heightint(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))vid_writercv2.VideoWriter(save_path,cv2.VideoWriter_fourcc(*fourcc),fps,(width,height))vid_writer.write(im0)ifsave_images:print(Resultssavedto%s%os.getcwd()os.sepoutput)ifplatformdarwin:#macosos.system(openoutputsave_path)if__name____main__:parserargparse.ArgumentParser()parser.add_argument(--cfg,typestr,defaultcfg/yolov3-tiny.cfg,helpcfgfilepath)parser.add_argument(--data-cfg,typestr,defaultdata/mask.data,helpcoco.datafilepath)parser.add_argument(--weights,typestr,defaultweights/latest.pt,helppathtoweightsfile)parser.add_argument(--images,typestr,defaultdata/samples,helppathtoimages)parser.add_argument(--img-size,typeint,default416,helpinferencesize(pixels))parser.add_argument(--conf-thres,typefloat,default0.5,helpobjectconfidencethreshold)parser.add_argument(--nms-thres,typefloat,default0.5,helpiouthresholdfornon-maximumsuppression)parser.add_argument(--fourcc,typestr,defaultmp4v,helpspecifiesthefourcccodeforoutputvideoencoding(makesureffmpegsupportsspecifiedfourcccodec))parser.add_argument(--output,typestr,defaultoutput,helpspecifiestheoutputpathforimagesandvideos)optparser.parse_args()print(opt)withtorch.no_grad():detect(opt.cfg,opt.data_cfg,opt.weights,imagesopt.images,img_sizeopt.img_size,conf_thresopt.conf_thres,nms_thresopt.nms_thres,fourccopt.fourcc,outputopt.output)

5.测试摄像头

把detect.py中的webcam改为False。此时会报错NoneType打开datasets.py文件

importglobimportmathimportosimportrandomimportshutilfrompathlibimportPathimportcv2importnumpyasnpimporttorchfromtorch.utils.dataimportDatasetfromtqdmimporttqdmfromproject.utilsimportxyxy2xywhclassLoadImages:#forinferencedef__init__(self,path,img_size416):self.heightimg_sizeimg_formats[.jpg,.jpeg,.png,.tif]vid_formats[.mov,.avi,.mp4]files[]ifos.path.isdir(path):filessorted(glob.glob(%s/*.*%path))elifos.path.isfile(path):files[path]images[xforxinfilesifos.path.splitext(x)[-1].lower()inimg_formats]videos[xforxinfilesifos.path.splitext(x)[-1].lower()invid_formats]nI,nVlen(images),len(videos)self.filesimagesvideosself.nFnInV#numberoffilesself.video_flag[False]*nI[True]*nVself.modeimagesifany(videos):self.new_video(videos[0])#newvideoelse:self.capNoneassertself.nF0,Noimagesorvideosfoundinpathdef__iter__(self):self.count0returnselfdef__next__(self):ifself.countself.nF:raiseStopIterationpathself.files[self.count]ifself.video_flag[self.count]:#Readvideoself.modevideoret_val,img0self.cap.read()ifnotret_val:self.count1self.cap.release()ifself.countself.nF:#lastvideoraiseStopIterationelse:pathself.files[self.count]self.new_video(path)ret_val,img0self.cap.read()self.frame1print(video%g/%g(%g/%g)%s:%(self.count1,self.nF,self.frame,self.nframes,path),end)else:#Readimageself.count1img0cv2.imread(path)#BGRassertimg0isnotNone,FileNotFoundpathprint(image%g/%g%s:%(self.count,self.nF,path),end)#Paddedresizeimg,_,_,_letterbox(img0,new_shapeself.height)#NormalizeRGBimgimg[:,:,::-1].transpose(2,0,1)#BGRtoRGBimgnp.ascontiguousarray(img,dtypenp.float32)#uint8tofloat32img/255.0#0-255to0.0-1.0#cv2.imwrite(path.letterbox.jpg,255*img.transpose((1,2,0))[:,:,::-1])#saveletterboximagereturnpath,img,img0,self.capdefnew_video(self,path):self.frame0self.capcv2.VideoCapture(path)#pathself.nframesint(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))def__len__(self):returnself.nF#numberoffilesclassLoadWebcam:#forinferencedef__init__(self,img_size416):vid_formats[.mov,.avi,.mp4]#64files[]#64self.camcv2.VideoCapture(0)self.heightimg_sizevideos[xforxinfilesifos.path.splitext(x)[-1].lower()invid_formats]#64self.modeimages#64ifany(videos):#64self.new_video(videos[0])#newvideo#64else:#64self.capNone#64def__iter__(self):self.count-1returnselfdef__next__(self):self.count1ifcv2.waitKey(1)27:#esctoquitcv2.destroyAllWindows()raiseStopIteration#Readimageret_val,img0self.cam.read()assertret_val,WebcamErrorimg_pathwebcam_%g.jpg%self.countimg0cv2.flip(img0,1)#flipleft-rightprint(webcam%g:%self.count,end)#Paddedresizeimg,_,_,_letterbox(img0,new_shapeself.height)#NormalizeRGBimgimg[:,:,::-1].transpose(2,0,1)#BGRtoRGBimgnp.ascontiguousarray(img,dtypenp.float32)#uint8tofloat32img/255.0#0-255to0.0-1.0returnimg_path,img,img0,Nonedef__len__(self):return0classLoadImagesAndLabels(Dataset):#fortraining/testingdef__init__(self,path,img_size416,batch_size16,augmentFalse,rectTrue,image_weightsFalse):withopen(path,r)asf:img_filesf.read().splitlines()self.img_fileslist(filter(lambdax:len(x)0,img_files))nlen(self.img_files)binp.floor(np.arange(n)/batch_size).astype(np.int)#batchindexnbbi[-1]1#numberofbatchesassertn0,Noimagesfoundin%s%pathself.nnself.batchbi#batchindexofimageself.img_sizeimg_sizeself.augmentaugmentself.image_weightsimage_weightsself.rectFalseifimage_weightselserectself.label_files[x.replace(images,labels).replace(.jpeg,.txt).replace(.jpg,.txt).replace(.bmp,.txt).replace(.png,.txt)forxinself.img_files]#RectangularTraininghttps://github.com/ultralytics/yolov3/issues/232ifself.rect:fromPILimportImage#Readimageshapes#spdataos.seppath.replace(.txt,.shapes).split(os.sep)[-1]#shapefilepath#spos.seppath.replace(.txt,.shapes).split(os.sep)[-1]#shapefilepathsppath.replace(.txt,shapes).split(os.sep)[-1]ifos.path.exists(sp):#readexistingshapefilewithopen(sp,r)asf:snp.array([x.split()forxinf.read().splitlines()],dtypenp.float32)assertlen(s)n,Shapefileoutofsync,pleasedelete%sandrerun%spelse:#noshapefile,soreadshapeusingPILandwriteshapefilefornexttime(faster)snp.array([Image.open(f).sizeforfintqdm(self.img_files,descReadingimageshapes)])np.savetxt(sp,s,fmt%g)#Sortbyaspectratioars[:,1]/s[:,0]#aspectratioiar.argsort()arar[i]self.img_files[self.img_files[i]foriini]self.label_files[self.label_files[i]foriini]#Settrainingimageshapesshapes[[1,1]]*nbforiinrange(nb):ariar[bii]mini,maxiari.min(),ari.max()ifmaxi1:shapes[i][maxi,1]elifmini1:shapes[i][1,1/mini]self.batch_shapesnp.ceil(np.array(shapes)*img_size/32.).astype(np.int)*32#Preloadlabels(requiredforweightedCEtraining)self.imgs[None]*nself.labels[np.zeros((0,5))]*nitertqdm(self.label_files,descReadinglabels)ifn1000elseself.label_filesfori,fileinenumerate(iter):try:withopen(file,r)asf:lnp.array([x.split()forxinf.read().splitlines()],dtypenp.float32)ifl.shape[0]:assertl.shape[1]5,5labelcolumns:%s%fileassert(l0).all(),negativelabels:%s%fileassert(l[:,1:]1).all(),non-normalizedoroutofboundscoordinatelabels:%s%fileself.labels[i]lexcept:pass#print(Warning:missinglabelsfor%s%self.img_files[i])#missinglabelfileassertlen(np.concatenate(self.labels,0))0,Nolabelsfound.Incorrectlabelpathsprovided.def__len__(self):returnlen(self.img_files)#def__iter__(self):#self.count-1#print(randatasetiter)#self.shuffled_vectornp.random.permutation(self.nF)ifself.augmentelsenp.arange(self.nF)#returnselfdef__getitem__(self,index):ifself.image_weights:indexself.indices[index]img_pathself.img_files[index]label_pathself.label_files[index]#Loadimageimgself.imgs[index]ifimgisNone:imgcv2.imread(img_path)#BGRassertimgisnotNone,FileNotFoundimg_pathifself.n1001:self.imgs[index]img#cacheimageintomemory#Augmentcolorspaceaugment_hsvTrueifself.augmentandaugment_hsv:#SVaugmentationby50%fraction0.50#mustbe1.0img_hsvcv2.cvtColor(img,cv2.COLOR_BGR2HSV)#hue,sat,valSimg_hsv[:,:,1].astype(np.float32)#saturationVimg_hsv[:,:,2].astype(np.float32)#valuea(random.random()*2-1)*fraction1b(random.random()*2-1)*fraction1S*aV*bimg_hsv[:,:,1]Sifa1elseS.clip(None,255)img_hsv[:,:,2]Vifb1elseV.clip(None,255)cv2.cvtColor(img_hsv,cv2.COLOR_HSV2BGR,dstimg)#Letterboxh,w,_img.shapeifself.rect:shapeself.batch_shapes[self.batch[index]]img,ratio,padw,padhletterbox(img,new_shapeshape,moderect)else:shapeself.img_sizeimg,ratio,padw,padhletterbox(img,new_shapeshape,modesquare)#Loadlabelslabels[]ifos.path.isfile(label_path):#withopen(label_path,r)asf:#xnp.array([x.split()forxinf.read().spl

相关阅读

  • 如何在win7下安装linux
  • sep writer win7
  • pytorch框架yolov3算法训练自己数据集 利用yolov3训练自己的数据集
  • 推薦系統(tǒng)

    • 雨林木風(fēng) winxp下載 純凈版 永久激活 winxp ghost系統(tǒng) sp3 系統(tǒng)下載

      雨林木風(fēng) winxp下載 純凈版 永久激活 winxp ghost系統(tǒng) sp3 系統(tǒng)下載64位
      系統(tǒng)大?。?/em>0MB系統(tǒng)類型:WinXP

      雨林木風(fēng)在系統(tǒng)方面技術(shù)積累雄厚深耕多年,打造了國內(nèi)重裝系統(tǒng)行業(yè)知名品牌,雨林木風(fēng)WindowsXP其系統(tǒng)口碑得到許多人認可,積累了廣大的用戶群體,是一款穩(wěn)定流暢的系統(tǒng),雨林木風(fēng) winxp下載 純凈版 永久激活 winxp ghost系統(tǒng) sp3 系統(tǒng)下載,有需要的朋友速度下載吧。

      系統(tǒng)等級:
      進入下載 >
    • 蘿卜家園win7純凈版 ghost系統(tǒng)下載 x64 聯(lián)想電腦專用

      蘿卜家園win7純凈版 ghost系統(tǒng)下載 x64 聯(lián)想電腦專用64位
      系統(tǒng)大小:0MB系統(tǒng)類型:Win7

      蘿卜家園win7純凈版是款非常純凈的win7系統(tǒng),此版本優(yōu)化更新了大量的驅(qū)動,幫助用戶們進行舒適的使用,更加的適合家庭辦公的使用,方便用戶,有需要的用戶們快來下載安裝吧。

      系統(tǒng)等級:
      進入下載 >
    • 雨林木風(fēng)xp系統(tǒng) xp系統(tǒng)純凈版 winXP ghost xp sp3 純凈版系統(tǒng)下載

      雨林木風(fēng)xp系統(tǒng) xp系統(tǒng)純凈版 winXP ghost xp sp3 純凈版系統(tǒng)下載64位
      系統(tǒng)大?。?/em>1.01GB系統(tǒng)類型:WinXP

      雨林木風(fēng)xp系統(tǒng) xp系統(tǒng)純凈版 winXP ghost xp sp3 純凈版系統(tǒng)下載,雨林木風(fēng)WinXP系統(tǒng)技術(shù)積累雄厚深耕多年,采用了新的系統(tǒng)功能和硬件驅(qū)動,可以更好的發(fā)揮系統(tǒng)的性能,優(yōu)化了系統(tǒng)、驅(qū)動對硬件的加速,加固了系統(tǒng)安全策略,運行環(huán)境安全可靠穩(wěn)定。

      系統(tǒng)等級:
      進入下載 >
    • 蘿卜家園win10企業(yè)版 免激活密鑰 激活工具 V2023 X64位系統(tǒng)下載

      蘿卜家園win10企業(yè)版 免激活密鑰 激活工具 V2023 X64位系統(tǒng)下載64位
      系統(tǒng)大小:0MB系統(tǒng)類型:Win10

      蘿卜家園在系統(tǒng)方面技術(shù)積累雄厚深耕多年,打造了國內(nèi)重裝系統(tǒng)行業(yè)的蘿卜家園品牌,(win10企業(yè)版,win10 ghost,win10鏡像),蘿卜家園win10企業(yè)版 免激活密鑰 激活工具 ghost鏡像 X64位系統(tǒng)下載,其系統(tǒng)口碑得到許多人認可,積累了廣大的用戶群體,蘿卜家園win10純凈版是一款穩(wěn)定流暢的系統(tǒng),一直以來都以用戶為中心,是由蘿卜家園win10團隊推出的蘿卜家園

      系統(tǒng)等級:
      進入下載 >
    • 蘿卜家園windows10游戲版 win10游戲?qū)I(yè)版 V2023 X64位系統(tǒng)下載

      蘿卜家園windows10游戲版 win10游戲?qū)I(yè)版 V2023 X64位系統(tǒng)下載64位
      系統(tǒng)大小:0MB系統(tǒng)類型:Win10

      蘿卜家園windows10游戲版 win10游戲?qū)I(yè)版 ghost X64位 系統(tǒng)下載,蘿卜家園在系統(tǒng)方面技術(shù)積累雄厚深耕多年,打造了國內(nèi)重裝系統(tǒng)行業(yè)的蘿卜家園品牌,其系統(tǒng)口碑得到許多人認可,積累了廣大的用戶群體,蘿卜家園win10純凈版是一款穩(wěn)定流暢的系統(tǒng),一直以來都以用戶為中心,是由蘿卜家園win10團隊推出的蘿卜家園win10國內(nèi)鏡像版,基于國內(nèi)用戶的習(xí)慣,做

      系統(tǒng)等級:
      進入下載 >
    • windows11下載 蘿卜家園win11專業(yè)版 X64位 V2023官網(wǎng)下載

      windows11下載 蘿卜家園win11專業(yè)版 X64位 V2023官網(wǎng)下載64位
      系統(tǒng)大小:0MB系統(tǒng)類型:Win11

      蘿卜家園在系統(tǒng)方面技術(shù)積累雄厚深耕多年,windows11下載 蘿卜家園win11專業(yè)版 X64位 官網(wǎng)正式版可以更好的發(fā)揮系統(tǒng)的性能,優(yōu)化了系統(tǒng)、驅(qū)動對硬件的加速,使得軟件在WINDOWS11系統(tǒng)中運行得更加流暢,加固了系統(tǒng)安全策略,WINDOWS11系統(tǒng)在家用辦公上跑分表現(xiàn)都是非常優(yōu)秀,完美的兼容各種硬件和軟件,運行環(huán)境安全可靠穩(wěn)定。

      系統(tǒng)等級:
      進入下載 >

    熱門系統(tǒng)

    常用系統(tǒng)