forked from keijiro/jp.keijiro.apriltag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebcamTest.cs
73 lines (59 loc) · 2.28 KB
/
WebcamTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using UnityEngine;
using System.Linq;
using UI = UnityEngine.UI;
sealed class WebcamTest : MonoBehaviour
{
[SerializeField] Vector2Int _resolution = new Vector2Int(1280, 720);
[SerializeField] int _decimation = 4;
[SerializeField] float _tagSize = 0.05f;
[SerializeField] Material _tagMaterial = null;
[SerializeField] UI.RawImage _webcamPreview = null;
[SerializeField] UI.Text _debugText = null;
// Webcam input and buffer
WebCamTexture _webcamRaw;
RenderTexture _webcamBuffer;
Color32 [] _readBuffer;
// AprilTag detector and drawer
AprilTag.TagDetector _detector;
TagDrawer _drawer;
void Start()
{
// Webcam initialization
_webcamRaw = new WebCamTexture(_resolution.x, _resolution.y, 60);
_webcamBuffer = new RenderTexture(_resolution.x, _resolution.y, 0);
_readBuffer = new Color32 [_resolution.x * _resolution.y];
_webcamRaw.Play();
_webcamPreview.texture = _webcamBuffer;
// Detector and drawer
_detector = new AprilTag.TagDetector(_resolution.x, _resolution.y, _decimation);
_drawer = new TagDrawer(_tagMaterial);
}
void OnDestroy()
{
Destroy(_webcamRaw);
Destroy(_webcamBuffer);
_detector.Dispose();
_drawer.Dispose();
}
void Update()
{
// Check if the webcam is ready (needed for macOS support)
if (_webcamRaw.width <= 16) return;
// Check if the webcam is flipped (needed for iOS support)
if (_webcamRaw.videoVerticallyMirrored)
_webcamPreview.transform.localScale = new Vector3(1, -1, 1);
// Webcam image buffering
_webcamRaw.GetPixels32(_readBuffer);
Graphics.Blit(_webcamRaw, _webcamBuffer);
// AprilTag detection
var fov = GetComponent<Camera>().fieldOfView * Mathf.Deg2Rad;
_detector.ProcessImage(_readBuffer, fov, _tagSize);
// Detected tag visualization
foreach (var tag in _detector.DetectedTags)
_drawer.Draw(tag.ID, tag.Position, tag.Rotation, _tagSize);
// 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}");
}
}