· 6 years ago · Dec 03, 2019, 08:42 PM
1using UnityEngine;
2using System.Collections;
3using System.Runtime.InteropServices;
4using System;
5using System.IO;
6using System.Net.Http;
7using System.Net.Http.Headers;
8using System.Text;
9using System.Collections.Generic;
10using UnityEngine.UI;
11
12
13 public class displayWebcam : MonoBehaviour {
14
15
16 // Replace <Subscription Key> with your valid subscription key.
17 const string subscriptionKey = "KEY";
18 // replace <myresourcename> with the string found in your endpoint URL
19 //const string uriBase = "https://<SERVICE_name>.cognitive.microsoft.com/face/v1.0/detect";
20 const string uriBase = "https://<SERVICE_name>.cognitiveservices.azure.com/face/v1.0/detect";
21
22
23 // Get the path and filename to process from the user.
24 async void MakeAnalysisRequest(string imageFilePath)
25 {
26 HttpClient client = new HttpClient();
27
28 // Request headers.
29 client.DefaultRequestHeaders.Add(
30 "Ocp-Apim-Subscription-Key", subscriptionKey);
31
32 // Request parameters. A third optional parameter is "details".
33 string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
34 "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
35 "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
36
37 // Assemble the URI for the REST API Call.
38 string uri = uriBase + "?" + requestParameters;
39
40 HttpResponseMessage response;
41
42 // Request body. Posts a locally stored JPEG image.
43 byte[] byteData = GetImageAsByteArray(imageFilePath);
44
45 using (ByteArrayContent content = new ByteArrayContent(byteData))
46 {
47 // This example uses content type "application/octet-stream".
48 // The other content types you can use are "application/json"
49 // and "multipart/form-data".
50 content.Headers.ContentType =
51 new MediaTypeHeaderValue("application/octet-stream");
52
53 // Execute the REST API call.
54 response = await client.PostAsync(uri, content);
55
56 // Get the JSON response.
57 string contentString = await response.Content.ReadAsStringAsync();
58
59
60 // Display the JSON response.
61 print("\nResponse:\n");
62 print(contentString);
63 }
64 }
65 // Returns the contents of the specified file as a byte array.
66 static byte[] GetImageAsByteArray(string imageFilePath)
67 {
68 using (FileStream fileStream =
69 new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
70 {
71 BinaryReader binaryReader = new BinaryReader(fileStream);
72 return binaryReader.ReadBytes((int)fileStream.Length);
73 }
74 }
75
76 public string deviceName;
77 WebCamTexture wct;
78 public RawImage RawImage;
79 public Color32Array colorArray;
80 Color32[] data;
81
82 [StructLayout(LayoutKind.Explicit)]
83 public struct Color32Array
84 {
85 [FieldOffset(0)]
86 public byte[] byteArray;
87
88 [FieldOffset(0)]
89 public Color32[] colors;
90 }
91
92 private string _SavePath = "C:/WebcamSnaps/";
93 int _CaptureCounter = 0;
94 String TakeSnapshot()
95 {
96 Texture2D snap = new Texture2D(wct.width, wct.height);
97 snap.SetPixels(wct.GetPixels());
98 snap.Apply();
99 String path = _SavePath + _CaptureCounter.ToString() + ".png";
100 System.IO.File.WriteAllBytes(_SavePath + _CaptureCounter.ToString() + ".png", snap.EncodeToPNG());
101 ++_CaptureCounter;
102 return path;
103 }
104
105 // Use this for initialization
106 void Start () {
107 WebCamDevice[] devices = WebCamTexture.devices;
108 deviceName = devices[0].name;
109 wct = new WebCamTexture(deviceName, 640, 480, 60);
110 colorArray = new Color32Array();
111 colorArray.colors = new Color32[wct.width * wct.height];
112 data = new Color32[wct.width * wct.height];
113
114 //GetComponent<Renderer>().material.mainTexture = wct;
115 RawImage.texture = wct;
116 RawImage.material.mainTexture = wct;
117 wct.Play();
118 }
119
120 void Update ()
121 {
122 if (Input.GetKeyDown("t"))
123 {
124 String path = TakeSnapshot();
125 print(path);
126
127 if (File.Exists(path))
128 {
129 try
130 {
131 MakeAnalysisRequest(path);
132 print("\nWait a moment for the results to appear.\n");
133 }
134 catch (Exception e)
135 {
136 print("\n" + e.Message + "\nPress Enter to exit...\n");
137 }
138 }
139 else
140 {
141 print("\nInvalid file path.\nPress Enter to exit...\n");
142 }
143
144 }
145 }
146 public byte[] getImageBytes()
147 {
148 return colorArray.byteArray;
149 }
150 }