Brief Introduction to OpenGL in Python with PyOpenGL

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

The easiest way to install OpenGL using Python is through the pip package manager. ... GL import OpenGL.GLUT import OpenGL. SALogotypeArticlesLearnWorkwithUsSigninSignupPythonJavaScriptJavaHomeArticlesBriefIntroductiontoOpenGLinPythonwithPyOpenGLMuhammadJunaidKhalidIntroduction Inthistutorial,we'regoingtolearnhowtousePyOpenGLlibraryinPython.OpenGLisagraphicslibrarywhichissupportedbymultipleplatformsincludingWindows,Linux,andMacOS,andisavailableforuseinmultipleotherlanguagesaswell;however,thescopeofthispostwillbelimitedtoitsusageinthePythonprogramminglanguage. OpenGL,ascomparedtoothersimilargraphicslibraries,isfairlysimple.We'llstartwithsettingituponoursystem,followedbywritingasimpleexampledemonstratingtheusageofthelibrary. Installation TheeasiestwaytoinstallOpenGLusingPythonisthroughthepippackagemanager.Ifyouhavepipinstalledinyoursystem,runthefollowingcommandtodownloadandinstallOpenGL: $pipinstallPyOpenGLPyOpenGL_accelerate I'drecommendcopyingtheabovecommandtohelpavoidtypos. Oncethiscommandfinishesexecution,iftheinstallationissuccessful,youshouldgetthefollowingoutputattheend: SuccessfullyinstalledPyOpenGL-3.1.0PyOpenGL-accelerate-3.1.0 Ifthisdoesn'twork,youcanalsodownloaditmanually.Forthat,thislink,scrolldowntothe'downloadingandinstallation'heading,anddownloadallthefilesoverthere.Afterthat,navigatetothefolderwhereyoudownloadedthosefiles,andrunthefollowingcommandintheterminalorcommandprompt: $pythonsetup.py ItispertinenttomentionthatyourequireVisualC++14.0buildtoolsinstalledonyoursysteminordertoworkwithOpenGLlibrariesinPython. NowthatwehavesuccessfullyinstalledOpenGLonoursystem,let'sgetourhandsdirtywithit. CodingExercise ThefirstthingweneedtodotouseOpenGLinourcodeistoimportit.Todothat,runthefollowingcommand: importOpenGL Beforeweproceed,thereareafewotherlibrariesthatyouneedtoimportwheneveryouintendtousethislibraryinyourprogram.Belowisthecodeforthoseimports: importOpenGL.GL importOpenGL.GLUT importOpenGL.GLU print("Importssuccessful!")#Ifyouseethisprintedtotheconsoletheninstallationwassuccessful Nowthatwearedonewiththenecessaryimports,let'sfirstcreateawindowinwhichourgraphicswillbeshown.Thecodeforthatisgivenbelow,alongwithitsexplanationinthecomments: defshowScreen(): glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)#Removeeverythingfromscreen(i.e.displaysallwhite) glutInit()#Initializeaglutinstancewhichwillallowustocustomizeourwindow glutInitDisplayMode(GLUT_RGBA)#Setthedisplaymodetobecolored glutInitWindowSize(500,500)#Setthewidthandheightofyourwindow glutInitWindowPosition(0,0)#Setthepositionatwhichthiswindowsshouldappear wind=glutCreateWindow("OpenGLCodingPractice")#Giveyourwindowatitle glutDisplayFunc(showScreen)#TellOpenGLtocalltheshowScreenmethodcontinuously glutIdleFunc(showScreen)#DrawanygraphicsorshapesintheshowScreenfunctionatalltimes glutMainLoop()#Keepsthewindowcreatedabovedisplaying/runninginaloop Copytheimportsabove,aswellasthiscodeinasinglepython(.py)file,andexecuteit.Youshouldseeawhitesquaredimensionscreenpopup.Now,ifwewishtodrawanyshapesormakeanyotherkindofgraphics,weneedtodothatinour"showScreen"function. Let'snowtrytomakeasquareusingOpenGL,butbeforewedoweneedtounderstandthecoordinatesystemthatOpenGLfollows. The(0,0)pointisthebottomleftofyourwindow,ifyougoupfromthere,you'removingalongthey-axis,andifyougorightfromthere,you'removingalongthex-axis.So,thetopleftpointofyourwindowwouldbe(0,500),toprightwouldbe(500,500),bottomrightwouldbe(500,0). Note:We'retalkingaboutthewindowwecreatedabove,whichhadadimensionof500x500inourexample,andnotyourcomputer'sfullscreen. Nowthatwe'vegotthatoutoftheway,letscodeasquare.Theexplanationtothecodecanbefoundinthecomments. fromOpenGL.GLimport* fromOpenGL.GLUTimport* fromOpenGL.GLUimport* w,h=500,500 #---Section1--- defsquare(): #Wehavetodeclarethepointsinthissequence:bottomleft,bottomright,topright,topleft glBegin(GL_QUADS)#Beginthesketch glVertex2f(100,100)#Coordinatesforthebottomleftpoint glVertex2f(200,100)#Coordinatesforthebottomrightpoint glVertex2f(200,200)#Coordinatesforthetoprightpoint glVertex2f(100,200)#Coordinatesforthetopleftpoint glEnd()#Marktheendofdrawing #Thisaloneisn'tenoughtodrawoursquare #---Section2--- defshowScreen(): glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)#Removeeverythingfromscreen(i.e.displaysallwhite) glLoadIdentity()#Resetallgraphic/shape'sposition square()#Drawasquareusingourfunction glutSwapBuffers() #---Section3--- glutInit() glutInitDisplayMode(GLUT_RGBA)#Setthedisplaymodetobecolored glutInitWindowSize(500,500)#Setthewandhofyourwindow glutInitWindowPosition(0,0)#Setthepositionatwhichthiswindowsshouldappear wind=glutCreateWindow("OpenGLCodingPractice")#Setawindowtitle glutDisplayFunc(showScreen) glutIdleFunc(showScreen)#Keepsthewindowopen glutMainLoop()#Keepstheabovecreatedwindowdisplaying/runninginaloop Runningthecodeabovewoulddrawasquare,butthatsquarewouldnotbevisiblesinceit'scolorwouldbethesameasthecolorofourwindow,soweneedtoassignitadifferentcoloraswell,forthatwewillmakesomechangesin"Section2"ofthecodeabovei.e.theshowScreenfunction.AddthefollowinglinebelowtheglLoadIdentitystatementandabovethesquare()statement: glColor3f(1.0,0.0,3.0)#Setthecolortopink However,ourcodeisstillnotcomplete.Whatitcurrentlydoesisdrawthesquareonce,andthenclearthescreenagain.Wedon'twantthat.Actually,wewon'tevenbeabletospotthemomentwhenitactuallydrawsthesquarebecauseitwouldappearanddisappearinasplitsecond.Letswriteanotherfunctiontoavoidthis. #AddthisfunctionbeforeSection2ofthecodeabovei.e.theshowScreenfunction defiterate(): glViewport(0,0,500,500) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0,500,0.0,500,0.0,1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() Callthisiteratefunctionin"Section2"ofthecodeabove.AdditbelowglLoadIdentityandabovetheglColor3dstatementintheshowScreenfunction. FreeeBook:GitEssentialsCheckoutourhands-on,practicalguidetolearningGit,withbest-practices,industry-acceptedstandards,andincludedcheatsheet.StopGooglingGitcommandsandactuallylearnit!DownloadtheeBook Let'snowcompileallthisintoasinglecodefilesothattherearenoambiguities: fromOpenGL.GLimport* fromOpenGL.GLUTimport* fromOpenGL.GLUimport* w,h=500,500 defsquare(): glBegin(GL_QUADS) glVertex2f(100,100) glVertex2f(200,100) glVertex2f(200,200) glVertex2f(100,200) glEnd() defiterate(): glViewport(0,0,500,500) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0,500,0.0,500,0.0,1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() defshowScreen(): glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glLoadIdentity() iterate() glColor3f(1.0,0.0,3.0) square() glutSwapBuffers() glutInit() glutInitDisplayMode(GLUT_RGBA) glutInitWindowSize(500,500) glutInitWindowPosition(0,0) wind=glutCreateWindow("OpenGLCodingPractice") glutDisplayFunc(showScreen) glutIdleFunc(showScreen) glutMainLoop() Whenyourunthis,awindowshouldappearwithapinkcoloredsquareboxinit. Output: Conclusion Inthistutorial,welearnedaboutOpenGL,howtodownloadandinstallit,followedbyusingitanashortexampleprogram.InthisexamplewealsopracticedmakingabasicshapeusingOpenGL,whichgaveusaninsightintosomecomplexfunctioncallsthatneedtobemadewheneverweneedtodrawsomethingusingthislibrary.Toconclude,OpenGLisveryresourcefulandgetsmoreandmorecomplexaswedivedeeperintoit. #python#openglLastUpdated:May17th,2019Wasthisarticlehelpful?Youmightalsolike...UnderstandingOpenGLthroughPythonAdvancedOpenGLinPythonwithPyGameandPyOpenGLHandlingUnixSignalsinPythonDon'tUseFlatten()-GlobalPoolingforCNNswithTensorFlowandKerasTheBestMachineLearningLibrariesinPythonImproveyourdevskills!Gettutorials,guides,anddevjobsinyourinbox.EmailaddressSignUpNospamever.Unsubscribeatanytime.ReadourPrivacyPolicy.MuhammadJunaidKhalidAuthorInthisarticleIntroductionInstallationCodingExerciseConclusionProjectReal-TimeRoadSignDetectionwithYOLOv5#python#machinelearning#computervision#pytorchIfyoudrive-there'sachanceyouenjoycruisingdowntheroad.Aresponsibledriverpaysattentiontotheroadsigns,andadjuststheir...DavidLandupDetailsProjectDataVisualizationinPython:TheCollatzConjecture#python#matplotlib#datavisualizationTheCollatzConjectureisanotoriousconjectureinmathematics.Aconjectureisaconclusionbasedonexistingevidence-however,aconjecturecannotbeproven....DetailsTwitterGitHubFacebook©2013-2022StackAbuse.Allrightsreserved.DisclosurePrivacyTermsDonotsharemyPersonalInformation.



請為這篇文章評分?