Python에서 3D 모델을 다운로드하는 방법
Aspose.3D FOSS for Python은 원주민 의존성 없이 3D 파일을 열기 위한 간단한 API를 제공합니다. Scene 개체, 당신은 노드 히어로를 걸어서 장면의 각 메시지에 대한 원료 지질 데이터를 읽을 수 있습니다.
단계별 가이드
단계 1 : 패키지를 설치합니다.
PyPI에서 Aspose.3D FOSS를 설치합니다. 추가 시스템 라이브러리가 필요하지 않습니다.
asposefoss/3d is not yet published — build from source until it ships. See the project README for build instructions.
지원되는 Python 버전: 3.7, 3.8, 3.9, 3.10, 3.11, 3.12.
단계 2 : 장면 클래스를 가져오기
그들의 Scene 클래스는 모든 3D 데이터를위한 최고 수준의 컨테이너입니다.당신이 필요로하는 모든 로드 옵션 클럽과 함께 가져오십시오.
from aspose.threed import Scene
from aspose.threed.formats import ObjLoadOptions모든 공공 클래스가 살아있다. aspose.threed 팩스 하드웨어 (Subpackage)aspose.threed.entities, aspose.threed.formats, aspose.threed.utilities).
단계 3 : 파일을 업로드합니다.
스테이크를 사용하십시오. Scene.from_file() 도서관은 지원되는 형식을 열 수 있습니다.이 도서는 파일 확장에서 자동으로 형식을 감지합니다.
##Automatic format detection
scene = Scene.from_file("model.obj")대체로, A를 만들기 위해서 Scene 과 전화 open();• 충전 옵션을 통과하거나 오류를 명시적으로 처리하려는 경우에 유용합니다 :
scene = Scene()
scene.open("model.obj")두 방법 모두 OBJ, STL (비나리 및 ASCII), glTF 2.0 / GLB, COLLADA (DAE) 및 3MF 파일을 지원합니다.
단계 4 : 무대 노드를 통과합니다.
짐이 있는 장면은 나무의 Node 뿌리 잡힌 물체들에 대하여 scene.root_node.모든 노드를 찾기 위해 반복적으로 이터를 눌러:
from aspose.threed import Scene, Node
scene = Scene.from_file("model.obj")
def walk(node: Node, depth: int = 0) -> None:
indent = " " * depth
print(f"{indent}Node: {node.name!r}")
for child in node.child_nodes:
walk(child, depth + 1)
walk(scene.root_node)각각의 Node 0 또는 더 많이 옮길 수 있습니다. Entity 물건 (대사, 카메라, 빛) 확인하기 node.entities 무엇이 붙어 있는지 보게 되었습니다.
5단계: Vertex 및 Polygon 데이터에 액세스
노드의 본질을 삽입하여 Mesh 그리고 그것의 제어 포인트 (버텍스 위치)와 폴리곤 (얼굴 인덱스 목록을 읽으십시오 :
from aspose.threed import Scene
from aspose.threed.entities import Mesh
scene = Scene.from_file("model.obj")
for node in scene.root_node.child_nodes:
for entity in node.entities:
if isinstance(entity, Mesh):
mesh: Mesh = entity
print(f"Mesh '{node.name}': "
f"{len(mesh.control_points)} vertices, "
f"{len(mesh.polygons)} polygons")
# First vertex position
if mesh.control_points:
v = mesh.control_points[0]
print(f" First vertex: ({v.x:.4f}, {v.y:.4f}, {v.z:.4f})")
# First polygon face (list of control-point indices)
if mesh.polygons:
print(f" First polygon: {mesh.polygons[0]}")mesh.control_points 그것은 목록의 Vector4 물건을 위한; x, y, z 위치를 유지하고, 그리고 w 동일한 조율이 일반적으로 1.0입니다.
mesh.polygons 각 내부 목록은 한 얼굴에 대한 통제 포인트 지표의 주문 세트입니다.
단계 6: 형식 특정 충전 옵션을 적용합니다.
OBJ 파일이 어떻게 해석되는지에 대한 얇은 통제는, ObjLoadOptions 예를 들어, scene.open():
from aspose.threed import Scene
from aspose.threed.formats import ObjLoadOptions
options = ObjLoadOptions()
options.flip_coordinate_system = True # Convert right-hand Y-up to Z-up
options.scale = 0.01 # Convert centimetres to metres
options.enable_materials = True # Load .mtl material file
options.normalize_normal = True # Normalize all normals to unit length
scene = Scene()
scene.open("model.obj", options)STL 파일의 경우, 동등한 클래스가 StlLoadOptions.GST를 사용하여, 사용하기 위해 GltfLoadOptions.보세요 The API 참조 전체 목록을 위해서.
일반적인 문제와 해결책
FileNotFoundError 전화할 때 오류가 발생합니다. Scene.from_file()
경로는 실시간 작업 디렉토리와 비교하여 절대적이거나 정확해야 합니다. pathlib.Path 신뢰할 수 있는 경로를 구축하기 위해:
from pathlib import Path
from aspose.threed import Scene
path = Path(__file__).parent / "assets" / "model.obj"
scene = Scene.from_file(str(path))mesh.polygons STL 파일을 업로드한 후 빈 상태입니다.
STL 파일은 원료 측면으로 삼각형을 저장하고 인덱스 된 껍질이 아닙니다.로드 후, 폴리곤은 그 측정에서 합성됩니다. polygons 텅 비어 보이는데 확인해요~ len(mesh.control_points);숫자가 3의 다수인 경우 지질학은 비표시 형태로 저장되며 각 연속 삼각형은 하나의 삼둥지를 형성합니다.
조정 시스템 오류 (모델은 회전 또는 거울로 나타납니다)
다른 도구는 다양한 컨벤션을 사용합니다 (Y-up vs Z-Up, 왼손 vs 오른손). ObjLoadOptions.flip_coordinate_system = True 또는 뿌리 노드에 회전을 적용합니다. Transform 충전 후에.
AttributeError: 'NoneType' object has no attribute 'polygons'
노드의 개체 목록에는 비 메시 개성(카메라, 빛)이 포함될 수 있습니다. isinstance(entity, Mesh) 카스팅하기 전에.
자주 묻는 질문 (FAQ)
어떤 3D 형식으로 충전할 수 있나요?
OBJ (Wavefront), STL (비나리 및 ASCII), glTF 2.0 / GLB, COLLADA (DAE) 및 3MF. FBX 파일 토큰화는 부분적으로 지원되지만 완전한 파싱은 아직 완료되지 않습니다.
OBJ 파일을 업로드하는 것도 .mtl 물질은 ?
예, 언제 ObjLoadOptions.enable_materials = True 도서관은 이들을 찾고 있다. - The Library is looking for the .mtl 동일한 디렉토리에서 파일을 작성하는 것과 같은 .obj 파일 : 만약 그가 .mtl 지질학이 여전히 부담되고 경고가 발행됩니다.
나는 바이트 스트림에서 파일을 로드 할 수 있습니까?
예요 ᄒᄒ. scene.open() 파일과 같은 모든 개체를 받아들이는 A .read() 방법은 파일 경로 스트립 외에.오픈 바이너리 스트림을 통과 (예를 들어,., io.BytesIO직접적으로 하는 것. Scene.from_file() 파일 경로 스트립만 받아들인다.
어떻게 표면 정상을 얻을 수 있습니까?
짐을 하다가 확인해 보세요. mesh.get_element(VertexElementType.NORMAL).이게 다시 A를 가져옵니다. VertexElementNormal 누구의 data 목록에는 참조 당 1개의 정상 벡터가 포함되어 있으며, 다음과 같이 지도됩니다. mapping_mode 그리고 reference_mode.
from aspose.threed.entities import Mesh, VertexElementType
normals = mesh.get_element(VertexElementType.NORMAL)
if normals:
print(normals.data[0]) # First normal vector도서관은 동시에 여러 파일을 충전하는 데 안전합니까?
각각의 Scene 개체는 독립적입니다.별로 파일을 별도로 업로드합니다. Scene 별도의 스트립에서 사례는 하나를 공유하지 않는 한 안전합니다. Scene 외부 잠금 없이 끈을 넘어.