如何使用RealityKit渲染规范化人脸网格?

5

我正在尝试使用RealityKit渲染面部网格,但还没有成功。当ARKit检测到人脸时,ARSession会生成一个包含面部几何网格的ARFaceAnchor。

但它无法作为模型实体生成。

有人能帮忙吗?

1个回答

4

RealityKit 中的规范人脸网格

要在 RealityKit 2.0 中以编程方式生成和呈现 ARKit 的规范人脸网格(由1220个顶点组成的 ARFaceGeometry 对象),请使用以下代码:

import ARKit
import RealityKit

class ControllerView: UIViewController {
    
    @IBOutlet var arView: ARView!
    var anchor = AnchorEntity()
    var model = ModelEntity()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        arView.automaticallyConfigureSession = false
        arView.session.delegate = self

        guard ARFaceTrackingConfiguration.isSupported
        else { 
            fatalError("We can't run face tracking config") 
        }
                
        let config = ARFaceTrackingConfiguration()
        config.maximumNumberOfTrackedFaces = 1
        arView.session.run(config)
    }
}

接下来创建一个用于转换面部anchor子属性的方法。注意,我使用了for-in循环将索引从转换为类型(在此处进行类型转换不起作用)。

extension ControllerView {
    
    private func nutsAndBoltsOf(_ anchor: ARFaceAnchor) -> MeshDescriptor {
        
        let vertices: [simd_float3] = anchor.geometry.vertices
        var triangleIndices: [UInt32] = []
        let texCoords: [simd_float2] = anchor.geometry.textureCoordinates
        
        for index in anchor.geometry.triangleIndices {         // [Int16]
            triangleIndices.append(UInt32(index))
        }
        print(vertices.count)         // 1220 vertices
        
        var descriptor = MeshDescriptor(name: "canonical_face_mesh")
        descriptor.positions = MeshBuffers.Positions(vertices)
        descriptor.primitives = .triangles(triangleIndices)
        descriptor.textureCoordinates = MeshBuffers.TextureCoordinates(texCoords)
        return descriptor
    }
}

最后,让我们运行代理方法来提供网格资源:
extension ControllerView: ARSessionDelegate {
    
    func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {

        guard let faceAnchor = anchors[0] as? ARFaceAnchor else { return }
        arView.session.add(anchor: faceAnchor)
        self.anchor = AnchorEntity(anchor: faceAnchor)
        self.anchor.scale *= 1.2

        let mesh: MeshResource = try! .generate(from: [nutsAndBoltsOf(faceAnchor)])
        var material = SimpleMaterial(color: .magenta, isMetallic: true)
        self.model = ModelEntity(mesh: mesh, materials: [material])
        self.anchor.addChild(self.model)
        arView.scene.anchors.append(self.anchor)
    }
}

以下是在 iPadOS 16.2 上测试的结果(在 iPad Pro 第四代上进行测试)。

enter image description here


我还建议您查看有关在 RealityKit 2.0 中可视化检测到平面的帖子

圣诞快乐!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接