Brief Introduction to OpenGL in Python with PyOpenGL
文章推薦指數: 80 %
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.
延伸文章資訊
- 1PyOpenGL · PyPI
Standard OpenGL bindings for Python. ... GLU (normally available on any OpenGL-capable machine). ...
- 2一篇就够的超良心pyOpenGL入门教程,不香喷我! - CSDN博客
OpenGL (python版本)OpenGL是用于渲染2D、3D矢量图形的扩语言、跨平台的应用程序编程接口。这个接口由近350个不同的函数调用组成,用来从简单的图形 ...
- 3Python安裝設定OpenGL環境的全過程記錄 - IT145.com
下載與自己Python版本合適的,執行命令:pip install XXX.whl 即可正常使用pyopengl環境。 測試環境程式碼. from OpenGL.GL import * from...
- 4PyOpenGL:是一個呼叫OpenGL的2D/3D的python圖形庫
PyOpenGL:是一個呼叫OpenGL的2D/3D的python圖形庫. 3.1.2 程式碼 #匯入OpenGL的庫,一般常規匯入下面三個模組 #調出gl函式 from OpenGL.GL i...
- 5PyOpenGL -- The Python OpenGL Binding
PyOpenGL is the most common cross platform Python binding to OpenGL and related APIs. The binding...