Exemplo n.º 1
0
		public static void Write(string file, ScanData data)
		{
			using (StreamWriter w = System.IO.File.CreateText(file))
			{
				w.WriteLine(string.Format("# Create By Sardauscan V{0}",Application.ProductVersion));
				w.WriteLine("#");
				w.WriteLine("# Object");
				List<FaceInfo> faces = new List<FaceInfo>();
				List<Vector3d> vertex = new List<Vector3d>();
				for (int i = 0; i < data.Count; i++) // collect vertices and face
				{
					ScanLine slice = data[i];
					if (slice.IsMesh)
					{
						List<Triangle3D> tris = slice.GetTriangles();
						for (int t = 0; t < tris.Count; t++)
						{
							Triangle3D triangle = tris[t];
							FaceInfo face = new FaceInfo();
							face.v1 = AddToList(vertex, triangle.Point1.Position);
							face.v2 = AddToList(vertex, triangle.Point2.Position);
							face.v3 = AddToList(vertex, triangle.Point3.Position);
							faces.Add(face);
						}
					}
				}
				w.WriteLine(string.Format("# Vertices {0}", vertex.Count));
				for (int i = 0; i < vertex.Count; i++)
					w.WriteLine(string.Format("v {0}",vertex[i].Dump()));
				w.WriteLine(string.Format("# Triangles {0}", faces.Count));
				for (int i = 0; i < faces.Count; i++)
					w.WriteLine(string.Format("f {0} {1} {2}", faces[i].v1 + 1, faces[i].v2 + 1, faces[i].v3 + 1));
			}
		}
Exemplo n.º 2
0
    public FaceInfo Randomise(Simple2x2 pos, Simple2x2 rot, Simple2x2 sc)
    {
        RandomIndex();
        FaceInfo final = new FaceInfo(Index, Colour);

        Vector3 p = new Vector3(pos.RandX(), 0.0F, pos.RandY());

        final._Position = p;

        Vector3 r = new Vector3(0.0F, 0.0F, rot.RandX());

        final._Rotation = r;

        Vector2 s = Utility.RandomMatrixPoint(sc);

        final._Scale = Vector3.one + new Vector3(s.x, s.y, 0.0F);

        return(final);
    }
