Last active
November 7, 2021 21:53
-
-
Save elvis75k/329b35089361ac5739f7ae746d6deb4e to your computer and use it in GitHub Desktop.
Keijiro's AprilTag for scene tracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Linq; | |
using UI = UnityEngine.UI; | |
using AprilTag; | |
sealed class PicTest : MonoBehaviour | |
{ | |
[SerializeField] Vector2Int _resolution = new Vector2Int(1280, 720); | |
[SerializeField] int _decimation = 4; | |
[SerializeField] float _tagSize = 0.05f; | |
[SerializeField] UI.RawImage _picPreview = null; | |
[SerializeField] Material _tagMaterial = null; | |
[SerializeField] UI.Text _debugText = null; | |
public Texture2D sourceImage; | |
Color32[] _readBuffer; | |
public RenderTexture myRenderTexture; | |
// AprilTag detector and drawer | |
AprilTag.TagDetector _detector; | |
TagDrawer _drawer; | |
void Start() | |
{ | |
_readBuffer = new Color32[_resolution.x * _resolution.y]; | |
_picPreview.texture = sourceImage; | |
// Detector and drawer | |
_detector = new AprilTag.TagDetector(_resolution.x, _resolution.y, _decimation); | |
_drawer = new TagDrawer(_tagMaterial); | |
} | |
void OnDestroy() | |
{ | |
// Destroy(sourceImage); | |
// Destroy(myRenderTexture); | |
_detector.Dispose(); | |
_drawer.Dispose(); | |
} | |
void Update() | |
{ | |
// Image conversion and buffering | |
sourceImage = toTexture2D(myRenderTexture); | |
_readBuffer = sourceImage.GetPixels32(); | |
// AprilTag detection | |
var fov = GetComponent<Camera>().fieldOfView * Mathf.Deg2Rad; | |
_detector.ProcessImage(_readBuffer, fov, _tagSize); | |
Destroy(sourceImage); | |
// Detected tag visualization | |
foreach (var tag in _detector.DetectedTags) | |
{ | |
_drawer.Draw(tag.ID, tag.Position, tag.Rotation, _tagSize); | |
Debug.LogFormat("ID: {0}, Pos: {1}, Rot: {2}", tag.ID, tag.Position, tag.Rotation); | |
} | |
// Profile data output (with 30 frame interval) | |
if (Time.frameCount % 30 == 0) | |
_debugText.text = _detector.ProfileData.Aggregate | |
("Profile (usec)", (c, n) => $"{c}\n{n.name} : {n.time}"); | |
} | |
private Texture2D toTexture2D(RenderTexture rt) | |
{ | |
var texture = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false); | |
RenderTexture.active = rt; | |
texture.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0); | |
texture.Apply(); | |
RenderTexture.active = null; | |
return texture; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment