ARKit图像检测和添加来自Assets.xcsets的图像 [英] ARKit Image Detection and Add Image From Assets.xcassets

查看:26
本文介绍了ARKit图像检测和添加来自Assets.xcsets的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩弄我从苹果开发人员网站下载的AR图像检测代码。我正在尝试修改它,以便在检测到图像后,在Resources/Assets.xcsets中的AR Resource文件夹中显示特定的图像。我看到一个类似的问题在两年前发布过,我尝试了这个也是唯一的答案,但没有成功。有人能帮忙吗?谢谢!

导入ARKit 导入场景工具包 导入UIKit

类视图控制器:UIView控制器,ARSCNViewDelegate{

@IBOutlet var sceneView: ARSCNView!

@IBOutlet weak var blurView: UIVisualEffectView!

/// The view controller that displays the status and "restart experience" UI.
lazy var statusViewController: StatusViewController = {
    return children.lazy.compactMap({ $0 as? StatusViewController }).first!
}()

/// A serial queue for thread safety when modifying the SceneKit node graph.
let updateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! +
    ".serialSceneKitQueue")

/// Convenience accessor for the session owned by ARSCNView.
var session: ARSession {
    return sceneView.session
}

// MARK: - View Controller Life Cycle

override func viewDidLoad() {
    super.viewDidLoad()

    sceneView.delegate = self
    sceneView.session.delegate = self

    // Hook up status view controller callback(s).
    statusViewController.restartExperienceHandler = { [unowned self] in
        self.restartExperience()
    }
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // Prevent the screen from being dimmed to avoid interuppting the AR experience.
    UIApplication.shared.isIdleTimerDisabled = true

    // Start the AR experience
    resetTracking()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    session.pause()
}

// MARK: - Session management (Image detection setup)

/// Prevents restarting the session while a restart is in progress.
var isRestartAvailable = true

/// Creates a new AR configuration to run on the `session`.
/// - Tag: ARReferenceImage-Loading
func resetTracking() {

    guard let referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: nil) else {
        fatalError("Missing expected asset catalog resources.")
    }

    let configuration = ARWorldTrackingConfiguration()
    configuration.detectionImages = referenceImages
    session.run(configuration, options: [.resetTracking, .removeExistingAnchors])

    statusViewController.scheduleMessage("Look around to detect images", inSeconds: 7.5, messageType: .contentPlacement)
}

// MARK: - ARSCNViewDelegate (Image detection results)
/// - Tag: ARImageAnchor-Visualizing
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
    guard let imageAnchor = anchor as? ARImageAnchor else { return }
    let referenceImage = imageAnchor.referenceImage
    updateQueue.async {

        // Create a plane to visualize the initial position of the detected image.
        let plane = SCNPlane(width: referenceImage.physicalSize.width,
                             height: referenceImage.physicalSize.height)
        let planeNode = SCNNode(geometry: plane)
        planeNode.opacity = 0.25

        /*
         `SCNPlane` is vertically oriented in its local coordinate space, but
         `ARImageAnchor` assumes the image is horizontal in its local space, so
         rotate the plane to match.
         */
        planeNode.eulerAngles.x = -.pi / 2

        /*
         Image anchors are not tracked after initial detection, so create an
         animation that limits the duration for which the plane visualization appears.
         */
        planeNode.runAction(self.imageHighlightAction)
        plane.materials = [SCNMaterial()]
        plane.materials[0].diffuse.contents = UIImage(named: "Macbook 12-inch")

        // Add the plane visualization to the scene.
        node.addChildNode(planeNode)



        DispatchQueue.main.async {
            let imageName = referenceImage.name ?? ""
            self.statusViewController.cancelAllScheduledMessages()
            self.statusViewController.showMessage("Detected image "(imageName)"")
        }
    }


}

var imageHighlightAction: SCNAction {
    return .sequence([
        .wait(duration: 0.25),
        .fadeOpacity(to: 0.85, duration: 0.25),
        .fadeOpacity(to: 0.15, duration: 0.25),
        .fadeOpacity(to: 0.85, duration: 0.25),
        .fadeOut(duration: 0.5),
        .removeFromParentNode()
    ])
}

}

推荐答案

在Xcode的<资源文件夹中,单击+按钮并为参考图像创建一个文件夹(使用.png.jpg格式)。在Xcode的目录中,此文件夹将获得.arresourcegroup扩展名。

//      AR and Textures –> AR Resource Group

您可以重命名此文件夹。没有必要在这个文件夹中放入高分辨率图像。每幅图像的合适分辨率为400x400。放在那里的图片不能超过100张。仅此而已。

您的代码可能如下所示:

guard let images = ARReferenceImage.referenceImages(
                                               inGroupNamed: "AR Resources",
                                                     bundle: nil)
else { return }

let config = ARWorldTrackingConfiguration()
config.detectionImages = images
config.maximumNumberOfTrackedImages = 3

arView.session.run(config, options: [])

这篇关于ARKit图像检测和添加来自Assets.xcsets的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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