Exemplo n.º 3
0
        private void saveFace(FaceInfo faceInfo, ImageFrame imageFrame)
        {
            Bitmap bitmap = FaceCropper.getFace(imageFrame.getArgb(), faceInfo, imageFrame.getWidth());

            if (source == RegActivity.SOURCE_REG)
            {
                // 注册来源保存到注册人脸目录
                File faceDir = FileUitls.getFaceDirectory();
                if (faceDir != null)
                {
                    String imageName = Guid.NewGuid().ToString();
                    File   file      = new File(faceDir, imageName);
                    // 压缩人脸图片至300 * 300,减少网络传输时间
                    ImageUtils.resize(bitmap, file, 300, 300);
                    Intent intent = new Intent();
                    intent.PutExtra("file_path", file.AbsolutePath);
                    SetResult(Result.Ok, intent);
                    Finish();
                }
                else
                {
                    toast("注册人脸目录未找到");
                }
            }
            else
            {
                try
                {
                    // 其他来源保存到临时目录
                    File file = File.CreateTempFile(Guid.NewGuid().ToString() + "", ".jpg");
                    // 人脸识别不需要整张图片。可以对人脸区别进行裁剪。减少流量消耗和,网络传输占用的时间消耗。
                    ImageUtils.resize(bitmap, file, 300, 300); Intent intent = new Intent();
                    intent.PutExtra("file_path", file.AbsolutePath);
                    SetResult(Result.Ok, intent);
                    Finish();
                }
                catch (IOException e)
                {
                    e.PrintStackTrace();
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 识别 <paramref name="bitmap"/> 中指定的人脸信息 <paramref name="info"/> 的关键点坐标。
        /// <para>
        /// 当 <see cref="FaceType"/> <see langword="="/> <see cref="FaceType.Normal"/> 时, 需要模型:<see langword="face_landmarker_pts68.csta"/><br/>
        /// 当 <see cref="FaceType"/> <see langword="="/> <see cref="FaceType.Mask"/> 时, 需要模型:<see langword="face_landmarker_mask_pts5.csta"/><br/>
        /// 当 <see cref="FaceType"/> <see langword="="/> <see cref="FaceType.Light"/> 时, 需要模型:<see langword="face_landmarker_pts5.csta"/><br/>
        /// </para>
        /// </summary>
        /// <param name="bitmap">包含人脸的图片</param>
        /// <param name="info">指定的人脸信息</param>
        /// <returns></returns>
        public FaceMarkPoint[] FaceMark(Bitmap bitmap, FaceInfo info)
        {
            byte[] bgr = ImageSet.Get24BGRFromBitmap(bitmap, out int width, out int height, out int channels);
            int    size;

            if (Platform64)
            {
                size = ViewFacePlus64.FaceMarkSize((int)MarkType);
            }
            else
            {
                size = ViewFacePlus32.FaceMarkSize((int)MarkType);
            }
            double[] _pointX = new double[size];
            double[] _pointY = new double[size];
            bool     val;

            if (Platform64)
            {
                val = ViewFacePlus64.FaceMark(bgr, width, height, channels, info.Location.X, info.Location.Y, info.Location.Width, info.Location.Height, _pointX, _pointY, (int)MarkType);
            }
            else
            {
                val = ViewFacePlus32.FaceMark(bgr, width, height, channels, info.Location.X, info.Location.Y, info.Location.Width, info.Location.Height, _pointX, _pointY, (int)MarkType);
            }
            if (val)
            {
                List <FaceMarkPoint> points = new List <FaceMarkPoint>();
                for (int i = 0; i < size; i++)
                {
                    points.Add(new FaceMarkPoint()
                    {
                        X = _pointX[i], Y = _pointY[i]
                    });
                }
                return(points.ToArray());
            }
            else
            {
                throw new Exception("人脸关键点获取失败");
            }
        }
Exemplo n.º 5
0
        protected void onOne2NHandler(FaceEvent e)
        {
            Action d = () =>
            {
                FaceInfo f = e.faceinfo;
                if (f == null)
                {
                    pictureBox_dicFace.Image = null;
                    return;
                }
                if (_lastFaceID == e.faceinfo.faceid)
                {
                    return;
                }

                if (f.userid != 0)
                {
                    _faceCamera.FaceCmd = FaceCamera.FaceCommand.NodShakeDetect;     //转换为检测角度模式

                    UserInfo uinfo = UserInfo.Get(f.userid);
                    label_userinfo.Text =
                        "账号:" + uinfo.usernumber +
                        "\n姓名:" + uinfo.username +
                        "\n性别:" + (uinfo.gender == 0?"男":"女");
                    textBox_balance.Text       = string.Format("{0}", uinfo.money);
                    textBox_payment.Text       = string.Format("{0}", 10);
                    textBox_balanceRemain.Text = "";
                    _faceCamera.SetSpeakOrderedAsync("确认付款请点头,取消付款请摇头。");
                }
                else
                {
                    //输出语音提示,您还没有注册账号
                    _faceCamera.SetSpeakAsync("您尚未注册账号!");
                }
                if (_lastFaceID != e.faceinfo.faceid)
                {
                    _lastFaceID = e.faceinfo.faceid;
                }
            };

            this.BeginInvoke(d);
        }
Exemplo n.º 6
0
 public bool TrackFeatureJudge(FaceInfo l, FaceInfo n)//如果根据传入的两个Faceinfo判断为同一个人(根据特征值判断)则返回1,不是同一人返回0,出错返回-1
 {
     try
     {
         int a = Face_detect_sdk.PFD_FeatureMatching(3000, l.feature, 3000, n.feature);
         if (a > 650)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("PFD_FeatureMatching Error" + ex.ToString());
         return(false);
     }
 }
Exemplo n.º 7
0
    public FaceInfo Randomise(bool gender, Simple2x2 pos, Simple2x2 rot, Simple2x2 sc)
    {
        int      Index = gender ? Random.Range(0, Male.Length) : Random.Range(0, Female.Length);
        FaceInfo final = new FaceInfo(Index, Colour);

        final.Obj = gender ? Male[Index]: Female[Index];

        Vector3 p = new Vector3(pos.RandX(), 0.0F, pos.RandY());

        final._Position = p;

        Vector3 r = new Vector3(0.0F, 0.0F, rot.RandX());

        final._Rotation = r;

        Vector2 s = Utility.RandomMatrixPoint(sc);

        final._Scale = Vector3.one + new Vector3(s.x, s.y, 0.0F);
        return(final);
    }
Exemplo n.º 8
0
        // Convert from FT_FaceInfo to FaceInfo
        FaceInfo GetFaceInfo(FT_FaceInfo ft_face, int scaleFactor)
        {
            FaceInfo face = new FaceInfo();

            face.Name       = ft_face.name;
            face.PointSize  = (float)ft_face.pointSize / scaleFactor;
            face.Padding    = 0;
            face.LineHeight = ft_face.lineHeight / scaleFactor;
            face.Baseline   = 0;
            //m_fontInfo.Ascender = faceInfo.Ascender;
            //m_fontInfo.Descender = faceInfo.Descender;
            face.CenterLine         = ft_face.centerLine / scaleFactor;
            face.Underline          = ft_face.underline / scaleFactor;
            face.UnderlineThickness = ft_face.underlineThickness == 0 ? 5 : ft_face.underlineThickness / scaleFactor; // Set Thickness to 5 if TTF value is Zero.
            face.CharacterCount     = ft_face.characterCount;
            face.AtlasWidth         = ft_face.atlasWidth / scaleFactor;
            face.AtlasHeight        = ft_face.atlasHeight / scaleFactor;

            return(face);
        }
Exemplo n.º 9
0
        private float rgbLiveness(ImageFrame imageFrame, FaceInfo faceInfo)
        {
            long  starttime = DateTime.Now.Millisecond;
            float rgbScore  = FaceLiveness.getInstance().rgbLiveness(imageFrame.getArgb(), imageFrame
                                                                     .getWidth(), imageFrame.getHeight(), faceInfo.Landmarks.ToArray());
            long duration = DateTime.Now.Millisecond - starttime;

            //    runOnUiThread(new Runnable() {
            //    @Override
            //    public void run()
            //    {
            //        rgbLivenssDurationTv.setVisibility(View.VISIBLE);
            //        rgbLivenessScoreTv.setVisibility(View.VISIBLE);
            //        rgbLivenssDurationTv.setText("RGB活体耗时:" + duration);
            //        rgbLivenessScoreTv.setText("RGB活体得分:" + rgbScore);
            //    }
            //});

            return(rgbScore);
        }
Exemplo n.º 10
0
        protected void onOne2NHandler(FaceEvent e)
        {
            Action d = () =>
            {
                FaceInfo f = e.faceinfo;
                if (f == null)
                {
                    pictureBox1.Image = null;
                    return;
                }
                if (_lastFaceID == e.faceinfo.faceid)
                {
                    return;
                }

                if (f.userid != 0)
                {
                    _faceCamera.FaceCmd = FaceCamera.FaceCommand.NodShakeDetect;     //转换为检测角度模式

                    UserInfo uinfo = UserInfo.Get(f.userid);
                    xingming.Text  = uinfo.usernumber;
                    shoujihao.Text = uinfo.phonenumber;
                    yue.Text       = uinfo.money.ToString();
                    _faceCamera.SetSpeakOrderedAsync("确认充值请点头,取消充值请摇头。");
                }
                else
                {
                    xingming.Text  = "";
                    shoujihao.Text = "";
                    yue.Text       = "";
                    //输出语音提示,您还没有注册账号
                    _faceCamera.SetSpeakAsync("您尚未注册账号!");
                }
                if (_lastFaceID != e.faceinfo.faceid)
                {
                    _lastFaceID = e.faceinfo.faceid;
                }
            };

            this.BeginInvoke(d);
        }
        public async Task <JsonResponse> AddIndexAsync(float[] feat, string id = null, string imagePath = "")
        {
            var bAdd = await Task.FromResult(AddIndex(feat, out var index));

            if (!bAdd)
            {
                return(JsonResponse.IndexError());
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                id = Guid.NewGuid().ToString();
            }
            if (imagePath == null)
            {
                imagePath = "";
            }
            FaceInfo faceInfo = new FaceInfo
            {
                Id        = id,
                Index     = index,
                ImagePath = imagePath,
                Feature   = feat
            };

            bAdd = AddFaceInfo(faceInfo);
            if (!bAdd)
            {
                RemoveIndex(index);
            }

            return(new JsonResponse
            {
                Code = 0,
                Msg = "Success",
                Data = new
                {
                    Id = id
                }
            });
        }
Exemplo n.º 12
0
        /**
         * 获取人脸框区域。
         *
         * @return 人脸框区域
         */
        // TODO padding?
        public Rect getFaceRect(FaceInfo faceInfo, ImageFrame frame)
        {
            Rect rect = new Rect();

            int[] points = new int[8];
            faceInfo.GetRectPoints(points);

            int left   = points[2];
            int top    = points[3];
            int right  = points[6];
            int bottom = points[7];

            //            int width = (right - left) * 4 / 3;
            //            int height = (bottom - top) * 4 / 3;
            //
            //            left = getInfo().mCenter_x - width / 2;
            //            top = getInfo().mCenter_y - height / 2;
            //
            //            rect.top = top;
            //            rect.left = left;
            //            rect.right = left + width;
            //            rect.bottom = top + height;

            //            int width = (right - left) * 4 / 3;
            //            int height = (bottom - top) * 5 / 3;
            int width  = (right - left);
            int height = (bottom - top);

            //            left = getInfo().mCenter_x - width / 2;
            //            top = getInfo().mCenter_y - height * 2 / 3;
            left = (int)(faceInfo.MCenterX - width / 2);
            top  = (int)(faceInfo.MCenterY - height / 2);


            rect.Top    = top < 0 ? 0 : top;
            rect.Left   = left < 0 ? 0 : left;
            rect.Right  = (left + width) > frame.getWidth() ? frame.getWidth() : (left + width);
            rect.Bottom = (top + height) > frame.getHeight() ? frame.getHeight() : (top + height);

            return(rect);
        }
Exemplo n.º 13
0
        private void identity(ImageFrame imageFrame, FaceInfo faceInfo)
        {
            float raw   = Java.Lang.Math.Abs(faceInfo.HeadPose[0]);
            float patch = Java.Lang.Math.Abs(faceInfo.HeadPose[1]);
            float roll  = Java.Lang.Math.Abs(faceInfo.HeadPose[2]);

            // 人脸的三个角度大于20不进行识别
            if (raw > 20 || patch > 20 || roll > 20)
            {
                return;
            }

            identityStatus = IDENTITYING;

            long starttime = DateTime.Now.Millisecond;

            int[] argb = imageFrame.getArgb();
            int   rows = imageFrame.getHeight();
            int   cols = imageFrame.getWidth();

            int[] landmarks = faceInfo.Landmarks.ToArray();

            int         type        = PreferencesUtil.getInt(GlobalFaceTypeModel.TYPE_MODEL, GlobalFaceTypeModel.RECOGNIZE_LIVE);
            IdentifyRet identifyRet = null;

            if (type == GlobalFaceTypeModel.RECOGNIZE_LIVE)
            {
                identifyRet = FaceApi.getInstance().identity(argb, rows, cols, landmarks, groupId);
            }
            else if (type == GlobalFaceTypeModel.RECOGNIZE_ID_PHOTO)
            {
                identifyRet = FaceApi.getInstance().identityForIDPhoto(argb, rows, cols, landmarks, groupId);
            }
            if (identifyRet != null)
            {
                displayUserOfMaxScore(identifyRet.getUserId(), identifyRet.getScore());
            }
            identityStatus = IDENTITY_IDLE;
            displayTip("特征抽取对比耗时:" + (DateTime.Now.Millisecond - starttime), featureDurationTv);
        }
Exemplo n.º 14
0
    void Update()
    {
        faceInfo = faceAnimManager.faceInfo;

        if (faceInfo == null || faceInfo.Instances.Length == 0 || faceInfo.Instances[0].face == null || faceInfo.Instances[0].face.landmark == null)
        {
            return;
        }

        Face face = faceInfo.Instances[0].face;

        for (int i = 0; i < landmarkCount; i++)
        {
            Vector2 point = face.landmark[i];
            points[i].position = new Vector2(point.x * Screen.width, Screen.height - point.y * Screen.height);
        }

        points[32].position = new Vector2(face.left_eye.x * Screen.width, Screen.height - face.left_eye.y * Screen.height);
        points[32].GetComponent <UnityEngine.UI.Image>().color = Color.red;
        points[31].position = new Vector2(face.right_eye.x * Screen.width, Screen.height - face.right_eye.y * Screen.height);
        points[31].GetComponent <UnityEngine.UI.Image>().color = Color.green;
    }
Exemplo n.º 15
0
    private void addToFaceSetsAt(int nextToRangeIndex, FaceInfo finfo)
    {
        Range1D   addRange = finfo.range;
        Direction dir      = finfo.direction;

        AssertUtil.Assert(nextToRangeIndex < this.faceSetTableHalfDims.s - 1, "need next to range to be in our table minus one column");

        foreach (int faceSetIndex in faceSetsAtAcrossIndexFlushWithRange(nextToRangeIndex, addRange, dir))
        {
            FaceSet nextToFS = faceSets[faceSetIndex];
            if (nextToFS.canIncorporatePartOrAllOfRange(addRange, nextToRangeIndex + 1))
            {
                Range1D usedRange = nextToFS.addRangeAtAcrossReturnAddedRange(addRange, nextToRangeIndex + 1);

                AssertUtil.Assert(usedRange.range > 0, "confusing used range was zero or less? (in face agg add fs w range)");

                setIndicesOfFaceSetsAtRangeToIndex(usedRange, nextToRangeIndex + 1, dir, faceSetIndex + FaceAggregator.FACETABLE_LOOKUP_SHIFT);

                Range1D unusedRangeBelow = addRange.subRangeBelowRange(usedRange);
                if (!unusedRangeBelow.isErsatzNull())
                {
//					addNewFaceSetsWith(nextToRangeIndex + 1, addRange, dir);
                    addNewFaceSetsWith(nextToRangeIndex + 1, finfo);
                }

                Range1D unusedAbove = addRange.subRangeAboveRange(usedRange);
                if (!unusedAbove.isErsatzNull())
                {
                    finfo.range = unusedAbove;
//					addToFaceSetsAt(nextToRangeIndex, unusedAbove, dir);
                    addToFaceSetsAt(nextToRangeIndex, finfo);
                }
                return;
            }
        }

        addNewFaceSetsWith(nextToRangeIndex + 1, finfo);
    }
Exemplo n.º 16
0
 public static void Write(string file, ScanData data)
 {
     using (StreamWriter w = System.IO.File.CreateText(file))
     {
         w.WriteLine(string.Format("# Create By Sardauscan V{0}", Application.ProductVersion));
         w.WriteLine("#");
         w.WriteLine("# Object");
         List <FaceInfo> faces  = new List <FaceInfo>();
         List <Vector3d> vertex = new List <Vector3d>();
         for (int i = 0; i < data.Count; i++)                 // collect vertices and face
         {
             ScanLine slice = data[i];
             if (slice.IsMesh)
             {
                 List <Triangle3D> tris = slice.GetTriangles();
                 for (int t = 0; t < tris.Count; t++)
                 {
                     Triangle3D triangle = tris[t];
                     FaceInfo   face     = new FaceInfo();
                     face.v1 = AddToList(vertex, triangle.Point1.Position);
                     face.v2 = AddToList(vertex, triangle.Point2.Position);
                     face.v3 = AddToList(vertex, triangle.Point3.Position);
                     faces.Add(face);
                 }
             }
         }
         w.WriteLine(string.Format("# Vertices {0}", vertex.Count));
         for (int i = 0; i < vertex.Count; i++)
         {
             w.WriteLine(string.Format("v {0}", vertex[i].Dump()));
         }
         w.WriteLine(string.Format("# Triangles {0}", faces.Count));
         for (int i = 0; i < faces.Count; i++)
         {
             w.WriteLine(string.Format("f {0} {1} {2}", faces[i].v1 + 1, faces[i].v2 + 1, faces[i].v3 + 1));
         }
     }
 }
Exemplo n.º 17
0
        private void btLoadPicture_Click(object sender, EventArgs e)
        {
            ControlBox = false;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "Images|*.jpg;*.bmp;*.png;*.jpeg";
            OpenFileDialog openFileDialog2 = openFileDialog1;

            if (openFileDialog2.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            try
            {
                Bitmap source = new Bitmap(openFileDialog2.FileName);
                pictureEdit1.Image = source;
                Image    image = source.ConvertFrom();
                FaceInfo face  = MainForm.Engine.DetectMaxFace(image, null);
                Cursor      = Cursors.Default;
                _currentKey = null;
                if (face != null)
                {
                    _currentKey = new BcKey
                    {
                        ImageKey = MainForm.Engine.ExtractTemplate(image, face)
                    };
                }
                else
                {
                    int num = (int)XtraMessageBox.Show(Messages.NoFaceWasFound, Messages.Message, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    _currentKey = null;
                }
            }
            catch (Exception ex)
            {
                int num = (int)XtraMessageBox.Show(ex.Message, Messages.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
Exemplo n.º 18
0
 public FontAsset(TMP_FontAsset tmpFontAsset)
 {
     if (tmpFontAsset.kerningDictionary == null)
     {
         tmpFontAsset.ReadFontDefinition();
     }
     this.textMeshProFont = tmpFontAsset;
     this.name            = tmpFontAsset.name;
     this.id                  = tmpFontAsset.GetInstanceID();
     this.faceInfo            = tmpFontAsset.fontInfo;
     this.atlas               = tmpFontAsset.atlas;
     this.weights             = tmpFontAsset.fontWeights;
     this.boldSpacing         = tmpFontAsset.boldSpacing;
     this.gradientScale       = tmpFontAsset.material.GetFloat(ShaderUtilities.ID_GradientScale);
     this.kerningDictionary   = ConvertKerning(tmpFontAsset.kerningDictionary);
     this.characterDictionary = ConvertCharacters(tmpFontAsset.characterDictionary);
     this.boldStyle           = tmpFontAsset.boldStyle;
     this.normalStyle         = tmpFontAsset.normalStyle;
     this.normalSpacingOffset = tmpFontAsset.normalSpacingOffset;
     this.italicStyle         = tmpFontAsset.italicStyle;
     this.weightNormal        = tmpFontAsset.normalStyle;
     this.weightBold          = tmpFontAsset.boldStyle;
 }
Exemplo n.º 19
0
    void Start()
    {
        block = new MaterialPropertyBlock();

        // glyphLookUp = FontAsset.glyphLookupTable;
        // block.SetColor(ShaderIDConstants.Color, Color.green);

        // Material = Canvas.GetDefaultCanvasMaterial();
        mesh = new Mesh();

        vertexInfo = new List <VertexData>();
        indices    = new List <uint>();

        FontEngine.InitializeFontEngine();

        FontEngine.LoadFontFace(FontToUse, 90);
        faceInfo = FontEngine.GetFaceInfo();

        // FontToUse.RequestCharactersInTexture(Text, 0, FontStyle.Italic | FontStyle.Normal | FontStyle.Bold | FontStyle.BoldAndItalic);
        FontToUse.RequestCharactersInTexture(Text);

        FontEngine.DestroyFontEngine();
    }
Exemplo n.º 20
0
        public void GetFacesList()
        {
            try
            {
                HaarCascade = new CascadeClassifier(HaarCascadePath);
                FacesList.Clear();
                string   line     = string.Empty;
                FaceInfo faceInfo = null;

                StreamReader reader = new StreamReader(FaceListTextFile);
                int          index  = 0;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] lineParts = line.Split(':');
                    faceInfo           = new FaceInfo();
                    faceInfo.GrayImage = new Image <Gray, byte>(FacePhotosPath + lineParts[0] + ImageFileExtension);
                    faceInfo.Name      = lineParts[1];
                    FacesList.Add(faceInfo);
                }
                foreach (var face in FacesList)
                {
                    ImageList.Push(face.GrayImage.Mat);
                    NamesList.Add(face.Name);
                    LabelsVactor.Push(new[] { index++ });
                }
                reader.Close();

                if (ImageList.Size > 0)
                {
                    FaceRecognizer = new EigenFaceRecognizer(ImageList.Size);
                    FaceRecognizer.Train(ImageList, LabelsVactor);
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 21
0
        // Convert from FT_FaceInfo to FaceInfo
        static FaceInfo GetFaceInfo(FT_FaceInfo ft_face, int scaleFactor)
        {
            FaceInfo face = new FaceInfo();

            face.Name               = ft_face.name;
            face.PointSize          = (float)ft_face.pointSize / scaleFactor;
            face.Padding            = ft_face.padding / scaleFactor;
            face.LineHeight         = ft_face.lineHeight / scaleFactor;
            face.CapHeight          = 0;
            face.Baseline           = 0;
            face.Ascender           = ft_face.ascender / scaleFactor;
            face.Descender          = ft_face.descender / scaleFactor;
            face.CenterLine         = ft_face.centerLine / scaleFactor;
            face.Underline          = ft_face.underline / scaleFactor;
            face.UnderlineThickness = ft_face.underlineThickness == 0 ? 5 : ft_face.underlineThickness / scaleFactor; // Set Thickness to 5 if TTF value is Zero.
            face.SuperscriptOffset  = face.Ascender;
            face.SubscriptOffset    = face.Underline;
            face.SubSize            = 0.5f;
            //face.CharacterCount = ft_face.characterCount;
            face.AtlasWidth  = ft_face.atlasWidth / scaleFactor;
            face.AtlasHeight = ft_face.atlasHeight / scaleFactor;

            return(face);
        }
Exemplo n.º 22
0
    private void addNewFaceSetsWith(int acrossI, FaceInfo finfo)
    {
        Range1D      addRange  = finfo.range;
        Direction    dir       = finfo.direction;
        AlignedCoord startAlco = new AlignedCoord(acrossI, addRange.start);

        int fsIndex = indexOfFaceSetAtCoord(startAlco, dir);

        if (!indexRepresentsAnOccupiedCoord(fsIndex))
        {
            newFaceSetAtCoord(startAlco, addRange.blockType, dir, 0, finfo.lightDataProvider);
        }
//			newFaceSetAtCoord(startAlco, addRange.blockType, dir, addRange.bottom_light_level, finfo.lightDataProvider);

        FaceSet justAddedFS = faceSetAt(startAlco, dir);

        Range1D usedRange     = justAddedFS.addRangeAtAcrossReturnAddedRange(addRange, acrossI);
        int     nowOccupiedFS = unshiftedIndexOfFaceSetAtCoord(startAlco, dir);

        AssertUtil.Assert(nowOccupiedFS > -1, "wha negative occupied coord? " + nowOccupiedFS);

        setIndicesOfFaceSetsAtRangeToIndex(usedRange, acrossI, dir, nowOccupiedFS);

        AssertUtil.Assert(addRange.subRangeBelowRange(usedRange).isErsatzNull(), "we thought there would be no range below. whoops");

        Range1D unusedRangeAbove = addRange.subRangeAboveRange(usedRange);

        if (!unusedRangeAbove.isErsatzNull())
        {
            if (unusedRangeAbove.range > 0)
            {
                finfo.range = unusedRangeAbove;
                addNewFaceSetsWith(acrossI, finfo);
            }
        }
    }
        private FaceInfo GetFaceInfo(FT_FaceInfo ft_face, int scaleFactor)
        {
            FaceInfo faceInfo = new FaceInfo();

            faceInfo.Name                   = ft_face.name;
            faceInfo.PointSize              = (float)ft_face.pointSize / (float)scaleFactor;
            faceInfo.Padding                = ft_face.padding / scaleFactor;
            faceInfo.LineHeight             = ft_face.lineHeight / (float)scaleFactor;
            faceInfo.CapHeight              = 0f;
            faceInfo.Baseline               = 0f;
            faceInfo.Ascender               = ft_face.ascender / (float)scaleFactor;
            faceInfo.Descender              = ft_face.descender / (float)scaleFactor;
            faceInfo.CenterLine             = ft_face.centerLine / (float)scaleFactor;
            faceInfo.Underline              = ft_face.underline / (float)scaleFactor;
            faceInfo.UnderlineThickness     = ((ft_face.underlineThickness == 0f) ? 5f : (ft_face.underlineThickness / (float)scaleFactor));
            faceInfo.strikethrough          = (faceInfo.Ascender + faceInfo.Descender) / 2.75f;
            faceInfo.strikethroughThickness = faceInfo.UnderlineThickness;
            faceInfo.SuperscriptOffset      = faceInfo.Ascender;
            faceInfo.SubscriptOffset        = faceInfo.Underline;
            faceInfo.SubSize                = 0.5f;
            faceInfo.AtlasWidth             = ft_face.atlasWidth / scaleFactor;
            faceInfo.AtlasHeight            = ft_face.atlasHeight / scaleFactor;
            return(faceInfo);
        }
Exemplo n.º 24
0
        // Convert from FT_FaceInfo to FaceInfo
        FaceInfo GetFaceInfo(FT_FaceInfo ft_face, int scaleFactor)
        {
            FaceInfo face = new FaceInfo();

            face.Name = ft_face.name;
            face.PointSize = (float)ft_face.pointSize / scaleFactor;
            face.Padding = 0; // ft_face.padding / scaleFactor;
            face.LineHeight = ft_face.lineHeight / scaleFactor;
            face.Baseline = 0;
            face.Ascender = ft_face.ascender / scaleFactor;
            face.Descender = ft_face.descender / scaleFactor;
            face.CenterLine = ft_face.centerLine / scaleFactor;
            face.Underline = ft_face.underline / scaleFactor;
            face.UnderlineThickness = ft_face.underlineThickness == 0 ? 5 : ft_face.underlineThickness / scaleFactor; // Set Thickness to 5 if TTF value is Zero.
            face.SuperscriptOffset = face.Ascender;
            face.SubscriptOffset = face.Underline;
            face.SubSize = 0.5f;
            //face.CharacterCount = ft_face.characterCount;
            face.AtlasWidth = ft_face.atlasWidth / scaleFactor;
            face.AtlasHeight = ft_face.atlasHeight / scaleFactor;

            return face;
        }
Exemplo n.º 25
0
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (pictureEdit1.Image == null)
            {
                return;
            }
            foreach (DataRow dataRow in (InternalDataCollectionBase)_mainTable.Rows)
            {
                try
                {
                    ((System.Drawing.Image)dataRow["Image"]).Dispose();
                }
                catch
                {
                }
            }
            _mainTable.Rows.Clear();
            Image    image = ((Bitmap)pictureEdit1.Image).ConvertFrom();
            FaceInfo face  = MainForm.Engine.DetectMaxFace(image, null);

            if (face != null)
            {
                foreach (BcIdentificationServer identificationServer in BcIdentificationServer.LoadAll())
                {
                    try
                    {
                        byte[]                     template                   = MainForm.Engine.ExtractTemplate(image, face);
                        BcServerSettings           bcServerSettings           = BcServerSettings.Load();
                        IdentificationServerClient identificationServerClient = new IdentificationServerClient(new InstanceContext(_client));
                        identificationServerClient.Endpoint.Address = new EndpointAddress("net.tcp://" + (object)bcServerSettings.Ip + ":" + (string)(object)bcServerSettings.Port + "/FaceIdentification/IdentificationServer");
                        identificationServerClient.Open();
                        List <Guid> list   = new List <Guid>();
                        long        dtFrom = 0;
                        if (this.dtFrom.Text != "")
                        {
                            dtFrom = this.dtFrom.DateTime.Date.Ticks;
                        }
                        long dtBefore = 0;
                        if (this.dtBefore.Text != "")
                        {
                            dtBefore = this.dtBefore.DateTime.Date.Ticks;
                        }
                        if (template != null)
                        {
                            identificationServerClient.DbSearch((int)spinEdit1.Value, Convert.ToSingle(tbScore.Text), dtFrom, dtBefore, cbSex.SelectedIndex, template);
                            _startDate = DateTime.Now;
                            marqueeProgressBarControl1.Visible = true;
                            _maintimer.Enabled = true;
                            break;
                        }
                        int num = (int)XtraMessageBox.Show(Messages.Error, Messages.Error, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    catch (Exception ex)
                    {
                        int num = (int)XtraMessageBox.Show(ex.Message, Messages.IdentificationServerUnavailble, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
            else
            {
                int num1 = (int)XtraMessageBox.Show(Messages.NoFaceWasFound, Messages.Message, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
Exemplo n.º 26
0
        static void OnFinished(TexFontSigned font)
        {
            var sdfPath = TEXPreference.main.MainFolderPath + "/Fonts/TMPro/" + font.id + ".asset";

            TMP_FontAsset asset;

            if (!(asset = AssetDatabase.LoadAssetAtPath <TMP_FontAsset>(sdfPath)))
            {
                // It doesn't exist (or invalid), so create new
                asset = font.asset = ScriptableObject.CreateInstance <TMP_FontAsset>();
                if (!AssetDatabase.IsValidFolder(TEXPreference.main.MainFolderPath + "/Fonts/TMPro"))
                {
                    AssetDatabase.CreateFolder(TEXPreference.main.MainFolderPath + "/Fonts", "TMPro");
                }
                AssetDatabase.CreateAsset(asset, sdfPath);
            }
            asset.fontAssetType = _render >= RenderModes.DistanceField16 ? TMP_FontAsset.FontAssetTypes.SDF : TMP_FontAsset.FontAssetTypes.Bitmap;
            FaceInfo face = GetFaceInfo(_faceInfo, 1);

            asset.AddFaceInfo(face);

            _atlasInfo = new Texture2D(_bufferWidth, _bufferHeight, TextureFormat.Alpha8, false, true);
            var _buffer32 = Array.ConvertAll(_buffers, x => new Color32(x, x, x, x));

            _atlasInfo.SetPixels32(_buffer32);
            _atlasInfo.Apply(false, true);

            // Add GlyphInfo[] to Font Asset
            TMP_Glyph[] glyphs = GetGlyphInfo(_glyphsInfo, 1);
            asset.AddGlyphInfo(glyphs);

            // Get and Add Kerning Pairs to Font Asset

            KerningTable kerningTable = GetKerningTable(font.rawpath, (int)face.PointSize);

            asset.AddKerningInfo(kerningTable);

            // Add Line Breaking Rules
            //LineBreakingTable lineBreakingTable = new LineBreakingTable();
            //

            // Add Font Atlas as Sub-Asset
            asset.atlas          = _atlasInfo;
            _atlasInfo.name      = font.id + " Atlas";
            _atlasInfo.hideFlags = HideFlags.HideInHierarchy;
            AssetDatabase.AddObjectToAsset(_atlasInfo, asset);

            // Create new Material and Add it as Sub-Asset
            Shader   default_Shader = Shader.Find("TextMeshPro/Distance Field"); //m_shaderSelection;
            Material tmp_material   = new Material(default_Shader);

            tmp_material.name = _atlasInfo + " Material";
            tmp_material.SetTexture(ShaderUtilities.ID_MainTex, _atlasInfo);
            tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, _atlasInfo.width);
            tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, _atlasInfo.height);

            tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, asset.normalStyle);
            tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, asset.boldStyle);

            int spread = _render >= RenderModes.DistanceField16 ? _padding + 1 : _padding;

            tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.

            asset.material         = tmp_material;
            tmp_material.hideFlags = HideFlags.HideInHierarchy;

            AssetDatabase.AddObjectToAsset(tmp_material, asset);

            font.asset = asset;
            font.ImportDictionary();
            AssetDatabase.SaveAssets();
        }
Exemplo n.º 27
0
 static extern int GetFaceInfo_Internal(ref FaceInfo faceInfo);
Exemplo n.º 28
0
        void Awake()
        {
            if (!Application.isPlaying || Initialization.Environment == Enums.RunningState.Editor)
            {
                return;
            }

            var type     = typeof(global::TMPro.TMP_FontAsset);
            var fontInfo = new FaceInfo();

            fontInfo.Name               = FaceInfo_Name;
            fontInfo.PointSize          = FaceInfo_PointSize;
            fontInfo.Scale              = FaceInfo_Scale;
            fontInfo.CharacterCount     = FaceInfo_CharacterCount;
            fontInfo.LineHeight         = FaceInfo_LineHeight;
            fontInfo.Baseline           = FaceInfo_Baseline;
            fontInfo.Ascender           = FaceInfo_Ascender;
            fontInfo.CapHeight          = FaceInfo_CapHeight;
            fontInfo.Descender          = FaceInfo_Descender;
            fontInfo.CenterLine         = FaceInfo_CenterLine;
            fontInfo.SuperscriptOffset  = FaceInfo_SuperscriptOffset;
            fontInfo.SubscriptOffset    = FaceInfo_SubscriptOffset;
            fontInfo.SubSize            = FaceInfo_SubSize;
            fontInfo.Underline          = FaceInfo_Underline;
            fontInfo.UnderlineThickness = FaceInfo_UnderlineThickness;
            fontInfo.TabWidth           = FaceInfo_TabWidth;
            fontInfo.Padding            = FaceInfo_Padding;
            fontInfo.AtlasWidth         = FaceInfo_AtlasWidth;
            fontInfo.AtlasHeight        = FaceInfo_AtlasHeight;
#if UNITY_EDITOR
            fontInfo.strikethrough          = FaceInfo_strikethrough;
            fontInfo.strikethroughThickness = FaceInfo_strikethroughThickness;
#endif

            type.GetField("m_fontInfo", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, fontInfo);

            List <TMP_Glyph> glyphs = new List <TMP_Glyph>();

            for (int i = 0; i < TMP_Glyph_height.Count; i++)
            {
                TMP_Glyph glyph = new TMP_Glyph();

                glyph.height   = TMP_Glyph_height[i];
                glyph.id       = TMP_Glyph_id[i];
                glyph.scale    = TMP_Glyph_scale[i];
                glyph.width    = TMP_Glyph_width[i];
                glyph.x        = TMP_Glyph_x[i];
                glyph.xAdvance = TMP_Glyph_xAdvance[i];
                glyph.xOffset  = TMP_Glyph_xOffset[i];
                glyph.y        = TMP_Glyph_y[i];
                glyph.yOffset  = TMP_Glyph_yOffset[i];
                glyphs.Add(glyph);
            }

            type.GetField("m_glyphInfoList", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, glyphs);

            KerningTable kTable = new KerningTable();

            for (int i = 0; i < KerningTable_AscII_Left.Count; i++)
            {
                kTable.kerningPairs.Add(new KerningPair(KerningTable_AscII_Left[i], KerningTable_AscII_Right[i], KerningTable_XadvanceOffset[i]));
            }

            type.GetField("m_kerningInfo", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, kTable);

            var newKerningPair = new KerningPair(KerningPair_AscII_Left, KerningPair_AscII_Right, KerningPair_XadvanceOffset);
            type.GetField("m_kerningPair", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, newKerningPair);



            FontCreationSetting fontSettings = new FontCreationSetting();

            fontSettings.fontAtlasHeight   = FontCreationSetting_fontAtlasHeight;
            fontSettings.fontAtlasWidth    = FontCreationSetting_fontAtlasWidth;
            fontSettings.fontCharacterSet  = FontCreationSetting_fontCharacterSet;
            fontSettings.fontKerning       = FontCreationSetting_fontKerning;
            fontSettings.fontPackingMode   = FontCreationSetting_fontPackingMode;
            fontSettings.fontPadding       = FontCreationSetting_fontPadding;
            fontSettings.fontRenderMode    = FontCreationSetting_fontRenderMode;
            fontSettings.fontSize          = FontCreationSetting_fontSize;
            fontSettings.fontSizingMode    = FontCreationSetting_fontSizingMode;
            fontSettings.fontSourcePath    = FontCreationSetting_fontSourcePath;
            fontSettings.fontStlyeModifier = FontCreationSetting_fontStyleModifier;
            fontSettings.fontStyle         = FontCreationSetting_fontStyle;
            type.GetField("fontCreationSettings", BindingFlags.Public | BindingFlags.Instance).SetValue(this, fontSettings);


            TMP_FontWeights[] weights = new TMP_FontWeights[TMP_FontWeights_italicTypeface.Count];

            for (int i = 0; i < TMP_FontWeights_italicTypeface.Count; i++)
            {
                var newWeight = new TMP_FontWeights();
                newWeight.italicTypeface  = TMP_FontWeights_italicTypeface[i];
                newWeight.regularTypeface = TMP_FontWeights_regularTypeface[i];

                weights[i] = newWeight;
            }


            type.GetField("fontWeights", BindingFlags.Public | BindingFlags.Instance).SetValue(this, weights);
        }
Exemplo n.º 29
0
        /**
         * 绘制人脸框。
         */
        private void showFrame2(LivenessModel model)
        {
            if (camemra1IsRgb)
            {
                Canvas canvas2 = textureViewOne.LockCanvas();
                if (canvas2 == null)
                {
                    textureViewOne.UnlockCanvasAndPost(canvas2);
                    return;
                }

                if (model == null)
                {
                    canvas2.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                    textureViewOne.UnlockCanvasAndPost(canvas2);
                    return;
                }

                FaceInfo[] faceInfos  = model.getTrackFaceInfo();
                ImageFrame imageFrame = model.getImageFrame();
                if (faceInfos == null || faceInfos.Length == 0)
                {
                    // 清空canvas
                    canvas2.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                    textureViewOne.UnlockCanvasAndPost(canvas2);
                    return;
                }
                canvas2.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                FaceInfo faceInfo2 = faceInfos[0];
                rectF.Set(getFaceRectTwo(faceInfo2, imageFrame));
                // 检测图片的坐标和显示的坐标不一样,需要转换。
                // mPreview[typeIndex].mapFromOriginalRect(rectF);
                float yaw2   = Java.Lang.Math.Abs(faceInfo2.HeadPose[0]);
                float patch2 = Java.Lang.Math.Abs(faceInfo2.HeadPose[1]);
                float roll2  = Java.Lang.Math.Abs(faceInfo2.HeadPose[2]);
                if (yaw2 > 20 || patch2 > 20 || roll2 > 20)
                {
                    // 不符合要求,绘制黄框
                    paint.Color = (Color.Yellow);

                    string text  = "请正视屏幕";
                    float  width = paint.MeasureText(text) + 50;
                    float  x     = rectF.CenterX() - width / 2;
                    paint.Color = (Color.Red);
                    paint.SetStyle(Paint.Style.Fill);
                    canvas2.DrawText(text, x + 25, rectF.Top - 20, paint);
                    paint.Color = (Color.Yellow);
                }
                else
                {
                    // 符合检测要求,绘制绿框
                    paint.Color = (Color.Green);
                }
                paint.SetStyle(Paint.Style.Stroke);
                // 绘制框
                canvas2.DrawRect(rectF, paint);
                textureViewOne.UnlockCanvasAndPost(canvas2);


                Canvas canvas = textureView.LockCanvas();
                if (canvas == null)
                {
                    textureView.UnlockCanvasAndPost(canvas);
                    return;
                }
                if (faceInfos == null || faceInfos.Length == 0)
                {
                    // 清空canvas
                    canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                    textureView.UnlockCanvasAndPost(canvas);
                    return;
                }
                canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                textureView.UnlockCanvasAndPost(canvas);
            }
            else
            {
                Canvas canvas = textureView.LockCanvas();
                if (canvas == null)
                {
                    textureView.UnlockCanvasAndPost(canvas);
                    return;
                }

                if (model == null)
                {
                    // 清空canvas
                    canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                    textureView.UnlockCanvasAndPost(canvas);
                    return;
                }
                FaceInfo[] faceInfos  = model.getTrackFaceInfo();
                ImageFrame imageFrame = model.getImageFrame();
                if (faceInfos == null || faceInfos.Length == 0)
                {
                    // 清空canvas
                    canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                    textureView.UnlockCanvasAndPost(canvas);
                    return;
                }
                canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);

                FaceInfo faceInfo = faceInfos[0];

                rectF.Set(getFaceRectTwo(faceInfo, imageFrame));

                // 检测图片的坐标和显示的坐标不一样,需要转换。
                // mPreview[typeIndex].mapFromOriginalRect(rectF);

                float yaw   = Java.Lang.Math.Abs(faceInfo.HeadPose[0]);
                float patch = Java.Lang.Math.Abs(faceInfo.HeadPose[1]);
                float roll  = Java.Lang.Math.Abs(faceInfo.HeadPose[2]);
                if (yaw > 20 || patch > 20 || roll > 20)
                {
                    // 不符合要求,绘制黄框
                    paint.Color = (Color.Yellow);

                    string text  = "请正视屏幕";
                    float  width = paint.MeasureText(text) + 50;
                    float  x     = rectF.CenterX() - width / 2;
                    paint.Color = (Color.Red);
                    paint.SetStyle(Paint.Style.Fill);
                    canvas.DrawText(text, x + 25, rectF.Top - 20, paint);
                    paint.Color = (Color.Yellow);
                }
                else
                {
                    // 符合检测要求,绘制绿框
                    paint.Color = (Color.Green);
                }
                paint.SetStyle(Paint.Style.Stroke);
                // 绘制框
                canvas.DrawRect(rectF, paint);
                textureView.UnlockCanvasAndPost(canvas);


                Canvas canvas2 = textureViewOne.LockCanvas();
                if (canvas2 == null)
                {
                    textureViewOne.UnlockCanvasAndPost(canvas2);
                    return;
                }
                if (faceInfos == null || faceInfos.Length == 0)
                {
                    // 清空canvas
                    canvas2.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                    textureViewOne.UnlockCanvasAndPost(canvas2);
                    return;
                }
                canvas2.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
                textureViewOne.UnlockCanvasAndPost(canvas2);
            }
        }
Exemplo n.º 30
0
 public void setInfo(FaceInfo info)
 {
     this.info = info;
 }
Exemplo n.º 31
0
            public static AFR_FSDK_FACEMODEL extractFRFeature(IntPtr hFREngine, ASVLOFFSCREEN inputImg, FaceInfo faceInfo)
            {
                AFR_FSDK_FACEINPUT faceinput = new AFR_FSDK_FACEINPUT();

                faceinput.lOrient       = faceInfo.orient;
                faceinput.rcFace.left   = faceInfo.left;
                faceinput.rcFace.top    = faceInfo.top;
                faceinput.rcFace.right  = faceInfo.right;
                faceinput.rcFace.bottom = faceInfo.bottom;

                AFR_FSDK_FACEMODEL faceFeature = new AFR_FSDK_FACEMODEL(IntPtr.Zero, 0);
                IntPtr             ret         = AFR_FSDKLibrary.AFR_FSDK_ExtractFRFeature(hFREngine, ref (inputImg), ref (faceinput), ref (faceFeature));

                if (ret.ToInt64() != 0)
                {
                    Console.WriteLine(String.Format("AFR_FSDK_ExtractFRFeature ret 0x{0:x}", ret));
                    return(new AFR_FSDK_FACEMODEL(IntPtr.Zero, 0));
                }

                try
                {
                    return(faceFeature.deepCopy());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    return(new AFR_FSDK_FACEMODEL(IntPtr.Zero, 0));
                }
            }
Exemplo n.º 32
0
        private String filter(FaceInfo faceInfo, ImageFrame imageFrame)
        {
            String tip = "";

            if (faceInfo.MConf < 0.6)
            {
                tip = "人脸置信度太低";
                return(tip);
            }

            float[] headPose = faceInfo.HeadPose.ToArray();
            if (Math.Abs(headPose[0]) > 20 || Math.Abs(headPose[1]) > 20 || Math.Abs(headPose[2]) > 20)
            {
                tip = "人脸置角度太大,请正对屏幕";
                return(tip);
            }

            int width  = imageFrame.getWidth();
            int height = imageFrame.getHeight();
            // 判断人脸大小,若人脸超过屏幕二分一,则提示文案“人脸离手机太近,请调整与手机的距离”;
            // 若人脸小于屏幕三分一,则提示“人脸离手机太远,请调整与手机的距离”
            float ratio = (float)faceInfo.MWidth / (float)height;

            Log.Info("liveness_ratio", "ratio=" + ratio);
            if (ratio > 0.6)
            {
                tip = "人脸离屏幕太近,请调整与屏幕的距离";
                return(tip);
            }
            else if (ratio < 0.2)
            {
                tip = "人脸离屏幕太远,请调整与屏幕的距离";
                return(tip);
            }
            else if (faceInfo.MCenterX > width * 3 / 4)
            {
                tip = "人脸在屏幕中太靠右";
                return(tip);
            }
            else if (faceInfo.MCenterX < width / 4)
            {
                tip = "人脸在屏幕中太靠左";
                return(tip);
            }
            else if (faceInfo.MCenterY > height * 3 / 4)
            {
                tip = "人脸在屏幕中太靠下";
                return(tip);
            }
            else if (faceInfo.MCenterX < height / 4)
            {
                tip = "人脸在屏幕中太靠上";
                return(tip);
            }

            int liveType = PreferencesUtil.getInt(LivenessSettingActivity.TYPE_LIVENSS, LivenessSettingActivity
                                                  .TYPE_NO_LIVENSS);

            if (liveType == LivenessSettingActivity.TYPE_NO_LIVENSS)
            {
                saveFace(faceInfo, imageFrame);
            }
            else if (liveType == LivenessSettingActivity.TYPE_RGB_LIVENSS)
            {
                if (rgbLiveness(imageFrame, faceInfo) > 0.9)
                {
                    saveFace(faceInfo, imageFrame);
                }
                else
                {
                    toast("rgb活体分数过低");
                }
            }


            return(tip);
        }