番茄系统家园 - 免费重装系统!简单装系统,人人都是装机大师!
当前位置:首页>Win7资讯 > pytorch框架yolov3算法训练自己数据集 利用yolov3训练自己的数据集

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

来源:番茄系统家园浏览:时间: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训练自己的数据集
  • 推荐系统

    • 雨林木风 winxp下载 纯净版 永久激活 winxp ghost系统 sp3 系统下载

      雨林木风 winxp下载 纯净版 永久激活 winxp ghost系统 sp3 系统下载64位
      系统大小:0MB系统类型:WinXP

      雨林木风在系统方面技术积累雄厚深耕多年,打造了国内重装系统行业知名品牌,雨林木风WindowsXP其系统口碑得到许多人认可,积累了广大的用户群体,是一款稳定流畅的系统,雨林木风 winxp下载 纯净版 永久激活 winxp ghost系统 sp3 系统下载,有需要的朋友速度下载吧。

      系统等级:
      进入下载 >
    • 萝卜家园win7纯净版 ghost系统下载 x64 联想电脑专用

      萝卜家园win7纯净版 ghost系统下载 x64 联想电脑专用64位
      系统大小:0MB系统类型:Win7

      萝卜家园win7纯净版是款非常纯净的win7系统,此版本优化更新了大量的驱动,帮助用户们进行舒适的使用,更加的适合家庭办公的使用,方便用户,有需要的用户们快来下载安装吧。

      系统等级:
      进入下载 >
    • 雨林木风xp系统 xp系统纯净版 winXP ghost xp sp3 纯净版系统下载

      雨林木风xp系统 xp系统纯净版 winXP ghost xp sp3 纯净版系统下载64位
      系统大小:1.01GB系统类型:WinXP

      雨林木风xp系统 xp系统纯净版 winXP ghost xp sp3 纯净版系统下载,雨林木风WinXP系统技术积累雄厚深耕多年,采用了新的系统功能和硬件驱动,可以更好的发挥系统的性能,优化了系统、驱动对硬件的加速,加固了系统安全策略,运行环境安全可靠稳定。

      系统等级:
      进入下载 >
    • 萝卜家园win10企业版 免激活密钥 激活工具 V2023 X64位系统下载

      萝卜家园win10企业版 免激活密钥 激活工具 V2023 X64位系统下载64位
      系统大小:0MB系统类型:Win10

      萝卜家园在系统方面技术积累雄厚深耕多年,打造了国内重装系统行业的萝卜家园品牌,(win10企业版,win10 ghost,win10镜像),萝卜家园win10企业版 免激活密钥 激活工具 ghost镜像 X64位系统下载,其系统口碑得到许多人认可,积累了广大的用户群体,萝卜家园win10纯净版是一款稳定流畅的系统,一直以来都以用户为中心,是由萝卜家园win10团队推出的萝卜家园

      系统等级:
      进入下载 >
    • 萝卜家园windows10游戏版 win10游戏专业版 V2023 X64位系统下载

      萝卜家园windows10游戏版 win10游戏专业版 V2023 X64位系统下载64位
      系统大小:0MB系统类型:Win10

      萝卜家园windows10游戏版 win10游戏专业版 ghost X64位 系统下载,萝卜家园在系统方面技术积累雄厚深耕多年,打造了国内重装系统行业的萝卜家园品牌,其系统口碑得到许多人认可,积累了广大的用户群体,萝卜家园win10纯净版是一款稳定流畅的系统,一直以来都以用户为中心,是由萝卜家园win10团队推出的萝卜家园win10国内镜像版,基于国内用户的习惯,做

      系统等级:
      进入下载 >
    • windows11下载 萝卜家园win11专业版 X64位 V2023官网下载

      windows11下载 萝卜家园win11专业版 X64位 V2023官网下载64位
      系统大小:0MB系统类型:Win11

      萝卜家园在系统方面技术积累雄厚深耕多年,windows11下载 萝卜家园win11专业版 X64位 官网正式版可以更好的发挥系统的性能,优化了系统、驱动对硬件的加速,使得软件在WINDOWS11系统中运行得更加流畅,加固了系统安全策略,WINDOWS11系统在家用办公上跑分表现都是非常优秀,完美的兼容各种硬件和软件,运行环境安全可靠稳定。

      系统等级:
      进入下载 >