-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathARFoundationCameraToMatExample.cs
More file actions
289 lines (223 loc) · 10.1 KB
/
Copy pathARFoundationCameraToMatExample.cs
File metadata and controls
289 lines (223 loc) · 10.1 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#if !(PLATFORM_LUMIN && !UNITY_EDITOR)
using OpenCVForUnity.CoreModule;
using OpenCVForUnity.ImgprocModule;
using OpenCVForUnity.UnityUtils;
using OpenCVForUnity.ObjdetectModule;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
using DlibFaceLandmarkDetector;
namespace ARFoundationWithOpenCVForUnityExample
{
public class ARFoundationCameraToMatExample : MonoBehaviour
{
public ARFaceManager faceManager;
[SerializeField, TooltipAttribute("The ARCameraManager which will produce frame events.")]
public ARCameraManager cameraManager = default;
[SerializeField, TooltipAttribute("The ARCamera.")]
public Camera arCamera;
[SerializeField]
Mat rgbaMat;
Mat rotatedFrameMat;
Texture2D texture;
bool hasInitDone = false;
bool isPlaying = true;
ScreenOrientation screenOrientation;
int displayRotationAngle = 0;
bool displayFlipVertical = false;
bool displayFlipHorizontal = false;
string dlibShapePredictorFileName = "sp_human_face_68_for_mobile.dat";
FaceLandmarkDetector faceLandmarkDetector;
void Start()
{
faceLandmarkDetector = new FaceLandmarkDetector(Utils.getFilePath(dlibShapePredictorFileName));
}
void OnEnable()
{
if (cameraManager != null)
{
cameraManager.frameReceived += OnCameraFrameReceived;
}
}
void OnDisable()
{
if (cameraManager != null)
{
cameraManager.frameReceived -= OnCameraFrameReceived;
}
}
protected void OnCameraFrameReceived(ARCameraFrameEventArgs eventArgs)
{
if ((cameraManager == null) || (cameraManager.subsystem == null) || !cameraManager.subsystem.running)
return;
// Attempt to get the latest camera image. If this method succeeds,
// it acquires a native resource that must be disposed (see below).
if (!cameraManager.TryAcquireLatestCpuImage(out XRCpuImage image))
{
return;
}
int width = image.width;
int height = image.height;
Matrix4x4 m_DisplayRotationMatrix = Matrix4x4.identity;
if (!hasInitDone || rgbaMat == null || rgbaMat.cols() != width || rgbaMat.rows() != height || screenOrientation != Screen.orientation)
{
Dispose();
screenOrientation = Screen.orientation;
XRCameraConfiguration config = (XRCameraConfiguration)cameraManager.currentConfiguration;
int framerate = config.framerate.HasValue ? config.framerate.Value : -1;
// Remove scaling and offset factors from the camera display matrix while maintaining orientation.
// Decompose that matrix to extract the rotation and flipping factors.
if (eventArgs.displayMatrix.HasValue)
{
// Copy the display rotation matrix from the camera.
Matrix4x4 cameraMatrix = eventArgs.displayMatrix ?? Matrix4x4.identity;
Vector2 affineBasisX = new Vector2(1.0f, 0.0f);
Vector2 affineBasisY = new Vector2(0.0f, 1.0f);
Vector2 affineTranslation = new Vector2(0.0f, 0.0f);
#if UNITY_IOS
affineBasisX = new Vector2(cameraMatrix[0, 0], cameraMatrix[1, 0]);
affineBasisY = new Vector2(cameraMatrix[0, 1], cameraMatrix[1, 1]);
affineTranslation = new Vector2(cameraMatrix[2, 0], cameraMatrix[2, 1]);
#endif // UNITY_IOS
#if UNITY_ANDROID
affineBasisX = new Vector2(cameraMatrix[0, 0], cameraMatrix[0, 1]);
affineBasisY = new Vector2(cameraMatrix[1, 0], cameraMatrix[1, 1]);
affineTranslation = new Vector2(cameraMatrix[0, 2], cameraMatrix[1, 2]);
#endif // UNITY_ANDROID
affineBasisX = affineBasisX.normalized;
affineBasisY = affineBasisY.normalized;
m_DisplayRotationMatrix = Matrix4x4.identity;
m_DisplayRotationMatrix[0, 0] = affineBasisX.x;
m_DisplayRotationMatrix[0, 1] = affineBasisY.x;
m_DisplayRotationMatrix[1, 0] = affineBasisX.y;
m_DisplayRotationMatrix[1, 1] = affineBasisY.y;
#if UNITY_IOS
Matrix4x4 FlipYMatrix = Matrix4x4.Scale(new Vector3(1, -1, 1));
m_DisplayRotationMatrix = FlipYMatrix.inverse * m_DisplayRotationMatrix;
#endif // UNITY_IOS
displayRotationAngle = (int)ARUtils.ExtractRotationFromMatrix(ref m_DisplayRotationMatrix).eulerAngles.z;
Vector3 localScale = ARUtils.ExtractScaleFromMatrix(ref m_DisplayRotationMatrix);
displayFlipVertical = Mathf.Sign(localScale.y) == -1;
displayFlipHorizontal = Mathf.Sign(localScale.x) == -1;
}
rgbaMat = new Mat(height, width, CvType.CV_8UC4);
if (displayRotationAngle == 90 || displayRotationAngle == 270)
{
width = image.height;
height = image.width;
rotatedFrameMat = new Mat(height, width, CvType.CV_8UC4);
}
texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
gameObject.GetComponent<Renderer>().material.mainTexture = texture;
//gameObject.transform.localScale = new Vector3(width, height, 1);
hasInitDone = true;
}
if (hasInitDone && isPlaying)
{
XRCpuImage.ConversionParams conversionParams = new XRCpuImage.ConversionParams(image, TextureFormat.RGBA32, XRCpuImage.Transformation.None);
image.Convert(conversionParams, (IntPtr)rgbaMat.dataAddr(), (int)rgbaMat.total() * (int)rgbaMat.elemSize());
if (displayFlipVertical && displayFlipHorizontal)
{
Core.flip(rgbaMat, rgbaMat, -1);
}
else if (displayFlipVertical)
{
Core.flip(rgbaMat, rgbaMat, 0);
}
else if (displayFlipHorizontal)
{
Core.flip(rgbaMat, rgbaMat, 1);
}
if (rotatedFrameMat != null)
{
if (displayRotationAngle == 90)
{
Core.rotate(rgbaMat, rotatedFrameMat, Core.ROTATE_90_CLOCKWISE);
}
else if (displayRotationAngle == 270)
{
Core.rotate(rgbaMat, rotatedFrameMat, Core.ROTATE_90_COUNTERCLOCKWISE);
}
Doprocess(rotatedFrameMat);
Utils.fastMatToTexture2D(rotatedFrameMat, texture);
}
else
{
if (displayRotationAngle == 180)
{
Core.rotate(rgbaMat, rgbaMat, Core.ROTATE_180);
}
Doprocess(rgbaMat);
Utils.fastMatToTexture2D(rgbaMat, texture);
}
}
image.Dispose();
}
private void Doprocess(Mat mat)
{
if (faceManager.enabled && faceManager.trackables.count > 0)
{
//mat to texture
Texture2D texture2D = new Texture2D(mat.cols(), mat.rows(), TextureFormat.RGBA32, false);
Utils.fastMatToTexture2D(mat, texture);
faceLandmarkDetector.SetImage(texture2D);
//detect face rects
List<UnityEngine.Rect> detectResult = faceLandmarkDetector.Detect();
foreach (var rect in detectResult)
{
Debug.Log("face : " + rect);
//detect landmark points
List<Vector2> points = faceLandmarkDetector.DetectLandmark(rect);
Debug.Log("face points count : " + points.Count);
foreach (var point in points)
{
Debug.Log("face point : x " + point.x + " y " + point.y);
}
//draw landmark points
faceLandmarkDetector.DrawDetectLandmarkResult(texture2D, 0, 255, 0, 255);
}
//draw face rect
faceLandmarkDetector.DrawDetectResult(texture2D, 255, 0, 0, 255, 2);
faceLandmarkDetector.Dispose();
//texture to mat
Utils.fastTexture2DToMat(texture2D, mat);
// destroy texture
Destroy(texture2D);
}
}
/// <summary>
/// Releases all resource.
/// </summary>
private void Dispose()
{
hasInitDone = false;
if (rgbaMat != null)
{
rgbaMat.Dispose();
rgbaMat = null;
}
if (rotatedFrameMat != null)
{
rotatedFrameMat.Dispose();
rotatedFrameMat = null;
}
if (texture != null)
{
Texture2D.Destroy(texture);
texture = null;
}
}
/// <summary>
/// Raises the destroy event.
/// </summary>
void OnDestroy()
{
Dispose();
}
}
}
#endif