openGL+open3d+python 鼠标拖动画矩形框选出点云数据的感兴趣区域代码
时间: 2023-07-14 13:12:16 浏览: 127
下面是一个使用OpenGL、Open3D和Python实现鼠标拖动画矩形框选出点云数据的感兴趣区域的代码示例:
```python
import open3d as o3d
from OpenGL.GL import *
from OpenGL.GLUT import *
import numpy as np
# 定义点云数据
pcd = o3d.io.read_point_cloud("pointcloud.ply")
# 定义全局变量
window_width = 800
window_height = 600
mouse_pressed = False
start_x, start_y = 0, 0
end_x, end_y = 0, 0
selected_points = []
def draw_rect(x1, y1, x2, y2):
# 绘制矩形框选区域
glColor3f(1.0, 1.0, 1.0)
glLineWidth(2.0)
glBegin(GL_LINE_LOOP)
glVertex2i(x1, y1)
glVertex2i(x2, y1)
glVertex2i(x2, y2)
glVertex2i(x1, y2)
glEnd()
def display():
# 显示函数
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glPointSize(2)
glBegin(GL_POINTS)
for i in range(len(pcd.points)):
glVertex3f(pcd.points[i][0], pcd.points[i][1], pcd.points[i][2])
glEnd()
draw_rect(start_x, start_y, end_x, end_y)
glutSwapBuffers()
def reshape(width, height):
# 窗口大小变化回调函数
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60.0, float(width)/float(height), 0.1, 1000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
gluLookAt(0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
def mouse(button, state, x, y):
# 鼠标事件回调函数
global mouse_pressed, start_x, start_y, end_x, end_y, selected_points
if button == GLUT_LEFT_BUTTON and state == GLUT_DOWN:
mouse_pressed = True
start_x, start_y = x, y
end_x, end_y = x, y
elif button == GLUT_LEFT_BUTTON and state == GLUT_UP:
mouse_pressed = False
selected_points = []
# 将选中的点云数据加入selected_points列表
for i in range(len(pcd.points)):
if pcd.points[i][0] > min(start_x, end_x) and pcd.points[i][0] < max(start_x, end_x) and \
pcd.points[i][1] > min(window_height - start_y, window_height - end_y) and pcd.points[i][1] < max(window_height - start_y, window_height - end_y):
selected_points.append(i)
elif button == GLUT_RIGHT_BUTTON and state == GLUT_DOWN:
# 右键清空选择
selected_points = []
def motion(x, y):
# 鼠标移动事件回调函数
global end_x, end_y
end_x, end_y = x, y
def main():
glutInit()
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(window_width, window_height)
glutCreateWindow(b"OpenGL Python")
glutDisplayFunc(display)
glutReshapeFunc(reshape)
glutMouseFunc(mouse)
glutMotionFunc(motion)
glEnable(GL_DEPTH_TEST)
glClearColor(0.0, 0.0, 0.0, 0.0)
glutMainLoop()
if __name__ == '__main__':
main()
```
在这个示例代码中,我们首先使用Open3D库读取点云数据,然后使用OpenGL和PyOpenGL库进行可视化。我们定义了全局变量`selected_points`,用于保存框选后的点云数据。当鼠标左键按下时,我们记录下起始位置`start_x`和`start_y`,并在`motion`函数中更新结束位置`end_x`和`end_y`。当鼠标左键释放时,我们遍历所有点云数据,将在矩形框选区域内的点加入`selected_points`列表中。当鼠标右键按下时,我们清空`selected_points`列表。
注意,在矩形框选区域内的点的判断中,我们使用了OpenGL坐标系,而不是窗口坐标系。OpenGL坐标系的原点在窗口中心,x轴向右,y轴向上。因此,当判断点在矩形框选区域内时,需要将y坐标转换为窗口坐标系下的坐标。
阅读全文