ImageTracking_TargetOnTheFly

Demonstrate how to create image target directly from real-time camera image and load it into tracker as a target.

How to Use

../../_images/image_25.png
Mark 1: Region for image capture.
Mark 2: Capture image in mark 1 to create image target.
Mark 3: Unload and delete all image targets and caches.

How It Works

Use part of camera image as target ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ x

This sample use part of the camera image as target. First get that data and encode to image.

private IEnumerator CaptureAndCreateTarget()
{
    yield return new WaitForEndOfFrame();

    var size = new Vector2Int((int)(Screen.width * 0.6f), (int)(Screen.height * 0.5f));
    var texture = new Texture2D(size.x, size.y, TextureFormat.RGB24, false);
    texture.ReadPixels(new Rect(Screen.width * 0.2f, Screen.height * 0.2f, size.x, size.y), 0, 0, false);
    texture.Apply();

    var target = CreateImageTarget(Instantiate(texture));

    targets.Add(target);
    var quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
    quad.GetComponent<MeshRenderer>().material.mainTexture = texture;
    quad.transform.SetParent(target.transform, false);
    quad.transform.localScale = new Vector3(1, (float)size.y / size.x, 1);
    var panda = Instantiate(Panda);
    panda.transform.SetParent(target.transform, false);
}

You can then create targets from images. Create an empty GameObject and add ImageTargetController and setup the ImageTargetController with image file.

private ImageTargetController CreateImageTarget(Texture2D texture)
{
    var targetObject = ARSessionFactory.CreateController<ImageTargetController>();
    var controller = targetObject.GetComponent<ImageTargetController>();
    controller.TargetDataLoad += (_) => Destroy(texture);
    controller.Source = new ImageTargetController.Texture2DSourceData
    {
        Texture = texture
    };
    controller.Tracker = Filter;
    return controller;
}

This sample use a direct way to handle target creation, but it is not in the best performance. You can also create an Image with image data byte array, and create target directly using ImageTarget.createFromParameters to achieve better performance.