You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PyQtGraph将图像纹理映射到球体网格上?

在PyQtGraph中为球体网格添加纹理映射

PyQtGraph完全支持将PNG/JPG图像或RGBA格式的numpy数组作为纹理映射到球体网格,无需依赖高顶点数的顶点颜色方案。核心是给MeshData添加纹理坐标,并为GLMeshItem指定纹理资源,具体实现步骤如下:

关键实现步骤

  • 生成纹理坐标:将球体顶点的3D坐标转换为UV纹理坐标(U对应水平方向,V对应垂直方向)
  • 加载纹理资源:可以从本地图片文件加载,或直接使用RGBA格式的numpy.ndarray转换为Qt纹理对象
  • 配置网格项:将纹理坐标绑定到MeshData,并为GLMeshItem设置texture参数

完整代码示例

import pyqtgraph as pg
import pyqtgraph.opengl as gl
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np

app = pg.mkQApp("GL Sphere Texture Example")
w = gl.GLViewWidget()
w.show()
w.setWindowTitle('pyqtgraph: Textured Sphere')
w.setCameraPosition(distance=4)

# 创建球体网格数据
md = gl.MeshData.sphere(rows=64, cols=128)

# --------------------------
# 步骤1:生成纹理坐标
# --------------------------
vertices = md.vertices()
r = np.sqrt(vertices[:,0]**2 + vertices[:,1]**2 + vertices[:,2]**2)
theta = np.arctan2(vertices[:,1], vertices[:,0])  # 方位角,范围[-π, π]
phi = np.arccos(vertices[:,2]/r)                  # 极角,范围[0, π]

# 将角度转换为UV坐标(0~1范围)
u = (theta + np.pi) / (2 * np.pi)
v = phi / np.pi
tex_coords = np.column_stack((u, v))
md.setTexCoords(tex_coords)

# --------------------------
# 步骤2:加载纹理(二选一即可)
# 选项A:从本地图片文件加载
# --------------------------
texture = QtGui.QImage("earth_map.png")
# 确保图片格式兼容,转换为RGBA如果需要
if texture.format() != QtGui.QImage.Format_RGBA8888:
    texture = texture.convertToFormat(QtGui.QImage.Format_RGBA8888)

# --------------------------
# 选项B:使用RGBA格式的numpy数组作为纹理
# --------------------------
# 示例:生成一个简单的渐变纹理(替换为你的实际数据)
# tex_width, tex_height = 512, 256
# texture_data = np.zeros((tex_height, tex_width, 4), dtype=np.uint8)
# texture_data[:, :, 0] = np.linspace(0, 255, tex_width)  # R通道渐变
# texture_data[:, :, 3] = 255  # 不透明
# texture = QtGui.QImage(texture_data.data, tex_width, tex_height, QtGui.QImage.Format_RGBA8888)

# --------------------------
# 步骤3:创建带纹理的网格项
# --------------------------
mesh_item = gl.GLMeshItem(
    meshdata=md,
    smooth=True,  # 开启平滑着色,让纹理过渡更自然
    texture=texture,
    shader='shaded'  # 使用带纹理的着色器
)
w.addItem(mesh_item)

if __name__ == '__main__':
    pg.exec()

关键细节说明

  • 纹理坐标计算:通过球面坐标转换得到的UV坐标,能保证地球纹理正确贴合球体,不会出现拉伸变形
  • 纹理格式:必须使用RGBA格式的QImage,PyQtGraph的GL纹理系统默认支持该格式
  • 着色器选择:使用shaded着色器可以同时保留光照效果和纹理显示,若不需要光照可改用plain着色器

内容的提问来源于stack exchange,提问作者nvaytet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 21:37:27