ARKit –如何在QRCode上放置3D对象? [英] ARKit – How to put 3D Object on QRCode?

查看:131
本文介绍了ARKit –如何在QRCode上放置3D对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是在尝试使用ARKit在QRCode上放置 3D对象为此,我使用 AVCaptureDevice 检测QRCode并建立QRCode的区域,该区域为我提供 CGRect .然后,我对CGRect的每个点进行 hitTest ,以获取平均3D坐标,如下所示:

I'm actually trying to put a 3D Object on QRCode with ARKit For that I use a AVCaptureDevice to detect a QRCode and establish the area of the QRCode that gives me a CGRect. Then, I make a hitTest on every point of the CGRect to get the average 3D coordinates like so :

positionGiven = SCNVector3(0, 0, 0)

for column in Int(qrZone.origin.x)...2*Int(qrZone.origin.x + qrZone.width) {
    for row in Int(qrZone.origin.y)...2*Int(qrZone.origin.y + qrZone.height) {
        for result in sceneView.hitTest(CGPoint(x: CGFloat(column)/2,y:CGFloat(row)/2), types: [.existingPlaneUsingExtent,.featurePoint]) {

            positionGiven.x+=result.worldTransform.columns.3.x
            positionGiven.y+=result.worldTransform.columns.3.y
            positionGiven.z+=result.worldTransform.columns.3.z
            cpts += 1
        }
    }
}

positionGiven.x=positionGiven.x/cpts
positionGiven.y=positionGiven.y/cpts
positionGiven.z=positionGiven.z/cpts

但是hitTest不会检测到任何结果并冻结相机,而当我触摸屏幕进行hitTest时,它会起作用.您知道为什么它不起作用吗?您还有其他想法可以帮助我实现我想要做的事情吗?

But the hitTest doesn't detect any result and freeze the camera while when I make a hitTest with a touch on screen it works. Do you have any idea why it's not working ? Do you have an other idea that can help me to achieve what I want to do ?

我已经考虑过使用CoreMotion进行 3D转换,它可以使设备倾斜,但看起来确实很乏味.我还听说过 ARWorldAlignmentCamera ,它可以锁定场景坐标以匹配相机的方向,但是我不知道如何使用它!

I already thought about 3D translation with CoreMotion that can give me the tilt of the device but that seems really tedious. I also heard about ARWorldAlignmentCamera that can locked the scene coordinate to match the orientation of the camera but I don't know how to use it !

编辑:每次触摸屏幕时,我都会尝试移动3D对象,并且hitTest是肯定的,并且非常准确!我真的不明白为什么像素区域的hitTest无法正常工作...

Edit : I try to move my 3D Object every time I touch the screen and the hitTest is positive, and it's pretty accurate ! I really don't understand why hitTest on an area of pixels doesn't work...

编辑2 :这是hitTest的代码,可在屏幕上进行2到5次触摸:

Edit 2 : Here is the code of the hitTest who works with 2-5 touches on the screen:

@objc func touch(sender : UITapGestureRecognizer) {

    for result in sceneView.hitTest(CGPoint(x: sender.location(in: view).x,y: sender.location(in: view).y), types: [.existingPlaneUsingExtent,.featurePoint]) {
        //Pop up message for testing
        alert("\(sender.location(in: view))", message: "\(result.worldTransform.columns.3)")

        //Moving the 3D Object to the new coordinates
        let objectList = sceneView.scene.rootNode.childNodes

        for object : SCNNode in objectList {
            object.removeFromParentNode()
        }
        addObject(SCNVector3(result.worldTransform.columns.3.x,result.worldTransform.columns.3.y,result.worldTransform.columns.3.z))
    }
}

编辑3 :我设法部分解决了我的问题.

Edit 3 : I manage to resolve my problem partially.

我获取摄像机的变换矩阵(session.currentFrame.camera.transform),以使对象位于摄像机的前面.然后,我将CGRect的位置应用于(x,y)的平移.但是我无法转换z轴,因为我没有足够的信息.而且我可能需要像hitTest一样估算z坐标.

I take the transform matrix of the camera (session.currentFrame.camera.transform) so that the object is in front of the camera. Then I apply a translation on (x,y) with the position of the CGRect. However i can't translate the z-axis because i don't have enough informations. And I will probably need a estimation of z coordinate like the hitTest do..

提前谢谢!:)

推荐答案

您可以使用 Apple的Vision API 检测QR码并放置锚点.

You could use Apple's Vision API to detect the QR code and place an anchor.

要开始检测QR码,请使用:

To start detecting QR codes, use:

 var qrRequests = [VNRequest]()
 var detectedDataAnchor: ARAnchor?
 var processing = false

 func startQrCodeDetection() {
    // Create a Barcode Detection Request
    let request = VNDetectBarcodesRequest(completionHandler: self.requestHandler)
    // Set it to recognize QR code only
    request.symbologies = [.QR]
    self.qrRequests = [request]
}

ARSession didUpdate框架

public func session(_ session: ARSession, didUpdate frame: ARFrame) {
    DispatchQueue.global(qos: .userInitiated).async {
        do {
            if self.processing {
              return
            }
            self.processing = true
            // Create a request handler using the captured image from the ARFrame
            let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: frame.capturedImage,
                                                            options: [:])
            // Process the request
            try imageRequestHandler.perform(self.qrRequests)
        } catch {

        }
    }
}

处理Vision QR请求并触发点击测试

Handle the Vision QR request and trigger the hit test

func requestHandler(request: VNRequest, error: Error?) {
    // Get the first result out of the results, if there are any
    if let results = request.results, let result = results.first as? VNBarcodeObservation {
        guard let payload = result.payloadStringValue else {return}
        // Get the bounding box for the bar code and find the center
        var rect = result.boundingBox
        // Flip coordinates
        rect = rect.applying(CGAffineTransform(scaleX: 1, y: -1))
        rect = rect.applying(CGAffineTransform(translationX: 0, y: 1))
        // Get center
        let center = CGPoint(x: rect.midX, y: rect.midY)

        DispatchQueue.main.async {
            self.hitTestQrCode(center: center)
            self.processing = false
        }
    } else {
        self.processing = false
    }
}

 func hitTestQrCode(center: CGPoint) {
    if let hitTestResults = self.latestFrame?.hitTest(center, types: [.featurePoint] ),
        let hitTestResult = hitTestResults.first {
        if let detectedDataAnchor = self.detectedDataAnchor,
            let node = self.sceneView.node(for: detectedDataAnchor) {
            let previousQrPosition = node.position
            node.transform = SCNMatrix4(hitTestResult.worldTransform)

        } else {
            // Create an anchor. The node will be created in delegate methods
            self.detectedDataAnchor = ARAnchor(transform: hitTestResult.worldTransform)
            self.sceneView.session.add(anchor: self.detectedDataAnchor!)
        }
    }
}

然后在添加锚点时添加节点的句柄.

Then handle adding the node when the anchor is added.

func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {

    // If this is our anchor, create a node
    if self.detectedDataAnchor?.identifier == anchor.identifier {
        let sphere = SCNSphere(radius: 1.0)
        sphere.firstMaterial?.diffuse.contents = UIColor.redColor()
        let sphereNode = SCNNode(geometry: sphere)
        sphereNode.transform = SCNMatrix4(anchor.transform)
        return sphereNode
    }
    return nil
}

来源

这篇关于ARKit –如何在QRCode上放置3D对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