Ejemplo n.º 1
0
 /// <summary>
 /// Specialised constructor
 /// </summary>
 /// <param name="path">Full path and name</param>
 public PictureInfo(string path)
 {
     FileName = Path.GetFileName(path);
      FullFileName = path;
      XmpFaces = new FaceList();
      PicasaFaces = new FaceList();
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Function to update the list of Face IDs, based on the example images added
        /// </summary>
        private async void UpdateFaceGuidsAsync()
        {
            if (!_faceListExists)
            {
                return;
            }

            try
            {
                FaceList faceList = await _faceServiceClient.GetFaceListAsync(FaceListName.ToLower());

                if (faceList == null)
                {
                    return;
                }

                PersistedFace[] faces = faceList.PersistedFaces;

                foreach (PersistedFace face in faces)
                {
                    FaceIds.Add(face.PersistedFaceId);
                }
            }
            catch (FaceAPIException ex)
            {
                Debug.WriteLine($"Failed to get face list - {ex.ErrorMessage}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Submits a dynamically taken image to the Microsoft Face API for Similarity comparison against stored detected faces
        /// from TrainDetectionAsync. Of the faces checked, the one that is the closest match (if a match is found) is returned.
        /// </summary>
        public static async Task <string> CheckForUserAsync(Uri UnidentifiedImage)
        {
            await _semaphore.WaitAsync();

            var DynamicUserImageStorageFile = await StorageFile.GetFileFromApplicationUriAsync(UnidentifiedImage);

            using (var DynamicUserImageFilestream = File.OpenRead(DynamicUserImageStorageFile.Path))
            {
                //Gets ID for face, which is good for 24 hours.
                //Should we error check for multiple faces or no faces?
                Face[] DetectedFaces;
                await WaitOnTransactionCapAsync();

                try
                {
                    DetectedFaces = await _faceClient.DetectAsync(DynamicUserImageFilestream);

                    _transactionCount++;
                }
                catch (Exception)
                {
                    _semaphore.Release();
                    return("");
                }

                Guid DynamicID;
                if (DetectedFaces.Length > 0)
                {
                    DynamicID = DetectedFaces[0].FaceId;
                }

                FaceList SavedUserFaces = null;
                SimilarPersistedFace[] FacialSimilarityResults;
                try
                {
                    await WaitOnTransactionCapAsync();

                    SavedUserFaces = await _faceClient.GetFaceListAsync(_listKey);

                    _transactionCount++;

                    await WaitOnTransactionCapAsync();

                    _transactionCount++;
                    FacialSimilarityResults = await _faceClient.FindSimilarAsync(DynamicID, _listKey);
                }
                catch
                {
                    _semaphore.Release();
                    return("");
                }

                _semaphore.Release();
                return(FacialSimilarityResults.Length == 0 ? "" : _userNames[FacialSimilarityResults[0].PersistedFaceId]);
            }
        }
Ejemplo n.º 4
0
 private void tbFaceKnown_Click(object sender, RoutedEventArgs e)
 {
     if ((bool)tbFaceKnown.IsChecked)
     {
         FaceList.Clear();
         faceRec.FaceList?.ForEach((face) =>
         {
             FaceList.Add(face);
         });
     }
 }
Ejemplo n.º 5
0
        public static IPrimitive CreateTraceData(this FaceList faceList, List <Vector3Float> vertexList, int maxRecursion = int.MaxValue)
        {
            var allPolys = new List <IPrimitive>();

            foreach (var face in faceList)
            {
                allPolys.Add(new TriangleShape(vertexList[face.v0], vertexList[face.v1], vertexList[face.v2], null));
            }

            return(BoundingVolumeHierarchy.CreateNewHierachy(allPolys, maxRecursion));
        }
Ejemplo n.º 6
0
        public static ITraceable CreateTraceData(FaceList faceList, List <Vector3Float> vertexList, BvhCreationOptions bvhCreationOptions = BvhCreationOptions.FavorFastTracing)
        {
            var allPolys = new List <ITraceable>();

            foreach (var face in faceList)
            {
                allPolys.Add(new TriangleShape(vertexList[face.v0], vertexList[face.v1], vertexList[face.v2], null));
            }

            return(BoundingVolumeHierarchy.CreateNewHierachy(allPolys, bvhCreationOptions));
        }
Ejemplo n.º 7
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="DefinitionBinder"/> class.
        /// </summary>
        /// <externalUnit cref="BallotList"/>
        /// <externalUnit cref="ballots"/>
        /// <externalUnit cref="CardList"/>
        /// <externalUnit cref="cards"/>
        /// <externalUnit cref="ContestList"/>
        /// <externalUnit cref="contests"/>
        /// <externalUnit cref="ElectionParameterList"/>
        /// <externalUnit cref="electionParameters"/>
        /// <externalUnit cref="MachineOptionList"/>
        /// <externalUnit cref="machineOptions"/>
        /// <externalUnit cref="MachineParameters"/>
        /// <externalUnit cref="machineParams"/>
        /// <revision revisor="dev11" date="12/16/2008" version="1.0.0.0">
        ///     Member Created
        /// </revision>
        public DefinitionBinder()
        {
            this.ballots        = new BallotList();
            this.cards          = new CardList();
            this.faces          = new FaceList();
            this.contests       = new ContestList();
            this.machineOptions = new MachineOptionList();
            this.machineParams  = new MachineParameters();
            this.machineParams.ParameterFiles = new ParameterFileList();
            this.electionParameters           = new ElectionParameterList();

            this.faceMap = new Dictionary <string, Face>();
        }
Ejemplo n.º 8
0
        public static void SplitEdges(List <Vector3> vL, FaceList fL, double maxLength)
        {
            //var maxLengthSqrd = maxLength * maxLength;
            //var facesToRemove = new HashSet<int>();
            //// check every face
            //for (int faceIndex = 0; faceIndex < fL.Count; faceIndex++)
            //{
            //	var face = fL[faceIndex];
            //	// check the edge of every face
            //	for (int i = 0; i < 3; i++)
            //	{
            //		var endIndex = face[((i + 1) % 3)];
            //		var startIndex = face[i];
            //		var start = vL[startIndex];
            //		var end = vL[endIndex];
            //		var lengthSqrd = (end.X - start.X) * (end.X - start.X);
            //		//var lengthSqrd = (end - start).LengthSquared;
            //		// if the edge is > maxXLength
            //		if (lengthSqrd > maxLengthSqrd)
            //		{
            //			int lastIndex = face[((i + 2) % 3)];
            //			// add a new vertex at the split
            //			var newPosition = (start + end) / 2;
            //			var newIndex = vL.Count;
            //			vL.Add(newPosition);
            //			// add two new faces
            //			// start, new, last
            //			fL.Add(new int[] { startIndex, newIndex, lastIndex });
            //			// new, end, last
            //			fL.Add(new int[] { newIndex, endIndex, lastIndex });
            //			// mark this face for removal
            //			facesToRemove.Add(faceIndex);
            //			// go on to next face
            //			break;
            //		}
            //	}
            //}

            //// remove all the faces that are marked for removal (make a new list with only keep)
            //var fLN = new FaceList();
            //for (int i = 0; i < fL.Count; i++)
            //{
            //	if (!facesToRemove.Contains(i))
            //	{
            //		fLN.Add(fL[i]);
            //	}
            //}

            //fL.Clear();
            //fL.AddRange(fLN);
        }
Ejemplo n.º 9
0
        private void DeleteFace(object obj)
        {
            if (!PasswordAuthentication())
            {
                return;
            }
            var faceName = obj as string;

            if (faceName == null)
            {
                return;
            }
            FaceList.Remove(faceName);
            faceRec.EncodingDelete(faceName);
        }
        /*
         * END - GROUP FACES
         */

        /*
         * FACELIST OPERATIONS
         * Create a face list and add single-faced images to it, then retrieve data from the faces.
         * Images are used from URLs.
         */
        public static async Task FaceListOperations(IFaceClient client, string baseUrl)
        {
            Console.WriteLine("========FACELIST OPERATIONS========");
            Console.WriteLine();

            const string FaceListId   = "myfacelistid_001";
            const string FaceListName = "MyFaceListName";

            // Create an empty FaceList with user-defined specifications, it gets stored in the client.
            await client.FaceList.CreateAsync(faceListId : FaceListId, name : FaceListName);

            // Create a list of single-faced images to append to base URL. Images with mulitple faces are not accepted.
            List <string> imageFileNames = new List <string>
            {
                "detection1.jpg",                                                // single female with glasses
                "detection2.jpg",                                                // single male
                "detection3.jpg",                                                // single male construction worker
            };

            // Add Faces to the FaceList.
            foreach (string image in imageFileNames)
            {
                string urlFull = baseUrl + image;
                // Returns a Task<PersistedFace> which contains a GUID, and is stored in the client.
                await client.FaceList.AddFaceFromUrlAsync(faceListId : FaceListId, url : urlFull);
            }

            // Print the face list
            Console.WriteLine("Face IDs from the face list: ");
            Console.WriteLine();

            // List the IDs of each stored image
            FaceList faceList = await client.FaceList.GetAsync(FaceListId);

            foreach (PersistedFace face in faceList.PersistedFaces)
            {
                Console.WriteLine(face.PersistedFaceId);
            }

            // Delete the face list, for repetitive testing purposes (cannot recreate list with same name).
            await client.FaceList.DeleteAsync(FaceListId);

            Console.WriteLine();
            Console.WriteLine("Deleted the face list.");
            Console.WriteLine();
        }
Ejemplo n.º 11
0
 public virtual void Clear()
 {
     Header.ElementFormat.Ver      = 2.1f;
     Header.ElementFormat.UVACount = 0;
     ModelInfo.Clear();
     VertexList.Clear();
     FaceList.Clear();
     MaterialList.Clear();
     BoneList.Clear();
     MorphList.Clear();
     BodyList.Clear();
     JointList.Clear();
     SoftBodyList.Clear();
     InitializeSystemNode();
     FilePath     = "";
     LoadErrCount = 0;
 }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// <remarks>
        /// facelistId:为空时,自动创建Guid
        /// </remarks>
        /// </summary>
        /// <param name="serviceKey">服务key</param>
        /// <param name="facelistId">容器Id</param>
        public FaceApiHelper(string serviceKey, string facelistId = "")
        {
            ServiceKey = serviceKey;
            if (string.IsNullOrEmpty(facelistId))
            {
                facelistId = Guid.NewGuid().ToString();
            }
            FaceListId        = facelistId;
            faceServiceClient = new FaceServiceClient(ServiceKey);
            //判定是否已经存在
            FaceList isExist = GetFaceListInfoById(FaceListId).Result;

            if (isExist == null)
            {
                var task = faceServiceClient.CreateFaceListAsync(FaceListId, FaceListId, FaceListId);
                task.Wait();
            }
        }
                public Obj(StringReader sreader, string name)
                {
                    this.obj_name = name;

                    String currentText = sreader.ReadLine();

                    String[] brokenstring;
                    char[]   split_space = { ' ' };

                    uint vartex_count;
                    uint face_count;
                    uint polygon_count;

                    while (!currentText.StartsWith("}"))
                    {
                        //Debug.Log(currentText);
                        if (currentText.StartsWith("	visible"))
                        {
                            this.visible = ReadStringUInt32(currentText, split_space);
                        }
                        else if (currentText.StartsWith("	shading"))
                        {
                            this.shading = ReadStringUInt32(currentText, split_space);
                        }
                        else if (currentText.StartsWith("	facet"))
                        {
                            this.facet = ReadStringsingle(currentText, split_space);
                        }
                        else if (currentText.StartsWith("	vertex") && !currentText.StartsWith("	vertexattr"))
                        {
                            //Debug.Log("Reading vert");
                            vartex_count     = ReadStringUInt32(currentText, split_space);
                            this.vertex_list = new VertexList(sreader, vartex_count);
                        }
                        else if (currentText.StartsWith("	face") && !currentText.StartsWith("	facet"))
                        {
                            //Debug.Log("Reading face");
                            face_count     = ReadStringUInt32(currentText, split_space);
                            polygon_count  = face_count;
                            this.face_list = new FaceList(sreader, face_count, polygon_count);
                        }
                        currentText = sreader.ReadLine();
                    }
                }
Ejemplo n.º 14
0
        /// <summary>
        /// Allows capabilities of comparing vectors in the projected space and give an ID to the unknown data.
        /// </summary>
        /// <param name="Face"> Face to be categorized</param>
        /// <param name="Decision"> Decision type. Either KNN or ClossestNeighbor</param>
        /// <param name="neighborNumber">How many neighbors to consider if using KNN</param>
        /// <returns></returns>
        public int PredictClassInProjectedSpace(ATTFace Face, DecisionType Decision = DecisionType.ClossestNeighbor, int neighborNumber = 3)
        {
            double[] projected = ComputeLDAProjection(Face);
            int      ID        = -1;

            foreach (ATTFace ReferenceFace in FaceList)
            {
                double[] y    = ReferenceFace.LDAProjection;
                double   dist = EuclideanDistance(y, projected);
                ReferenceFace.Closeness = dist;
            }
            FaceList.Sort();
            if (Decision == DecisionType.ClossestNeighbor)
            {
                ID = FaceList[0].personID;
            }
            else if (Decision == DecisionType.KNN)
            {
                IDictionary <int, int> Tally = new Dictionary <int, int>();
                int maxVotes = 0;
                ID = -1;
                for (int i = 0; i < neighborNumber; i++)
                {
                    ATTFace Person = FaceList[i];
                    if (Tally.ContainsKey(Person.personID))
                    {
                        Tally[Person.personID]++;
                        if (Tally[Person.personID] > maxVotes)
                        {
                            //To be here, a personID needs at leats two votes
                            maxVotes = Tally[Person.personID];
                            ID       = Person.personID;
                        }
                    }
                    else
                    {
                        Tally.Add(Person.personID, 1);
                    }
                }
            }
            return(ID);
        }
Ejemplo n.º 15
0
        private async void deleteFacesButton_Click(object sender, EventArgs e)
        {
            PersonGroup selectedPersonGroup = personGroups[personGroupSelector.SelectedIndex];
            Person      selectedPerson      = persons[personSelector.SelectedIndex];

            FaceListMetadata[] faceListMetaData = await faceServiceClient.ListFaceListsAsync();

            foreach (FaceListMetadata meta in faceListMetaData)
            {
                if (meta.Name == selectedPerson.Name)
                {
                    FaceList faceList = await faceServiceClient.GetFaceListAsync(meta.FaceListId);

                    PersistedFace[] persistedFaces = faceList.PersistedFaces;
                    foreach (PersistedFace f in persistedFaces)
                    {
                        await faceServiceClient.DeleteFaceFromFaceListAsync(faceList.FaceListId, f.PersistedFaceId);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="data">The exiftool data which is needed to build this object</param>
        internal ImageInfo(ExifToolPictureData data)
        {
            _ExifToolPictureData = data;

             // Create the face list with all XMP faces
             _XmpFaces = new FaceList();
             if (data.RegionInfoMp != null && data.RegionInfoMp.Regions != null)
             {
            foreach (RegionMp region in data.RegionInfoMp.Regions)
            {
               string[] rect = region.Rectangle.Split(new char[] { ',' });
               float x, y, w, h;
               x = (float)Math.Round(Convert.ToSingle(rect[0]), Precision);
               y = (float)Math.Round(Convert.ToSingle(rect[1]), Precision);
               w = (float)Math.Round(Convert.ToSingle(rect[2]), Precision);
               h = (float)Math.Round(Convert.ToSingle(rect[3]), Precision);
               Face f = new Face(region.PersonConvertedName, new RectangleF(x, y, w, h));
               _XmpFaces.Add(f);
            }
             }

             // Create the face list with all Picasa faces
             _PicasaFaces = new FaceList();
             if (data.RegionInfo.RegionList != null)
             {
            foreach (ExifTool.Region region in data.RegionInfo.RegionList)
            {

               float x, y, w, h;

               x = (float)Math.Round(region.Area.X - (region.Area.W / 2), Precision);
               y = (float)Math.Round(region.Area.Y - (region.Area.H / 2), Precision);
               w = (float)Math.Round(region.Area.W, Precision);
               h = (float)Math.Round(region.Area.H, Precision);
               Face f = new Face(region.PersonConvertedName, new RectangleF(x, y, w, h));
               _PicasaFaces.Add(f);
            }
             }
        }
        public Drawing(Template template)
        {
            if (template == null)
            {
                throw new System.ArgumentNullException("template");
            }

            this.dom = template.LoadCleanDOM();

            this._pages = new PageList(this);
            this._faces = new FaceList();
            this._windows = new List<Window>();
            this._colors = new List<ColorEntry>();

            var masters_el = this.dom.Root.ElementVisioSchema2003("Masters");
            if (masters_el == null)
            {
                throw new System.InvalidOperationException();
            }

            // Store information about each master found in the drawing
            foreach (var master_el in masters_el.ElementsVisioSchema2003("Master"))
            {
                var name = master_el.Attribute("NameU").Value;
                var id = int.Parse(master_el.Attribute("ID").Value);

                var subshapes = master_el.Descendants()
                    .Where(el => el.Name.LocalName == "Shape")
                    .ToList();

                var count_groups = subshapes.Count(shape_el => shape_el.Attribute("Type").Value == "Group");

                bool master_is_group = count_groups > 0;

                var md = new MasterMetadata();
                md.Name = name;
                md.ID = id;
                md.IsGroup = master_is_group;
                md.SubShapeCount = subshapes.Count();

                this.master_metadata[md.Name] = md;

                this.CurrentShapeID = 1;
            }

            var facenames_el = this.dom.Root.ElementVisioSchema2003("FaceNames");
            foreach (var face_el in facenames_el.ElementsVisioSchema2003("FaceName"))
            {
                var id = int.Parse(face_el.Attribute("ID").Value);
                var name = face_el.Attribute("Name").Value;
                var face = new Face(id, name);
                this._faces.Add(face);
            }

            var colors_el = this.dom.Root.ElementVisioSchema2003("Colors");
            foreach (var color_el in colors_el.ElementsVisioSchema2003("ColorEntry"))
            {
                var rgb_s = color_el.Attribute("RGB").Value;
                int rgb = int.Parse(rgb_s.Substring(1), System.Globalization.NumberStyles.AllowHexSpecifier);
                var ce = new ColorEntry();
                ce.RGB = rgb;
                this._colors.Add(ce);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Check the Pictures, if delta is found, set it to DeltaList
        /// </summary>
        /// <returns>true, DeltaList is built</returns>
        public bool CheckPics()
        {
            _DeltaList = new FaceList();
             _OnlyInPicasa = new FaceList();
             _OnlyInExif = new FaceList();
             _RegionMismatch = new FaceList();
             _WriteData = new FaceList();
            #if oldcode
             // 1) if there are faces in Picasa and none in exif: copy all
             // 2) if there are none in Picasa and some in exif: do nothing
             // 3) compare, list difference

             // 1)
             if (ExifInfoMissing && !PicasaInfoMissing)
             {
            foreach (KeyValuePair<string, Face> kp in PicasaInfo.Faces)
            {
               _DeltaList.Add(kp.Key, kp.Value);
               _OnlyInPicasa.Add(kp.Key, kp.Value);
               _WriteData.Add(kp.Key, kp.Value);
               Debug.WriteLine("No XMP Info read with exiftool", this.FileName);
            }
            return true;
             }
             // 2)
             if (PicasaInfoMissing && !ExifInfoMissing)
             {
            foreach (KeyValuePair<string, Face> kp in ExifInfo.Faces)
            {
               _OnlyInExif.Add(kp.Key, kp.Value);
               _WriteData.Add(kp.Key, kp.Value);
               Debug.WriteLine("XMP Info available but none from Picasa", this.FileName);
            }
            return false;
             }
             // 3) Compare: not only the name, also the region
             foreach (KeyValuePair<string, Face> kp in PicasaInfo.Faces)
             {
            if (!ExifInfo.Faces.ContainsKey(kp.Key))
            {  // name was found in Picasa but not in exif. But what if it was
               // renamed in picasa? we add it here, but we have to check it
               // when reading exiftool data later on
               _DeltaList.Add(kp.Key, kp.Value);
               _OnlyInPicasa.Add(kp.Key, kp.Value);
               Debug.WriteLine("Found in Picasa but not in XMP", this.FileName);
               _WriteData.Add(kp.Key, kp.Value);
            }
            else
            { // how about the region?
               if (!CompareRectangle(kp.Value.Rect, ExifInfo.Faces[kp.Key].Rect))
               {
                  if (_RegionMismatch.ContainsKey(kp.Key))
                  {
                     _RegionMismatch.Add(kp.Key, kp.Value);
                  }
                  else
                  {
                     Debug.WriteLine("Rectangle mismatch", this.FileName);
                     _WriteData.Add(kp.Key, kp.Value);
                     _DeltaList.Add(kp.Key, kp.Value);
                  }
               }
               else
               { // is the same, so add to "write data" (otherwise we loose this info)
                  Debug.WriteLine("Same in Picasa and XMP", this.FileName);
                  _WriteData.Add(kp.Key, kp.Value);
               }
            }
             }
             foreach (KeyValuePair<string, Face> kp in ExifInfo.Faces)
             {
            if (!PicasaInfo.Faces.ContainsKey(kp.Key))
            {  // Name in Exif but not in Picasa. As picasa has the higher priority,
               // we have to check whether the region is already used or not
               bool found = false;
               foreach (KeyValuePair<string, Face> alreadyHere in _WriteData)
               {
                  if (CompareRectangle(alreadyHere.Value.Rect, kp.Value.Rect, 10))
                  { // yes, it is here! Ignore this one
                     found = true;
                     break;
                  }
               }
               if (!found)
               {
                  _OnlyInExif.Add(kp.Key, kp.Value);
                  _WriteData.Add(kp.Key, kp.Value);
                  Debug.WriteLine("Found in XMP but not in Picasa", this.FileName);
               }
               else
               {
                  _DeltaList.Add(kp.Key, kp.Value);
               }
            }
            else
            { // region?
               if (!CompareRectangle(kp.Value.Rect, PicasaInfo.Faces[kp.Key].Rect))
               {
                  if (_RegionMismatch.ContainsKey(kp.Key))
                  {
                     _RegionMismatch.Add(kp.Key, kp.Value);
                  }
                  else
                  {
                     if (!_WriteData.ContainsKey(kp.Key))
                     {
                        _WriteData.Add(kp.Key, kp.Value);
                     }
                  }
               }
               else
               { // is the same, so add to "write data" (otherwise we loose this info)
                  if (!_WriteData.ContainsKey(kp.Key))
                  {
                     Debug.WriteLine("Same in Picasa and XMP", this.FileName);
                     _WriteData.Add(kp.Key, kp.Value);
                  }
               }
            }
             }
            #endif
             return _WriteData.Count > 0;
        }
Ejemplo n.º 19
0
        public override Task Rebuild()
        {
            this.DebugDepth("Rebuild");
            bool valuesChanged = Diameter == double.MinValue;

            if (StartPercent < 0 ||
                StartPercent > 100)
            {
                StartPercent  = Math.Min(100, Math.Max(0, StartPercent));
                valuesChanged = true;
            }

            using (RebuildLock())
            {
                ResetMeshWrapperMeshes(Object3DPropertyFlags.All, CancellationToken.None);

                // remember the current matrix then clear it so the parts will rotate at the original wrapped position
                var currentMatrix = Matrix;
                Matrix = Matrix4X4.Identity;

                var meshWrapperEnumerator = WrappedObjects();

                var aabb = this.GetAxisAlignedBoundingBox();

                if (Diameter == double.MinValue)
                {
                    // uninitialized set to a reasonable value
                    Diameter = (int)aabb.XSize;
                    // TODO: ensure that the editor display value is updated
                }

                if (Diameter > 0)
                {
                    var radius        = Diameter / 2;
                    var circumference = MathHelper.Tau * radius;
                    rotationCenter = new Vector2(aabb.MinXYZ.X + (aabb.MaxXYZ.X - aabb.MinXYZ.X) * (StartPercent / 100), aabb.MaxXYZ.Y + radius);
                    foreach (var object3Ds in meshWrapperEnumerator)
                    {
                        var matrix = object3Ds.original.WorldMatrix(this);
                        if (!BendCcw)
                        {
                            // rotate around so it will bend correctly
                            matrix *= Matrix4X4.CreateTranslation(0, -aabb.MaxXYZ.Y, 0);
                            matrix *= Matrix4X4.CreateRotationX(MathHelper.Tau / 2);
                            matrix *= Matrix4X4.CreateTranslation(0, aabb.MaxXYZ.Y - aabb.YSize, 0);
                        }

                        var matrixInv = matrix.Inverted;

                        var curvedMesh = object3Ds.meshCopy.Mesh;

                        // split long edges so it will be curved
                        if (false)
                        {
                            double numRotations   = aabb.XSize / circumference;
                            double numberOfCuts   = numRotations * MinSidesPerRotation;
                            var    maxXLength     = aabb.XSize / numberOfCuts;
                            var    maxXLengthSqrd = maxXLength * maxXLength;

                            // convert the mesh into vertex and face arrays
                            double[] v;
                            int[]    f;
                            v = curvedMesh.Vertices.ToDoubleArray(object3Ds.meshCopy.Matrix);
                            f = curvedMesh.Faces.ToIntArray();

                            // make lists so we can add to them
                            var vL = v.ToVector3List();
                            vL.Transform(matrix);
                            var fL = new FaceList(f, curvedMesh.Vertices);

                            Teselate.SplitEdges(vL, fL, maxXLength);
                            vL.Transform(matrixInv);

                            // convert the lists back into the mesh
                            object3Ds.meshCopy.Mesh = new Mesh(vL, fL);
                            curvedMesh = object3Ds.meshCopy.Mesh;
                        }

                        for (int i = 0; i < curvedMesh.Vertices.Count; i++)
                        {
                            var worldPosition = curvedMesh.Vertices[i].Transform((Matrix4X4)matrix);

                            var angleToRotate      = ((worldPosition.X - rotationCenter.X) / circumference) * MathHelper.Tau - MathHelper.Tau / 4;
                            var distanceFromCenter = rotationCenter.Y - worldPosition.Y;

                            var rotatePosition = new Vector3Float(Math.Cos(angleToRotate), Math.Sin(angleToRotate), 0) * distanceFromCenter;
                            rotatePosition.Z = worldPosition.Z;
                            var worldWithBend = rotatePosition + new Vector3Float(rotationCenter.X, radius + aabb.MaxXYZ.Y, 0);
                            curvedMesh.Vertices[i] = worldWithBend.Transform(matrixInv);
                        }

                        curvedMesh.MarkAsChanged();
                        curvedMesh.CalculateNormals();
                    }

                    if (!BendCcw)
                    {
                        // fix the stored center so we draw correctly
                        rotationCenter = new Vector2(rotationCenter.X, aabb.MinXYZ.Y - radius);
                    }
                }

                // set the matrix back
                Matrix = currentMatrix;
            }

            Parent?.Invalidate(new InvalidateArgs(this, InvalidateType.Mesh));
            if (valuesChanged)
            {
                Invalidate(InvalidateType.DisplayValues);
            }

            return(Task.CompletedTask);
        }
        public static Mesh BuildMeshFromLevelingData(PrinterConfig printer)
        {
            var printerShim = ApplicationController.Instance.Shim(printer);
            PrintLevelingData levelingData = printer.Settings.Helpers.PrintLevelingData;
            var currentLevelingFunctions   = new LevelingFunctions(printerShim, levelingData);

            var vertices = new List <Vector3Float>();

            var pointCounts = new Dictionary <Vector3Float, int>();

            var points = new int[3];

            var faces = new FaceList();

            // Add top faces
            foreach (var region in currentLevelingFunctions.Regions)
            {
                int i = 0;

                foreach (var point in new[] { new Vector3Float(region.V0), new Vector3Float(region.V1), new Vector3Float(region.V2) })
                {
                    int index = vertices.IndexOf(point);
                    if (index == -1)
                    {
                        index = vertices.Count;
                        vertices.Add(point);
                    }

                    if (!pointCounts.TryGetValue(point, out int pointCount))
                    {
                        pointCount = 0;
                    }

                    pointCounts[point] = pointCount + 1;

                    points[i++] = index;
                }

                faces.Add(new Face(points[0], points[2], points[1], vertices));
            }

            List <Vector3Float> outerPoints = GetOuterPoints(vertices, pointCounts, printer.Bed.BedCenter);

            // Add reflected hull points at the bed - reflected point for item in negative z should be the negative value
            var reflectedVertices = outerPoints.Select(h => new Vector3Float(h.X, h.Y, h.Z > 0 ? 0 : h.Z)).ToList();

            vertices.AddRange(reflectedVertices);

            int lastReflected = vertices.IndexOf(reflectedVertices.Last());

            int currIndex, reflectedIndex, nextIndex = -1;

            var anchorIndex = vertices.IndexOf(reflectedVertices.First());

            // Loop over all outer points, reflecting a point onto the bed and stitching the current, reflect and next points together
            for (var i = 0; i < outerPoints.Count; i++)
            {
                var point     = outerPoints[i];
                var reflected = reflectedVertices[i];

                bool lastIndex = (i == outerPoints.Count - 1);

                Vector3Float nextPoint = lastIndex ? outerPoints.First() : outerPoints[i + 1];

                currIndex      = vertices.IndexOf(point);
                nextIndex      = vertices.IndexOf(nextPoint);
                reflectedIndex = vertices.IndexOf(reflected);

                Face faceA, faceB;

                // Add face back to previous
                faces.Add(faceB = new Face(currIndex, lastReflected, reflectedIndex, vertices));

                // Add face for current
                faces.Add(faceA = new Face(currIndex, reflectedIndex, nextIndex, vertices));

                lastReflected = reflectedIndex;
            }

            // Add bottom faces
            foreach (var region in currentLevelingFunctions.Regions)
            {
                int i = 0;

                foreach (var point in new[] { GetReflected(region.V0), GetReflected(region.V1), GetReflected(region.V2) })
                {
                    int index = vertices.IndexOf(point);
                    if (index == -1)
                    {
                        index = vertices.Count;
                        vertices.Add(point);
                    }

                    points[i++] = index;
                }

                faces.Add(new Face(points[0], points[1], points[2], vertices));
            }

            return(new Mesh(vertices, faces));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 获取当前facelist信息
        /// </summary>
        /// <returns></returns>
        public FaceList GetCurrentFaceListInfo()
        {
            FaceList info = GetFaceListInfoById(FaceListId).Result;

            return(info);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Constructor
 /// </summary>
 public PictureComparer()
 {
     _DeltaList = new FaceList();
      _OnlyInPicasa = new FaceList();
      _OnlyInExif = new FaceList();
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public PictureInfo()
 {
     XmpFaces = new FaceList();
      PicasaFaces = new FaceList();
 }
Ejemplo n.º 24
0
    /// <summary>
    /// 保持摄像头图片
    /// </summary>
    /// <param name="t"></param>
    public void Save(Texture t)
    {
        Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, true);

        t2d = TextureExtentions.TextureToTexture2D(t);
        t2d.Apply();
        //编码
        byte[] imageTytes = t2d.EncodeToJPG();

        //存储到本地
        //File.WriteAllBytes(Application.streamingAssetsPath + "/FaceDetect/" + Time.time + ".jpg", imageTytes);
        //构建百度人脸识别所需数据
        //图片数据
        var imgData = Convert.ToBase64String(imageTytes);
        //图片类型
        var imageType = "BASE64";
        //需要的参数
        var options = new Dictionary <string, object> {
            { "face_field", "age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype" },
            { "max_face_num", 2 },
            { "face_type", "LIVE" },
        };
        //请求识别
        var result = mClient.Detect(imgData, imageType, options);
        //返回的人脸识别结果
        var data = JsonUtility.FromJson <FaceRootData>(result.ToString());

        //Debug.Log(data.error_code + "       " + data.result.face_num + "      " + result);
        if (data != null && data.result != null && data.result.face_list != null && data.result.face_list.Count > 0 && data.result.face_list[0].landmark72 != null)
        {
            //此处仅取第一个人脸数据来显示
            FaceList face = data.result.face_list[0];
            //设置角度
            //var _ange = data.result.face_list[0].angle;
            //PointRoot.transform.localRotation = Quaternion.Euler(new Vector3(_ange.pitch, _ange.yaw, _ange.roll));

            //设置72个关键点坐标
            for (int i = 0; i < data.result.face_list[0].landmark72.Count; i++)
            {
                var _itemData = data.result.face_list[0].landmark72[i];
                PointList[i].transform.localPosition = new Vector3(_itemData.x, _itemData.y, 0); //new Vector3(_itemData.x / ratioX, _itemData.y / ratioX, 0); //new Vector3(_itemData.x / ratioX, _itemData.y / ratioX, 0);
                //PointList[i].SetActive(true);

                //Debug.Log(i + "       " + _itemData.x + "         " + _itemData.y);
            }

            double eye1 = PointList[19].transform.localPosition.y - PointList[15].transform.localPosition.y;
            double eye2 = PointList[36].transform.localPosition.y - PointList[32].transform.localPosition.y;
            //Debug.Log("eye1:"+eye1);
            double width1 = PointList[17].transform.localPosition.x - PointList[13].transform.localPosition.x;
            double width2 = PointList[34].transform.localPosition.x - PointList[30].transform.localPosition.x;
            double race1  = eye1 / width1;
            double race2  = eye2 / width2;
            //Debug.Log("race1:" + race1);
            double mouth = PointList[64].transform.localPosition.y - PointList[60].transform.localPosition.y;
            //Debug.Log ("mouth: "+mouth);
            double nose_width = PointList[54].transform.localPosition.x - PointList[49].transform.localPosition.x;
            //Debug.Log ("width: "+mouth_width);
            double race3 = mouth / nose_width;

            /*if (race3 > max3)
             *  max3 = race3;
             * if (race3 <= min3)
             *  min3 = race3;*/
            double headDir    = PointList[12].transform.localPosition.y - PointList[0].transform.localPosition.y;
            double head_width = PointList[12].transform.localPosition.x - PointList[0].transform.localPosition.x;

            double zhuanL = PointList[50].transform.localPosition.x - PointList[1].transform.localPosition.x;
            //Debug.Log("zhuanL:"+zhuanL);
            zhuan = face.angle.yaw;
            //Debug.Log(zhuan);

            pitch = face.angle.pitch;
            //Debug.Log("pitch:"+pitch);
            roll = face.angle.roll;
            //Debug.Log("roll:" + roll);

            if (headDir > 0 && headDir > head_width * 0.15)
            {
                state4 = 1;
            }
            else if (headDir < 0 && headDir < head_width * -0.15)
            {
                state4 = -1;
            }
            else
            {
                state4 = 0;
            }


            if (race1 > max1)
            {
                max1 = race1;
            }
            if (race1 <= min1)
            {
                min1 = race1;
            }

            //Debug.Log ("race: "+race1);
            //state1 = 0;
            if (race1 < min1)
            {
                min1 = race1;
            }
            if (race2 < min2)
            {
                min2 = race2;
            }
            if (race3 < min3)
            {
                min3 = race3;
            }
            if (race1 > max1)
            {
                max1 = race1;
            }
            if (race2 > max2)
            {
                max2 = race2;
            }
            if (race3 > max3)
            {
                max3 = race3;
            }
            if (race1 >= 0.28)
            {
                state1 = 0;
            }
            else if (race1 < 0.28)
            {
                state1 = 1;
            }
            //else
            //{
            //    state1 = 0.5;
            //}
            if (race2 > 0.35)
            {
                state2 = 0;
            }
            else if (race2 < 0.28)
            {
                state2 = 1;
            }
            else
            {
                state2 = 0.5;
            }
            //                                      state1 = 1-((race1 - min1) / (max1 - min1));
            //                                      state2 = 1-((race2 - min2) / (max2 - min2));
            state3 = 1 - ((race3 - min3) / (max3 - min3));
            if (state3 > 0.75)
            {
                state3 = 1;
            }
            //state1 = 0;
            //state1 = 0;
            //Debug.Log ("max: "+max1);
            //Debug.Log ("min: "+min1);
            //Debug.Log("state3: " + state3);
            //显示年龄 性别等信息
            mResultText.text = string.Format(@"年龄:{0}      性别:{1}", face.age, face.gender.type == "male" ? "男" : "女");
        }

        Destroy(t2d);
        t2d = null;
    }
Ejemplo n.º 25
0
        public virtual void FromStream(Stream s, bool id)
        {
            Action <Action> action = delegate(Action a)
            {
                try
                {
                    a();
                }
                catch (Exception)
                {
                    LoadErrCount++;
                }
            };
            PmxHeader head = new PmxHeader();

            head.FromStreamEx(s);
            Header.FromHeader(head);
            head.ElementFormat.WithID = id;
            action(delegate
            {
                ModelInfo.FromStreamEx(s, head.ElementFormat);
            });
            int count = 0;

            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            VertexList.Clear();
            VertexList.Capacity = count;
            for (int k = 0; k < count; k++)
            {
                PmxVertex v = new PmxVertex();
                action(delegate
                {
                    v.FromStreamEx(s, head.ElementFormat);
                });
                VertexList.Add(v);
            }
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            FaceList.Clear();
            FaceList.Capacity = count;
            for (int l = 0; l < count; l++)
            {
                int ix = 0;
                action(delegate
                {
                    ix = PmxStreamHelper.ReadElement_Int32(s, head.ElementFormat.VertexSize, signed: false);
                });
                FaceList.Add(ix);
            }
            PmxTextureTable tx = new PmxTextureTable();

            action(delegate
            {
                tx.FromStreamEx(s, head.ElementFormat);
            });
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            MaterialList.Clear();
            MaterialList.Capacity = count;
            for (int m = 0; m < count; m++)
            {
                PmxMaterial j = new PmxMaterial();
                action(delegate
                {
                    j.FromStreamEx_TexTable(s, tx, head.ElementFormat);
                });
                MaterialList.Add(j);
            }
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            BoneList.Clear();
            BoneList.Capacity = count;
            for (int n = 0; n < count; n++)
            {
                PmxBone b = new PmxBone();
                action(delegate
                {
                    b.FromStreamEx(s, head.ElementFormat);
                });
                BoneList.Add(b);
            }
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            MorphList.Clear();
            MorphList.Capacity = count;
            for (int num = 0; num < count; num++)
            {
                PmxMorph morph = new PmxMorph();
                action(delegate
                {
                    morph.FromStreamEx(s, head.ElementFormat);
                });
                MorphList.Add(morph);
            }
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            NodeList.Clear();
            NodeList.Capacity = count;
            for (int num2 = 0; num2 < count; num2++)
            {
                PmxNode node = new PmxNode();
                action(delegate
                {
                    node.FromStreamEx(s, head.ElementFormat);
                });
                NodeList.Add(node);
                if (NodeList[num2].SystemNode)
                {
                    if (NodeList[num2].Name == "Root")
                    {
                        RootNode = NodeList[num2];
                    }
                    else if (NodeList[num2].Name == "表情")
                    {
                        ExpNode = NodeList[num2];
                    }
                }
            }
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            BodyList.Clear();
            BodyList.Capacity = count;
            for (int num3 = 0; num3 < count; num3++)
            {
                PmxBody b2 = new PmxBody();
                action(delegate
                {
                    b2.FromStreamEx(s, head.ElementFormat);
                });
                BodyList.Add(b2);
            }
            action(delegate
            {
                count = PmxStreamHelper.ReadElement_Int32(s);
            });
            JointList.Clear();
            JointList.Capacity = count;
            for (int num4 = 0; num4 < count; num4++)
            {
                PmxJoint i = new PmxJoint();
                action(delegate
                {
                    i.FromStreamEx(s, head.ElementFormat);
                });
                JointList.Add(i);
            }
            if (head.Ver >= 2.1f)
            {
                action(delegate
                {
                    count = PmxStreamHelper.ReadElement_Int32(s);
                });
                SoftBodyList.Clear();
                SoftBodyList.Capacity = count;
                for (int num5 = 0; num5 < count; num5++)
                {
                    PmxSoftBody b3 = new PmxSoftBody();
                    action(delegate
                    {
                        b3.FromStreamEx(s, head.ElementFormat);
                    });
                    SoftBodyList.Add(b3);
                }
            }
            if (id)
            {
                action(delegate
                {
                    FilePath = PmxStreamHelper.ReadString(s, head.ElementFormat);
                });
            }
            head.ElementFormat.WithID = false;
        }
Ejemplo n.º 26
0
        public void FromPmx(Pmx pmx)
        {
            Clear();
            FilePath     = pmx.FilePath;
            LoadErrCount = pmx.LoadErrCount;
            Header       = pmx.Header.Clone();
            ModelInfo    = pmx.ModelInfo.Clone();
            int count = pmx.VertexList.Count;

            VertexList.Capacity = count;
            for (int i = 0; i < count; i++)
            {
                VertexList.Add(pmx.VertexList[i].Clone());
            }
            count             = pmx.FaceList.Count;
            FaceList.Capacity = count;
            for (int j = 0; j < count; j++)
            {
                FaceList.Add(pmx.FaceList[j]);
            }
            count = pmx.MaterialList.Count;
            MaterialList.Capacity = count;
            for (int k = 0; k < count; k++)
            {
                MaterialList.Add(pmx.MaterialList[k].Clone());
            }
            count             = pmx.BoneList.Count;
            BoneList.Capacity = count;
            for (int l = 0; l < count; l++)
            {
                BoneList.Add(pmx.BoneList[l].Clone());
            }
            count = pmx.MorphList.Count;
            MorphList.Capacity = count;
            for (int m = 0; m < count; m++)
            {
                MorphList.Add(pmx.MorphList[m].Clone());
            }
            count = pmx.NodeList.Count;
            NodeList.Clear();
            NodeList.Capacity = count;
            for (int n = 0; n < count; n++)
            {
                NodeList.Add(pmx.NodeList[n].Clone());
                if (NodeList[n].SystemNode)
                {
                    if (NodeList[n].Name == "Root")
                    {
                        RootNode = NodeList[n];
                    }
                    else if (NodeList[n].Name == "表情")
                    {
                        ExpNode = NodeList[n];
                    }
                }
            }
            count             = pmx.BodyList.Count;
            BodyList.Capacity = count;
            for (int num = 0; num < count; num++)
            {
                BodyList.Add(pmx.BodyList[num].Clone());
            }
            count = pmx.JointList.Count;
            JointList.Capacity = count;
            for (int num2 = 0; num2 < count; num2++)
            {
                JointList.Add(pmx.JointList[num2].Clone());
            }
            count = pmx.SoftBodyList.Count;
            SoftBodyList.Capacity = count;
            for (int num3 = 0; num3 < count; num3++)
            {
                SoftBodyList.Add(pmx.SoftBodyList[num3].Clone());
            }
        }
Ejemplo n.º 27
0
        Mesh MakeMesh(FaceList <Vector3> faceList, string textureName)
        {
            // MeshVertices<Vector3> verts, VertexNormals<Vector3> vertNormals, VertexUV<Vector2> vertUV

            // Must remain the same length.
            var meshVerts = new List <Vector3>();
            var meshUV    = new List <Vector2>();
            var meshNorms = new List <Vector3>();
            var meshUV2   = new List <Vector2>(); // bottom left corner of subtexture in atlas
            var meshUV3   = new List <Vector2>(); // top right corner of subtexture in atlas

            // References into part level mesh data
            var optVerts   = Part.verts;
            var optNormals = Part.vertNormals;
            var optUV      = Part.vertUV;

            // Unity can only have one normal and UV per vertex.
            // All sub-meshes (triangle lists) in the same mesh have to share the same vertex list.
            // This data uses normal and UV data per face, per vertex.
            // So we have to make a new vertex any time a polygon references a different normal
            // or UV than another polygon.
            var usedVertLookup = new Dictionary <VertexSplitTuple, int>();

            // Workaround for sat1.opt: no Tex00005 on LOD1.
            int texId = 0;

            Part.Craft.TextureAtlas.Layout.TextureId.TryGetValue(textureName, out texId);

            Rect atlasRect = Part.Craft.TextureAtlas.Layout.GetUvLocation(texId);

            // Build the vert/normal/UV lists
            var triangles = new List <int>();

            for (int i = 0; i < faceList.Count; i++)
            {
                var newVertRefs = new int[4];

                // Some normals in xwing98 tug, xwing98 bwing, xwa shuttle and possibly others, are garbage data.
                // Other normals in the vicinity might also garbage, so flate shade the entire face.
                bool rejectNormal = false;
                for (int j = 0; j < 4; j++)
                {
                    var id = faceList.VertexNormalRef[i][j];
                    if (id < 0 || id >= optNormals.Normals.Count || optNormals.Normals[id] == Vector3.zero)
                    {
                        rejectNormal = true;
                    }
                }

                // check each point for need to generate new vertex
                for (int j = 0; j < 4; j++)
                {
                    VertexSplitTuple vt;
                    vt.vId    = faceList.VertexRef[i][j];
                    vt.uvId   = faceList.UVRef[i][j];
                    vt.normId = faceList.VertexNormalRef[i][j];
                    vt.texId  = texId;

                    // Some faces are triangles instead of quads.
                    if (vt.vId == -1 || vt.uvId == -1 || vt.normId == -1)
                    {
                        newVertRefs[j] = -1;
                        continue;
                    }

                    // Some normals in xwing98 tug, xwing98 bwing, xwa shuttle and possibly others, are garbage data.
                    // Zero normals can cause unity lighting problems.  Fallback on face normal.
                    Vector3 normal;
                    if (rejectNormal)
                    {
                        normal = GetFaceNormal(faceList.VertexRef[i], optVerts);
                    }
                    else
                    {
                        normal = optNormals.Normals[vt.normId];
                    }

                    if (usedVertLookup.ContainsKey(vt) && !rejectNormal)
                    {
                        // reuse the vertex
                        newVertRefs[j] = usedVertLookup[vt];
                    }
                    else
                    {
                        // make a new one
                        if (vt.vId > optVerts.Vertices.Count - 1)
                        {
                            Debug.LogError(string.Format(CultureInfo.CurrentCulture, "Vert {0}/{4} out of bound {1:X} {2} {3} ", vt.vId, faceList.OffsetInFile, i, j, optVerts.Vertices.Count));
                        }
                        if (vt.normId > optNormals.Normals.Count - 1)
                        {
                            Debug.LogError(string.Format(CultureInfo.CurrentCulture, "Normal {0}/{4} out of bound {1:X} {2} {3} ", vt.normId, faceList.OffsetInFile, i, j, optNormals.Normals.Count));
                        }
                        if (vt.uvId > optUV.Vertices.Count - 1)
                        {
                            Debug.LogError(string.Format(CultureInfo.CurrentCulture, "UV {0}/{4} out of bound {1:X} {2} {3} ", vt.uvId, faceList.OffsetInFile, i, j, optUV.Vertices.Count));
                        }
                        meshVerts.Add(optVerts.Vertices[vt.vId]);
                        meshNorms.Add(normal.normalized);

                        // translate uv to atlas space
                        Vector2 uv = optUV.Vertices[vt.uvId];
                        //uv.x = uv.x * atlasRect.width + atlasRect.xMin;
                        //uv.y = uv.y * atlasRect.height + atlasRect.yMin;
                        meshUV.Add(uv);

                        meshUV2.Add(new Vector2(atlasRect.x, atlasRect.y));
                        meshUV3.Add(new Vector2(atlasRect.width, atlasRect.height));

                        // Index it so we can find it later.
                        usedVertLookup[vt] = meshVerts.Count - 1;
                        newVertRefs[j]     = usedVertLookup[vt];
                    }
                }

                // TODO: Less nieve quad split.
                // First triangle
                triangles.Add(newVertRefs[1]);
                triangles.Add(newVertRefs[0]);
                triangles.Add(newVertRefs[2]);

                // second triangle if a quad
                if (newVertRefs[3] != -1)
                {
                    triangles.Add(newVertRefs[3]);
                    triangles.Add(newVertRefs[2]);
                    triangles.Add(newVertRefs[0]);
                }
            }

            var mesh = new Mesh
            {
                vertices  = meshVerts.ToArray(),
                normals   = meshNorms.ToArray(),
                triangles = triangles.ToArray(),
                uv        = meshUV.ToArray(),
                uv2       = meshUV2.ToArray(),
                uv3       = meshUV3.ToArray(),
            };

            return(mesh);
        }
Ejemplo n.º 28
0
 public HVCTrackingResult()
 {
     this.faces  = new FaceList();
     this.bodies = new BodyList();
     this.hands  = new HandList();
 }
Ejemplo n.º 29
0
        async Task <AiResult> MakeRequest(string imageToCheck)
        {
            AiResult res = new AiResult();
            // imageToCheck = "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg";

            EmotionServiceClient emotionServiceClient = new EmotionServiceClient(emotionKey);

            Emotion[] imageEmotion = await emotionServiceClient.RecognizeAsync(imageToCheck);

            Console.WriteLine("Feeling: " + imageEmotion[0].Scores.ToRankedList().First().Key);
            Console.WriteLine("Top score: " + imageEmotion[0].Scores.ToRankedList().First().Value);

            res.Emotion = string.Format("Unknwn ({0:P2})", 0);
            float bestScore = 0;

            foreach (var em in imageEmotion[0].Scores.ToRankedList())
            {
                if (em.Value > bestScore)
                {
                    bestScore   = em.Value;
                    res.Emotion = res.Emotion = string.Format("{0} ({1:P2})", em.Key, em.Value);
                }
            }

            FaceServiceClient faceServiceClient = new FaceServiceClient(faceKey);
            FaceList          trumpList         = null;

            try
            {
                trumpList = await faceServiceClient.GetFaceListAsync(faceList);
            }
            catch (FaceAPIException apiExp)
            {
                if (apiExp.ErrorCode == "FaceListNotFound")
                {
                    await faceServiceClient.CreateFaceListAsync(faceList, faceList, "A collection of trumps");

                    trumpList = await faceServiceClient.GetFaceListAsync(faceList);
                }
                else
                {
                    throw apiExp;
                }
            }
            if (trumpList.PersistedFaces.Count() < 5)
            {
                await faceServiceClient.AddFaceToFaceListAsync(faceList, "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://thefederalist.com/wp-content/uploads/2016/02/trumpie.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://www.redstate.com/uploads/2016/02/donald-trump-is-still-soaring-in-iowa-but-there-are-now-some-clear-warning-signs.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://i.huffpost.com/gen/3706868/images/o-DONALD-TRUMP-FUNNY-facebook.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://media.salon.com/2015/04/donald_trump_thumbsup.jpg");

                trumpList = await faceServiceClient.GetFaceListAsync(faceList);
            }

            Face[] faceToCompare = await faceServiceClient.DetectAsync(imageToCheck);

            SimilarPersistedFace[] faces = await faceServiceClient.FindSimilarAsync(faceToCompare[0].FaceId, faceList, FindSimilarMatchMode.matchFace);

            res.TrumpMatch = String.Format("{0:P2}", 0);
            if (faces.Count() == 0)
            {
                Console.WriteLine("Sorry, nothing compares to you");
            }
            else
            {
                double totalConfidence = 0;
                foreach (SimilarPersistedFace matching in faces)
                {
                    totalConfidence += matching.Confidence;
                }
                double averageConfidence = totalConfidence / faces.Count();
                res.TrumpMatch = String.Format("{0:P2}", averageConfidence);
                Console.WriteLine("Trump comparison: " + res.TrumpMatch);
            }
            return(res);
        }