python OpenGL导入obj模型
时间: 2023-05-20 14:02:56 浏览: 118
opengl加载obj模型
可以使用PyOpenGL库来导入obj模型,具体代码如下:
```python
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy as np
def load_obj(filename):
vertices = []
normals = []
faces = []
with open(filename) as f:
for line in f:
if line.startswith('#'):
continue
values = line.split()
if not values:
continue
if values[0] == 'v':
vertices.append(list(map(float, values[1:4])))
elif values[0] == 'vn':
normals.append(list(map(float, values[1:4])))
elif values[0] == 'f':
face = []
for v in values[1:]:
w = v.split('/')
face.append(int(w[0]))
faces.append(face)
return vertices, normals, faces
def draw_obj(filename):
vertices, normals, faces = load_obj(filename)
glBegin(GL_TRIANGLES)
for face in faces:
for i in range(3):
glVertex3fv(vertices[face[i]-1])
glNormal3fv(normals[face[i]-1])
glEnd()
def display():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)
glColor3f(1, 1, 1)
draw_obj('model.obj')
glutSwapBuffers()
glutInit()
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(640, 480)
glutCreateWindow(b"OpenGL Window")
glutDisplayFunc(display)
glEnable(GL_DEPTH_TEST)
glutMainLoop()
```
这段代码使用PyOpenGL库加载obj模型,并在OpenGL窗口中绘制出来。你只需要将模型文件名改为你自己的obj模型文件名即可。
阅读全文