pydcu/ueye.py at master - GitHub

文章推薦指數: 80 %
投票人數:10人

Python wrapper for Thorlabs DCU 200 series camera. ... print 'ueye.dll not found' ... used for ring buffering must have been allocated the same colour. Skiptocontent {{message}} wmpauli / pydcu Public forkedfrombernardokyotoku/pydcu Notifications Fork 3 Star 2 Code Pullrequests 0 Actions Projects 0 Wiki Security Insights More Code Pullrequests Actions Projects Wiki Security Insights Permalink master Branches Tags Couldnotloadbranches Nothingtoshow Loading {{refName}} default Couldnotloadtags Nothingtoshow {{refName}} default Loading pydcu/ueye.py / Jumpto Nodefinitionsfoundinthisfile. Gotofile Gotofile T Gotoline L Gotodefinition R Copypath Copypermalink     Cannotretrievecontributorsatthistime 965lines(828sloc) 35.5KB Raw Blame OpenwithDesktop Viewraw Viewblame ThisfilecontainsbidirectionalUnicodetextthatmaybeinterpretedorcompileddifferentlythanwhatappearsbelow.Toreview,openthefileinaneditorthatrevealshiddenUnicodecharacters. LearnmoreaboutbidirectionalUnicodecharacters Showhiddencharacters #Thisfileispartofpydcu. #pydcuisfreesoftware:youcanredistributeitand/ormodify #itunderthetermsoftheGNUGeneralPublicLicenseaspublishedby #theFreeSoftwareFoundation,eitherversion3oftheLicense,or #(atyouroption)anylaterversion. #pydcuisdistributedinthehopethatitwillbeuseful, #butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyof #MERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.Seethe #GNUGeneralPublicLicenseformoredetails. #YoushouldhavereceivedacopyoftheGNUGeneralPublicLicense #alongwithpydcu.Ifnot,see. importos importos.path fromos.pathimportexpanduser#todetermineuserhomedirectory importsys importtextwrap fromnumpyimportzeros,uint8,ctypeslib fromctypesimportbyref,c_int,create_string_buffer,c_char_p,cdll,util,c_void_p importIS importctypes importnumpyasnp importpdb importtime importcv2 importlogging SUCCESS=0 NO_SUCCESS=-1 INVALID_HANDLER=1 HANDLE=c_void_p HCAM=HANDLE HWND=c_void_p INT=c_int UINT=ctypes.c_uint DOUBLE=ctypes.c_double ifos.name=='nt': libname='ueye' include_ueye_h=os.environ['PROGRAMFILES']+'\\ThorlabsDCUcamera\\Develop\\Include\\ueye.h' ifos.name=='posix': libname='ueye_api' include_ueye_h="/usr/include/ueye.h" lib=util.find_library(libname) iflibisNone: print'ueye.dllnotfound' libueye=cdll.LoadLibrary(lib) logger=logging.getLogger() defCALL(name,*args): """ Callslibueyefunction"name"andarguments"args". """ funcname='is_'+name func=getattr(libueye,funcname) new_args=[] forainargs: ifisinstance(a,unicode): printname,'argument',a,'isunicode' new_args.append(str(a)) else: new_args.append(a) returnfunc(*new_args) defpair_gen(getXconst,getYconst): classpair(list): def__init__(self,args,camera): list.__init__(self,args) self.cam=camera @property defx(self): returnself[0] @x.setter defx(self,value): self[0]=value y=self.cam.SetImagePos(getYconst) self.cam.SetImagePos(value,y) @property defy(self): returnself[1] @y.setter defy(self,value): self[1]=value x=self.cam.SetImagePos(getXconst) self.cam.SetImagePos(x,value) returnpair pos_pair=pair_gen(IS.GET_IMAGE_POS_X,IS.GET_IMAGE_POS_Y) size_pair=pair_gen(IS.GET_IMAGE_SIZE_X,IS.GET_IMAGE_SIZE_Y) classimage(object): def__init__(self,camera): self.cam=camera @property defsize(self): x=self.cam.SetImageSize(x=IS.GET_IMAGE_SIZE_X) y=self.cam.SetImageSize(x=IS.GET_IMAGE_SIZE_Y) returnsize_pair([x,y],self.cam) @size.setter defsize(self,value): iflen(value)!=2: raiseException("Valuelennotequal2.") (width,height)=value ifwidthisNone: width=self.cam.SetImageSize(x=IS.GET_IMAGE_SIZE_X) ifheightisNone: height=self.cam.SetImageSize(x=IS.GET_IMAGE_SIZE_Y) self.cam.SetImageSize(x=width,y=height) @property defposition(self): x=self.cam.SetImagePos(IS.GET_IMAGE_POS_X) y=self.cam.SetImagePos(IS.GET_IMAGE_POS_Y) r=pos_pair([x,y],self.cam) returnr @position.setter defposition(self,value): iflen(value)!=2: raiseException("Valuelennotequal2.") (x,y)=value ifxisNone: x=self.cam.SetImagePos(IS.GET_IMAGE_POS_X) ifyisNone: y=self.cam.SetImagePos(IS.GET_IMAGE_POS_Y) self.cam.SetImagePos(x,y) classpycam: def__init__(self,camera_id=0): self.cam=camera(camera_id) self.image=image(self.cam) self.cam.AllocImageMem() self.cam.SetImageMem() def__del__(self): self.cam.ExitCamera() defsnapshot(self,filename=None,param=75): self.cam.CaptureVideo(wait=IS.WAIT) self.cam.StopLiveVideo(wait=IS.WAIT) r=self.cam.SaveImage(filename) returnr defstart_capture(self): pass defstop_capture(self): pass classcamera(HCAM): def__init__(self,camera_id=0): HCAM.__init__(self,0) r=CALL('InitCamera',byref(self),HWND(0)) ifrisnotSUCCESS: raiseException("Error%d"%r) self.width=260 self.height=216 self.seq=0 #self.data=zeros((self.height,self.width),dtype=np.uint8) self.ctypes_data=(ctypes.c_int*(260*((8+1)/8+0)*216))() self.mem_buffer=ctypes.pythonapi.PyBuffer_FromMemory self.mem_buffer.restype=ctypes.py_object self.sizes=self.enum_sizes() self.sizes_menu=dict(zip([str(w)+"x"+str(h)forw,hinself.sizes],range(len(self.sizes)))) self.rates=self.enum_rates() self.rates_menu=dict(zip([str(float(d)/n)forn,dinself.rates],range(len(self.rates)))) fps=self.rates[2] try: self.current_rate_idx=self.rates.index(fps) exceptValueError: logger.warning("BuggyVideoCamera:Notallavailableratesareexposed.") self.current_rate_idx=0 returnNone defCheckForSuccessError(self,return_value): ifreturn_valueisnotSUCCESS: self.GetError() raiseException(self.error_message.value) returnSUCCESS defCheckForNoSuccessError(self,return_value): ifreturn_valueisNO_SUCCESS: self.GetError() raiseException(self.error_message.value) returnreturn_value defAddToSequence(self): """ AddToSequence()insertsimagememoryintotheimagememorylist, whichistobeusedforringbuffering.Theimagememoryhasto beallocatedwithAllocImageMem().Allimagememorywhichis usedforringbufferingmusthavebeenallocatedthesamecolour depth(i.e.bitsperpixel).Thenumberofimagememoriesfora sequence(nID)islimitedtotheintegervaluerange. """ self.seq+=1 r=CALL('AddToSequence',self,self.image,self.id) returnself.CheckForSuccessError(r) defClearSequence(self): """ ClearSequence()deletesallimagememoryfromthesequencelist thatwasinsertedwithAddToSequence().AfterClearSequence()no moreimagememoryisactive.Tomakeacertainpartoftheimage memoryactive,SetImageMem()andSetImageSize()havetobe executed. Nottested! """ r=CALL('ClearSequence',self) returnself.CheckForSuccessError(r) defLockSeqBuf(self,number): """ LockSeqBuf()canbeusedtodisabletheoverwritingoftheimage memorywithnewimagedata.Andthusitispossibletoprevent imageswhicharerequiredforfurtherprocessingfrombeing overwritten.Fullaccesstotheimagememoryisstillavailable. Onlyoneimagememorycanbedisabledatthesametime.To accesstheimagememoryusefunctionUnlockSeqBuf(). Nottested! """ r=CALL('LockSeqBuf',self,INT(number),self.image) returnself.CheckForSuccessError(r) defUnlockSeqBuf(self,number): """ WithUnlockSeqBuf()imageacquisitionisallowedinapreviously lockedimagememory.Theimagememoryisputtotheprevious positioninthesequencelist. """ r=CALL('UnlockSeqBuf',self,INT(number),self.image) returnself.CheckForSuccessError(r) defGetLastMemorySequence(self): """ ThefunctionGetLastMemorySequence()returnstheIDofthelast recordedsequenceinthememoryboard.Thisparametercanthen beusedincombinationwiththefunctionTransferImage()toread imagesoutofthecameramemory. Nomemoryboardtotestthis,Nottested! """ r=CALL('GetLastMemorySequence',self,byref(self.id)) returnself.CheckForSuccessError(r) defTransferImage(): """ Experimenttofindouthowitworks TransferImage(self,INTnMemID,INTseqID,INTimageNr,INTreserved) Notintheusermanual! Notimplemented! """ CALL('TransferImage',self,INT(),INT(),INT(),INT()) defTransferMemorySequence(): """ Experimenttofindouthowitworks TransferMemorySequence(HIDShf,INTseqID,INTStartNr,INTnCount,INTnSeqPos); Notintheusermanual! Notimplemented! """ pass defGetMemorySequenceWindow(self,id): """ ThefunctionGetMemorySequenceWindow()canbeusedtocheckthe windowsizeofaspecifiedmemoryboardsequence.Theassigned sequenceIDisrequiredasaparameter. Nottested! """ top=INT() left=INT() right=INT() bottom=INT() CALL('GetMemorySequenceWindow',self,INT(id),byref(left),byref(top),byref(right),byref(bottom)) return(left.value,top.value,right.value,bottom.value) defGetActSeqBuf(self): """ WithGetActSeqBuf()theimagememoryinwhichimageacquisition (ppcMem)iscurrentlytakingplaceandtheimagememorywhich waslastusedforimageacquisition(ppcMemLast)canbedeter- mined.Thisfunctionisonlyavailablewhentheringbufferis active.Ifimageacquisitionisstartedforaringbuffer, GetActSeqBufreturns0inpnNumaslongasdataisacquiredto thefirstimagememoryofthesequence.AndthuspnNumreceives thenumberofthesequenceimagememory,inwhichimageacqui- sitioniscurrentlytakingplace.ThenumberisnottheIDof theimagememorywhichisprovidedfromAllocImageMem(),butthe runningnumberinthesequenceasdefinedinAddToSequence(). """ aqID=INT() pcMem=c_char_p() pcMemLast=c_char_p() paqID=byref(aqID) ppcMem=byref(pcMem) ppcMemLast=byref(pcMemLast) r=CALL('GetActSeqBuf',self,paqID,ppcMem,ppcMemLast) returnself.CheckForSuccessError(r) defAllocImageMem(self,width=260,height=216,bitpixel=8): """ AllocImageMem()allocatesimagememoryforanimagewithwidth, widthandheight,heightandcolourdepthbitspixel.Memorysize isatleast: size=[width*((bitspixel+1)/8)+adjust]*height adjustseebelow Lineincrementsarecalculatedwith: line=width*[(bitspixel+1)/8] lineinc=line+adjust. adjust=0whenlinewithoutrestisdivisibleby4 adjust=4-rest(line/4) whenlinewithoutrestisnotdivisibleby4 ThelineincrementcanbereadwiththeGetImgMemPitch()func- tion.Thestartaddressintheimagememoryisreturnedwith ppcImgMem.pidcontainsanidentificationnumberofthealloc- atedmemory.Anewlyactivatedmemorylocationisnotdirectly activated.Inotherwords,imagesarenotdirectlydigitizedto thisnewmemorylocation.Beforethiscanhappen,thenewmemory locationhastobeactivatedwithSetImageMem().After SetImageMem()anSetImageSize()mustfollowsothattheimage conditionscanbetransferredtothenewlyactivatedmemory location.Thereturnedpointerhastobesavedandmaybe reused,asitisrequiredforallfurtherImageMemfunctions! ThefreeingofthememoryisachievedwithFreeImageMem().In theDirectDrawmodes,theallocationofanimagememoryisnot required! """ self.image=c_char_p() self.id=INT() r=CALL('AllocImageMem',self, INT(width), INT(height), INT(bitpixel), byref(self.image), byref(self.id)) returnself.CheckForSuccessError(r) defGetNumberOfMemoryImages(self): """ ThefunctionGetNumberOfMemoryImages()returnsthenumberof validimagesthatarecurrentlylocatedinthecameramemory withinthespecifiedsequenceID.Thisnumbercandifferfrom theoriginallyrecordednumberofimagesbecauseofoverwriting. Nottested! """ number=INT() r=CALL('GetNumberOfMemoryImages',self,INT(self.seq),byref(number)) returnself.CheckForSuccessError(r) defSetImageMem(self): """ SetImageMem()setstheallocatedimagememorytoactivememory. Onlyanactiveimagememorycanreceiveimagedata.After callingSetImageMem()functionSetImageSize()mustfollowtoset theimagesizeoftheactivememory.Apointerfromfunction AllocImgMem()hastobegiventoparameterpcImgMem. """ r=CALL("SetImageMem",self,self.image,self.id) returnself.CheckForSuccessError(r) defSetImageSize(self,x=IS.GET_IMAGE_SIZE_X_MAX,y=IS.GET_IMAGE_SIZE_Y_MAX):#non-zeroret """ Setstheimagesize. Ifxisconfigureto: IS.GET_IMAGE_SIZE_XRetrievalofcurrentwidth IS.GET_IMAGE_SIZE_X_MINSmallestvaluefortheAOIwidth IS.GET_IMAGE_SIZE_X_MAXLargestvaluefortheAOIwidth IS.GET_IMAGE_SIZE_X_INCIncrementfortheAOIwidth IS.GET_IMAGE_SIZE_YRetrievalofcurrentheight IS.GET_IMAGE_SIZE_Y_MINSmallestvaluefortheAOIheight IS.GET_IMAGE_SIZE_Y_MAXLargestvaluefortheAOIheight IS.GET_IMAGE_SIZE_Y_INCIncrementfortheAOIheight yisignoredandthespecifiedsizeisreturned. """ r=CALL("SetImageSize",self,INT(x),INT(y)) ifx&0x8000==0x8000: returnself.CheckForNoSuccessError(r) returnself.CheckForSuccessError(r) defGetImageSize(self):#,x=IS.GET_IMAGE_SIZE_X_MAX,y=IS.GET_IMAGE_SIZE_Y_MAX):#non-zeroret """ Setstheimagesize. Ifxisconfigureto: IS.GET_IMAGE_SIZE_XRetrievalofcurrentwidth IS.GET_IMAGE_SIZE_X_MINSmallestvaluefortheAOIwidth IS.GET_IMAGE_SIZE_X_MAXLargestvaluefortheAOIwidth IS.GET_IMAGE_SIZE_X_INCIncrementfortheAOIwidth IS.GET_IMAGE_SIZE_YRetrievalofcurrentheight IS.GET_IMAGE_SIZE_Y_MINSmallestvaluefortheAOIheight IS.GET_IMAGE_SIZE_Y_MAXLargestvaluefortheAOIheight IS.GET_IMAGE_SIZE_Y_INCIncrementfortheAOIheight yisignoredandthespecifiedsizeisreturned. """ width_c=ctypes.c_int(IS.GET_IMAGE_SIZE_X) height_c=ctypes.c_int(IS.GET_IMAGE_SIZE_Y) width=CALL("SetImageSize",self,width_c) height=CALL("SetImageSize",self,height_c) #ifr==0: return([width,height]) #else: #returnself.CheckForSuccessError(r) defFreeImageMem(self): """ FreeImageMem()deallocatespreviouslyallocatedimagememory.i ForpcImgMemoneofthepointersfromAllocImgMem()hastobe used.Allotherpointersleadtoanerrormessage!Therepeated handingoverofthesamepointersalsoleadstoanerrormessage """ r=CALL("FreeImageMem",self,self.image,self.id) returnself.CheckForSuccessError(r) defSetAllocatedImageMem(self,width=260,height=216,bitpixel=8): """ Setanallocatedmemory,thatwasnotallocatedusing AllocImageMem,tothedriversoitcanbeusedtostorethe imagethatwillbedegitized.Theallocatedmemorymustbe globallylocked. (Basically,usethisifsomenon-driverfunctionhappenstohave somememoryalreadyallocated,soyoudon'tneedtoallocatemore memory) NotImplemented! """ self.image=self.data.ctypes.data_as(c_char_p) self.id=INT() r=CALL('SetAllocatedImageMem',self, INT(width), INT(height), INT(bitpixel), self.data.ctypes.data, byref(self.id)) returnself.CheckForSuccessError(r) defGetActiveImageMem(self): """ GetActiveImageMem()returnsthepointertothebeginningandthe IDnumberoftheactivememory.IfDirectDrawmodeisactiveand imagememoryhasbeenallocated,thisfunctionreturnsthe pointerandtheIDoftheimagememory,whichwasactivatedwith SetImageMem().However,itshouldbenotedthatinDirectDraw mode,thismemoryisnotusedfordigitizing. AlsoseeGetImgMem(). Nottested! """ CALL('GetActiveImageMem',self,byref(self.image),byref(self.id)) defGetImageMem(self): """ GetImageMem()returnsthepointertothestartoftheactive imagememory.InDirectDrawmodethepointerisreturnedtothe backbuffer(orthevisiblearea-DirectDrawPrimarySurface mode). """ CALL('GetImageMem',self,byref(self.image)) defFreezeVideo(self,wait=IS.WAIT): CALL("FreezeVideo",self,INT(wait)) defCopyImageMem(self): """ CopyImageMem()copiesthecontentsoftheimagememory,as describedispcSourceandnIDtotheareainmemory,which pcDestpointsto. """ r=CALL("CopyImageMem",self,self.image,self.id,byref(self.ctypes_data)) buffer=self.mem_buffer(self.ctypes_data,self.width*self.height) self.data=np.frombuffer(buffer,np.dtype('uint8')) self.data=np.reshape(self.data,[self.height,self.width]) returnself.CheckForSuccessError(r) defGetError(self): self.error=INT() self.error_message=c_char_p() returnCALL("GetError",self, byref(self.error), byref(self.error_message)) defSaveImage(self,filename): file=Noneiffilename==Noneelsec_char_p(filename) printfile r=CALL('SaveImage',self,file) returnself.CheckForSuccessError(r) defSaveImageEx(self,filename=None,format=IS.IMG_JPG,param=75): file=Noneiffilename==Noneelsec_char_p(filename) r=CALL('SaveImageEx',self,file,INT(format))#,INT(format),INT(param)) returnself.CheckForSuccessError(r) defSaveImageMemEx(self,file,type="jpg"): r=CALL('SaveImageMemEx',self,None) returnself.CheckForSuccessError(r) defSetImagePos(self,x=0,y=0): r=CALL("SetImagePos",self,INT(x),INT(y)) ifx&0x8000==0x8000: returnself.CheckForNoSuccessError(r) returnself.CheckForSuccessError(r) defCaptureVideo(self,wait=IS.DONT_WAIT): """ CaptureVideo()digitizesvideoimagesinrealtimeandtransfers theimagestothepreviouslyallocatedimagememory. AlternativelyifyouareusingDirectDrawtheimagescanbe transferredtothegraphicsboard.Theimageacquisition(DIB Mode)takesplaceinthememorywhichhasbeensetby SetImageMem()andAllocImageMem().GetImageMem()determines exactlywherethestartaddressinmemoryis.Incaseofring buffering,thenimageacquisitionloopsendlesslythroughall imagememeoriesaddedtothesequence. wait IS.DONT_WAITThisfunctionsynchronizestheimageacquisitionoftheV-SYNC,butreturnsimmediately. IS.WAITThisfunctionsynchronizestheimageacquisition oftheV-SYNCandonlythendoesreturn(i.e. waitsuntilimageacquisitionbegins) 10wait1sec.) """ r=CALL("CaptureVideo",self,INT(wait)) returnself.CheckForSuccessError(r) defLoadParameters(self): """LoadParameterFilesavedpreviouslywithueyedemo""" home_dir=expanduser("~") parameter_file=home_dir+'/UI154xLE-M_conf.ini' ifos.path.isfile(parameter_file): print"LoadingParamtersforCamera" r=CALL("LoadParameters",self,c_char_p(parameter_file)) printr else: print"FilenotFound:%s"%parameter_file returnFalse returnself.CheckForSuccessError(r) defSetColorMode(self,color_mode=IS.SET_CM_Y8): r=CALL("SetColorMode",self,INT(color_mode)) returnself.CheckForNoSuccessError(r) defSetSubSampling(self,mode=IS.SUBSAMPLING_DISABLE): r=CALL("SetSubSampling",self,INT(mode)) returnself.CheckForSuccessError(r) defStopLiveVideo(self,wait=IS.DONT_WAIT): """ TheStopLiveVideo()functionfreezestheimageintheVGAcard orinthePC'ssystemmemory.Thefunctioniscontrolledwith theparameterWait.Thefunctionhastwomodes:Usingthefirst mode,thefunctionimmediatelyreturnstothecallingfunction andgrabstheimageinthebackground.Inthesecondmodethe functionwaitsuntiltheimagehasbeencompletelyacquiredand onlythendoesthefunctionreturn. BytheuseofIS.FORCE_VIDEO_STOPasingleframerecordingwhich isstartedwithFreezeVideo(IS.DONT_WAIT)canbeterminated immediately. """ r=CALL("StopLiveVideo",self,INT(wait)) returnself.CheckForSuccessError(r) defExitCamera(self): r=CALL("ExitCamera",self) returnself.CheckForSuccessError(r) defReadEEPROM(self,offset=0,count=64): """ ThereisarewritableEEPROMinthecamerawhichservesasa smallmemory.Additionallytotheinformationwhichisstored intheEEPROM,64extrabytescanbewritten.Withthe ReadEEPROM()commandthecontentsofthese64bytescanberead. SeeWriteEEPROM. """ ifoffset+count>64: sys.stderr.write("offset+counttoobig,mustbesmallerorequal64") raise buffer=create_string_buffer(count) CALL('ReadEEPROM',self,INT(offset),buffer,INT(count)) returnbuffer.value defWriteEEPROM(self,content,offset=0): """ IntheDCUcamerathereisarewritableEEPROM,where64bytes ofinformationcanbewritten.WiththeReadEEPROM()function thecontentsofthis64byteblockcanberead. """ count=len(content) ifcount+offset>64: raiseException("Contenttolong") pcString=c_char_p(content) r=CALL('WriteEEPROM',self,INT(offset),pcString,INT(count)) returnself.CheckForSuccessError(r) defExposure(self,time): """ Setstheexposuretime(inms). """ IS_EXPOSURE_CMD_SET_EXPOSURE=12#thereisawholelisttoimplement TIME=DOUBLE(time) nSizeOfParam=8 CALL('Exposure',self, UINT(IS_EXPOSURE_CMD_SET_EXPOSURE), byref(TIME), UINT(nSizeOfParam)) defInquireImageMem(self): """ readsthepropertiesoftheallocatedimagememory. """ self.pnX=INT() self.pnY=INT() self.pnBits=INT() self.pnPitch=INT() CALL('InquireImageMem',self,self.image,self.id,byref(self.pnX),byref(self.pnY),byref(self.pnBits),byref(self.pnPitch)) defGetColorDepth(self): """ thecurrentVGAcardcoloursettingandreturnsthebitdepth(pnCol) andtherelatedcolourmode(pnColMode).Thecolourmodecanbedirectl passedtotheis_SetColorMode()function. """ self.pnCol=INT() self.pnColMode=INT() r=CALL('GetColorDepth',self,byref(self.pnCol),byref(self.pnColMode)) returnself.CheckForSuccessError(r) defSetAOI(self,isType=IS.SET_IMAGE_AOI,x=0,y=0,width=260,height=216): """ Withis_SetAOI()thesizeandpositionofanAOIcanbesetwithonecommandcall.Possible AOIare: -ImageAOI -AutoBrightnessAOI -AutoWhitebalanceAOI Theautoimageareasareusedforappropriateautofunctionality.Asdefaultvaluethewin- dowisalwaysmaximally,thusalwaysaslargeasthecurrentimageAOI. Keywordarguments: hf--Camerahandle Type-- IS_SET_IMAGE_AOI--SetImageAOI IS_GET_IMAGE_AOI--ReturnsthecurrentImageAOI IS_SET_AUTO_BRIGHT_AOI--SettheAutoFeatureAOIforAutoGainandAutoShutter IS_GET_AUTO_BRIGHT_AOI--ReturnscurrentaveragevalueoftheAOI IS_SET_AUTO_WB_AOI--SetAOIforAutoWhitebalance IS_GET_AUTO_WB_AOI--ReturnsthecurrentAutoWhitebalanceAOI pXPos--HorizontalpositionoftheAOI pYPos--VerticalpositiontheAOI pWidth--WidthoftheAOI pHeight--HeightoftheAOI """ logger.info("origAOIvals:%s,%s,%s,%s"%(x,y,width,height)) x=int(x/4)*4 y=int(y/4)*4 width=int(width/4)*4 height=int(height/4)*4 xPos_c=ctypes.c_int(x) yPos_c=ctypes.c_int(y) width_c=ctypes.c_int(width) height_c=ctypes.c_int(height) isType_c=ctypes.c_int(isType) logger.info("roundedAOIvals:%s,%s,%s,%s"%(x,y,width,height)) r=CALL('SetAOI',self,isType_c,byref(xPos_c),byref(yPos_c),byref(width_c),byref(height_c)) isType_c=ctypes.c_int(IS.SET_AUTO_BRIGHT_AOI) #r=CALL('SetAOI',self,isType_c,byref(xPos_c),byref(yPos_c),byref(width_c),byref(height_c)) #isType_c=ctypes.c_int(IS.SET_AUTO_WB_AOI) #r=CALL('SetAOI',self,isType_c,byref(xPos_c),byref(yPos_c),byref(width_c),byref(height_c)) self.roi=[0,0,height,width] self.t_roi=[y,x,y+height,x+width] ifr==0: return([xPos_c.value,yPos_c.value,width_c.value,height_c.value]) else: returnself.CheckForSuccessError(r) defGetAOI(self,isType=IS.GET_IMAGE_AOI,x=0,y=0,width=0,height=0): returnself.SetAOI(isType,x,y,width,height) defSetAutoParameter(self,isType=IS.SET_ENABLE_AUTO_SHUTTER,pval1=1,pval2=0): '''controlsAutoGain,AutoShutter,AutoFramerateandAutoWhitebalance functionality.Purposeoftheautofunctionsisittocontrolthecamera imageinitsaverage''' pval1_c=ctypes.c_double(pval1) pval2_c=ctypes.c_double(pval2) isType_c=ctypes.c_int(isType) r=CALL('SetAutoParameter',self,isType_c,byref(pval1_c),byref(pval2_c)) pval1=pval1_c.value pval2=pval2_c.value ret=dict() ret['status']=r ret['pval1']=pval1 ret['pval2']=pval2 returnret defenableAutoGain(self): r=self.SetAutoParameter(isType=IS.SET_ENABLE_AUTO_GAIN,pval1=1,pval2=0) returnr defenableAutoExposure(self): r=self.SetAutoParameter(isType=IS.SET_ENABLE_AUTO_SHUTTER,pval1=1,pval2=0) returnr defdisableAutoGain(self): r=self.SetAutoParameter(isType=IS.SET_ENABLE_AUTO_GAIN,pval1=0,pval2=0) returnr defdisableAutoExposure(self): r=self.SetAutoParameter(isType=IS.SET_ENABLE_AUTO_SHUTTER,pval1=0,pval2=0) returnr defenableAutoWhitebalance(self): '''notsupportedyetbythedriver''' r=self.SetAutoParameter(isType=IS.SET_ENABLE_AUTO_WHITEBALANCE,pval1=1,pval2=0) returnr defdisableAutoWhitebalance(self): '''notsupportedyetbythedriver''' r=self.SetAutoParameter(isType=IS.SET_ENABLE_AUTO_WHITEBALANCE,pval1=0,pval2=0) returnr defgetAutoGain(self): r=self.SetAutoParameter(isType=IS.GET_ENABLE_AUTO_GAIN,pval1=1,pval2=0) returnbool(r['pval1']) defgetAutoExposure(self): r=self.SetAutoParameter(isType=IS.GET_ENABLE_AUTO_SHUTTER,pval1=1,pval2=0) returnbool(r['pval1']) defsetAutoGain(self,enable): ifenable: returnself.enableAutoGain() else: returnself.disableAutoGain() defsetAutoExposure(self,enable): ifenable: returnself.enableAutoExposure() else: returnself.disableAutoExposure() deftoggleAutoParameters(self): r=self.enableAutoGain() r=self.enableAutoExposure() time.sleep(.2) r=self.disableAutoGain() r=self.disableAutoExposure() defSetFrameRate(self,fps=30): fps_c=ctypes.c_double(fps) new_fps_c=ctypes.c_double(0) r=CALL('SetFrameRate',self,fps_c,byref(new_fps_c)) ifr==0: returnnew_fps_c.value defGetFrameRate(self): returnself.SetFrameRate(fps=IS.GET_FRAMERATE) defenum_rates(self): rates=[] fornin[1000.0/25,1000.0/30,1000.0/60,1000.0/100,1000.0/200]: rates.append((n,1000.0)) returnrates defset_rate(self,fps): try: self.current_rate_idx=self.rates.index(fps) exceptValueError: logger.warning("BuggyVideoCamera:Notallavailableratesareexposed.") self.current_rate_idx=0 logger.info("newframerate"+str(fps[1]/fps[0])) returnself.SetFrameRate(fps[1]/fps[0]) defget_rate(self): returnself.GetFrameRate() defset_rate_idx(self,rate_id): new_rate=self.rates[rate_id] r=self.set_rate(new_rate) returnr defget_size(self): returnself.GetAOI() defset_size(self,isType=IS.SET_IMAGE_AOI,x=0,y=0,width=260,height=216): self.SetAOI() time.sleep(.2) self.CopyImageMem() self.init_frame=self.data.copy() r=self.SetAOI(isType=IS.SET_IMAGE_AOI,x=x,y=y,width=width,height=height) self.toggleAutoParameters() returnr defcleanup(self): self.StopLiveVideo() self.FreeImageMem() self.ExitCamera() defisOpened(self): returnTrue defenableEvent(self,event=IS.SET_EVENT_FRAME): which=ctypes.c_int(event) r=CALL('EnableEvent',self,which) defwaitForNewFrame(self): '''waituntilnewframeisavailable''' which=ctypes.c_int(IS.SET_EVENT_FRAME) timeout=ctypes.c_int(1000) r=CALL('WaitEvent',self,which,timeout) returnTrue defread(self): """ wrappertomakeanalogoustoopencvcall returnmostrecentframe """ self.waitForNewFrame() now=time.time() self.CopyImageMem() #frame=self.init_frame.copy() #frame[self.t_roi[0]:self.t_roi[2],self.t_roi[1]:self.t_roi[3]]=self.data[self.roi[0]:self.roi[2],self.roi[1]:self.roi[3]] frame=cv2.cvtColor(self.data,cv2.COLOR_GRAY2RGB) returnFrame(now,frame)#self.init_frame) defenum_sizes(self): return([(260,216)]) #defset_exposure_time(self,exp): #'''setexposuretimeofcamera''' #new_exp=ctypes.c_double(0) #exp=ctypes.c_double(exp) #r=CALL('SetExposureTime',self,exp,byref(new_exp)) #ifrisSUCCESS: #returnnew_exp.value #else: #return-1 defset_exposure_time(self,exp): '''setexposuretimeofcamera''' new_exp=ctypes.c_double(0) exp=ctypes.c_double(exp) r=CALL('SetExposureTime',self,exp,byref(new_exp)) ifrisSUCCESS: returnnew_exp.value else: return0 defget_exposure_time(self): '''setexposuretimeofcamera''' new_exp=ctypes.c_double(0) exp=ctypes.c_double(IS.GET_EXPOSURE_TIME) r=CALL('SetExposureTime',self,exp,byref(new_exp)) ifrisSUCCESS: returnnew_exp.value else: return0 defset_contrast(self,cont): '''setcontrastfrom0-200%''' cont=int(cont) cont=max(0,cont) cont=min(511,cont) cont=ctypes.c_int(cont) r=CALL('SetContrast',self,cont) ifrisSUCCESS: returnTrue else: returnFalse defget_contrast(self): r=CALL('SetContrast',self,IS.GET_CONTRAST) returnr defget_gain_boost(self,mode=IS.GET_GAINBOOST): r=CALL('SetGainBoost',self,mode) ifr==IS.SET_GAINBOOST_ON: returnTrue else: returnFalse defset_gain_boost(self,enable=True): ifenable: r=CALL('SetGainBoost',self,IS.SET_GAINBOOST_ON) else: r=CALL('SetGainBoost',self,IS.SET_GAINBOOST_OFF) ifr==IS.SET_GAINBOOST_ON: returnTrue else: returnFalse defset_hardware_gain(self,nMaster): nMaster=ctypes.c_int(nMaster) ignore_me=ctypes.c_double(IS.IGNORE_PARAMETER) r=CALL('SetHardwareGain',self,nMaster,ignore_me,ignore_me,ignore_me) ifrisSUCCESS: returnTrue else: returnFalse defget_hardware_gain(self): r=CALL('SetHardwareGain',self,IS.GET_MASTER_GAIN) returnr defset_brightness(self,bright): '''setbrightnessfrom0-200%''' bright=max(0,bright) bright=min(255,bright) bright=ctypes.c_int(bright) r=CALL('SetBrightness',self,bright) ifrisSUCCESS: returnTrue else: returnFalse defget_brightness(self): r=CALL('SetBrightness',self,IS.GET_BRIGHTNESS) returnr classFrame(object): """docstringforFrame""" def__init__(self,timestamp,img,compressed_img=None,compressed_pix_fmt=None): self.timestamp=timestamp self.img=img self.compressed_img=compressed_img self.compressed_pix_fmt=compressed_pix_fmt Copylines Copypermalink Viewgitblame Go Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?