python OpenGL导入obj模型
时间: 2023-05-20 12:02:46 浏览: 263
可以使用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, 'r') 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()
```
其中load_obj函数用于读取obj文件,draw_obj函数用于绘制obj模型。在display函数中调用draw_obj函数即可绘制模型。
阅读全文