Ejemplo n.º 1
0
        private void loadAds()
        {
            String    domain = ConfigurationManager.AppSettings["domain"];
            NetResult result = request(String.Format("{0}/api/ad/items/feiyu.json", domain));

            if (result == null || result.Status == "err")
            {
                return;
            }

            JArray items = result.Data as JArray;
            int    count = 0;

            foreach (JObject item in items)
            {
                Image image = this.getImage(String.Format("{0}/api/ad/get_resource/{1}.json", domain, item["id"]));
                if (image == null)
                {
                    continue;
                }


                Point point = new Point(10, 10);

                if (count > 0)
                {
                    point = new Point(this.Width - image.Width - 10, 10);
                }

                Size size = new Size(image.Width, image.Height);
                this.addAd(image, point, size);
                count++;
            }
        }
Ejemplo n.º 2
0
    public IEnumerator Initialize(BundleLoadingPresenter presenter, string cdnHost, NetResult result)
    {
        this.presenter = presenter;
        this.cdnHost   = cdnHost;
        this.ready     = false;
        Service.Run(UpdateProgress());

        yield return(Service.Run(LoadScenes(result)));

        if (result.IsFailed())
        {
            yield break;
        }

        yield return(Service.Run(LoadResources(result)));

        if (result.IsFailed())
        {
            yield break;
        }

        result.SetSuccess(true);
        ready = true;
        yield break;
    }
Ejemplo n.º 3
0
        public static MatrixOp Mat <T>(NetResult <Matrix <T> > results)
            where T : struct
        {
            if (results == null)
            {
                throw new ArgumentNullException(nameof(results));
            }
            if (!results.Any())
            {
                throw new ArgumentException();
            }
            if (results.Any(m => m == null))
            {
                throw new ArgumentException();
            }

            results.ThrowIfDisposed();

            Matrix <T> .TryParse <T>(out var elementType);

            var first           = results.First();
            var templateRows    = first.TemplateRows;
            var templateColumns = first.TemplateColumns;

            //using (var vector = new StdVector<Matrix<T>>(results, new[] { templateRows, templateColumns }))
            //{
            //    var ret = Native.mat_mat_OpStdVectToMat(elementType.ToNativeMatrixElementType(),
            //                                            vector.NativePtr,
            //                                            templateRows,
            //                                            templateColumns,
            //                                            out var matrix);
            //    switch (ret)
            //    {
            //        case ErrorType.ElementTypeNotSupport:
            //            throw new ArgumentException($"{elementType} is not supported.");
            //    }

            //    return new MatrixOp(ElementType.OpStdVectToMat, elementType, matrix, templateRows, templateColumns);
            //}
            var ret = NativeMethods.mat_mat_OpStdVectToMat(elementType.ToNativeMatrixElementType(),
                                                           results.NativePtr,
                                                           templateRows,
                                                           templateColumns,
                                                           out var matrix);

            switch (ret)
            {
            case ErrorType.ElementTypeNotSupport:
                throw new ArgumentException($"{elementType} is not supported.");
            }

            return(new MatrixOp(ElementType.OpStdVectToMat, elementType, matrix, templateRows, templateColumns));
        }
Ejemplo n.º 4
0
        public static String[] GetAccessToken(String appId, String appSecret)
        {
            NetResult result = NetApi.GetAccessToken(appId, appSecret);

            if (result == null || result.Status == "err")
            {
                return(null);
            }
            JObject item = result.Data as JObject;

            return(new String[] { item["access_token"].ToString(), item["access_expired"].ToString() });
        }
Ejemplo n.º 5
0
    IEnumerator LoadScenes(NetResult result)
    {
        yield return(Service.Run(DownloadSceneMeta(result)));

        if (result.IsFailed())
        {
            logger.LogError("Can not load scene meta.");
            yield break;
        }

#if UNITY_EDITOR && BOOT_BUNDLE_EDIT
        yield break;
#endif

        // init count
        doneCount = 0;
        string text = Service.sb.Get("loading.status.bundle.load.scene");
        if (presenter != null)
        {
            presenter.SetDescription(string.Format(text, 0));
        }

        successSceneWorkerCount = 0;
        failedSceneWorkerCount  = 0;
        for (int index = 0; index < worker; index++)
        {
            Service.Run(LoadSceneWorker(index));
        }

        // waiting load
        while (true)
        {
            yield return(new WaitForSeconds(0.1f));

            if (successSceneWorkerCount + failedSceneWorkerCount < worker)
            {
                continue;
            }
            break;
        }

        // result check
        if (failedSceneWorkerCount > 0)
        {
            result.SetSuccess(false);
        }
        else
        {
            result.SetSuccess(true);
            PersistenceUtil.SaveTextFile(remoteScenesMetaFilePath, remoteScenesMeta);
        }
    }
Ejemplo n.º 6
0
        public static void SetUnthorize(this AuthorizationFilterContext context)
        {
            NetResult <ResponseData> result = new NetResult <ResponseData>()
            {
                HttpStatus = 401,
                Error      = new RepositoryCore.Result.DefaultResult()
                {
                    Code = 401, Message = "Unuthorize"
                }
            };

            context.HttpContext.Response.StatusCode = 401;
            context.Result = new CoreJsonResult(result);
        }
Ejemplo n.º 7
0
        public static NetResult GetAccessToken(String appId, String appSecret)
        {
            Soft   soft = null;
            String url  = String.Format("{0}{1}.json", domain, GetUrl);

            String time = TimeStamp.GetNowTimeStamp().ToString();

            System.String nonce = Encryption.MD5(time);

            IDictionary <String, String> param = new Dictionary <String, String>();

            param.Add("app_id", appId);
            param.Add("nonce", nonce);
            param.Add("timestamp", time);
            param.Add("signature", Encryption.MD5(String.Format("{0}{1}{2}&key={3}", appId, nonce, time, appSecret)));

            String       json   = null;
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(url, param, 30000, "WinFormFeiyu", Encoding.UTF8, null);

                stream = response.GetResponseStream();
                reader = new StreamReader(stream);
                json   = reader.ReadToEnd();
                reader.Close();
                stream.Close();
            }
            catch (System.Net.WebException e)
            {
                MessageBox.Show(e.Message, "获取Token时发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            finally
            {
                reader?.Close();
                stream?.Close();
            }

            if (String.IsNullOrEmpty(json))
            {
                return(null);
            }
            NetResult result = JsonHelper.DeserializeJsonToObject <NetResult>(json);

            return(result);
        }
Ejemplo n.º 8
0
    IEnumerator InitializeService()
    {
        Service.ready = false;

        yield return Service.sb.Initialize("en", "ko");
        yield return Service.Run(Service.setting.Initialize());

        // initialize bundle downloader service
        NetResult result = new NetResult();
        yield return Service.Run(Service.bundle.Initialize(this, "http://raindays.net/unity/boot/", result));
        if (result.IsFailed()) {
            logger.LogError(Service.sb.Get("loading.status.bundle.failed"));
            yield break;
        }

        Service.ready = true;
    }
Ejemplo n.º 9
0
        private NetResult request(String url)
        {
            NetResult result = null;

            try {
                HttpWebResponse response = HttpWebResponseUtility.CreateGetHttpResponse(url, null, 30000, "WinForm", null);
                Stream          stream   = response.GetResponseStream();
                StreamReader    reader   = new StreamReader(stream);
                String          json     = reader.ReadToEnd();

                result = JsonHelper.DeserializeJsonToObject <NetResult>(json);
            } catch (WebException e) {
                MessageBox.Show(e.Message, "网络异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(result);
        }
Ejemplo n.º 10
0
    IEnumerator InitializeService()
    {
        Service.ready = false;

        yield return(Service.sb.Initialize("en", "ko"));

        yield return(Service.Run(Service.setting.Initialize()));

        // initialize bundle downloader service
        NetResult result = new NetResult();

        yield return(Service.Run(Service.bundle.Initialize(this, "http://raindays.net/unity/boot/", result)));

        if (result.IsFailed())
        {
            logger.LogError(Service.sb.Get("loading.status.bundle.failed"));
            yield break;
        }

        Service.ready = true;
    }
Ejemplo n.º 11
0
        public static Soft GetSoft(int id, String token)
        {
            Soft   soft = null;
            String url  = String.Format("{0}{1}{2}.json?access_token={3}", domain, GetUrl, id, token);

            String       json   = null;
            Stream       stream = null;
            StreamReader reader = null;

            try
            {
                HttpWebResponse response = Tools.HttpWebResponseUtility.CreateGetHttpResponse(url, null, 30000,
                                                                                              "WinForm", null);
                stream = response.GetResponseStream();
                reader = new StreamReader(stream);
                json   = reader.ReadToEnd();
            }
            catch (System.Net.WebException e)
            {
                MessageBox.Show(e.Message, "更新异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
            finally
            {
                reader?.Close();
                stream?.Close();
            }

            NetResult result = JsonHelper.DeserializeJsonToObject <NetResult>(json);

            if (result.Status == "succ")
            {
                JObject item = result.Data as JObject;
                soft = new Soft(item);
            }

            return(soft);
        }
Ejemplo n.º 12
0
    IEnumerator DownloadSceneMeta(NetResult result)
    {
        // get local
        string localMeta = PersistenceUtil.LoadTextFile(remoteScenesMetaFilePath);

        if (localMeta.Length > 0)
        {
            try {
                localScenes = JsonMapper.ToObject <Dictionary <string, uint> >(localMeta);
            }
            catch (Exception e) {
                logger.LogWarning(e.ToString());
            }
        }

        // get remote
        using (WWW www = new WWW(cdnScenesMeta)) {
            yield return(www);

            if (www.error != null)
            {
                result.SetSuccess(false);
                yield break;
            }

            try {
                remoteScenes     = JsonMapper.ToObject <Dictionary <string, uint> >(www.text);
                remoteScenesMeta = www.text;
                result.SetSuccess(true);
            }
            catch (Exception e) {
                result.SetSuccess(false);
                logger.LogError(e.ToString());
            }
        }
    }
Ejemplo n.º 13
0
        public static Soft GetSoft(int id)
        {
            Soft   soft = null;
            String url  = String.Format("{0}{1}/{2}", domain, GetUrl, id);

            IDictionary <String, Object> param = new Dictionary <String, Object>();

            param.Add("access_token", "123456");

            HttpWebResponse response = Tools.HttpWebResponseUtility.CreateGetHttpResponse(url, param, 30000, "WinForm", null);
            Stream          stream   = response.GetResponseStream();
            StreamReader    reader   = new StreamReader(stream);
            String          json     = reader.ReadToEnd();

            NetResult result = JsonHelper.DeserializeJsonToObject <NetResult>(json);

            if (result.Status == "succ")
            {
                JObject item = result.Data as JObject;
                soft = new Soft(item);
            }

            return(soft);
        }
Ejemplo n.º 14
0
        protected override NetResult[] BeginDetect(Bitmap img, float minProbability = 0.3F, string[] labelsFilters = null)
        {
            //Extract width and height from config file
            ExtractValueFromConfig("width", out int widthBlob);
            ExtractValueFromConfig("height", out int heightBlob);

            using (Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(img))
            {
                //Create the blob
                var blob = CvDnn.BlobFromImage(mat, Scale, size: new OpenCvSharp.Size(widthBlob, heightBlob), crop: false);

                //Set blob of a default layer
                network.SetInput(blob);

                //Get all out layers
                string[] outLayers = network.GetUnconnectedOutLayersNames();

                //Initialize all blobs for the all out layers
                Mat[] result = new Mat[outLayers.Length];
                for (int i = 0; i < result.Length; i++)
                {
                    result[i] = new Mat();
                }

                ///Execute all out layers
                network.Forward(result, outLayers);

                List <NetResult> netResults = new List <NetResult>();
                foreach (var item in result)
                {
                    for (int i = 0; i < item.Rows; i++)
                    {
                        //Get the max loc and max of the col range by prefix result
                        Cv2.MinMaxLoc(item.Row[i].ColRange(Prefix, item.Cols), out double min, out double max, out OpenCvSharp.Point minLoc, out OpenCvSharp.Point maxLoc);

                        //Validate the min probability
                        if (max >= minProbability)
                        {
                            //The label is the max Loc
                            string label = Labels[maxLoc.X];
                            if (labelsFilters != null)
                            {
                                if (!labelsFilters.Contains(label))
                                {
                                    continue;
                                }
                            }

                            //The probability is the max value
                            double probability = max;

                            //Center BoundingBox X is the 0 index result
                            int centerX = Convert.ToInt32(item.At <float>(i, 0) * (float)mat.Width);
                            //Center BoundingBox X is the 1 index result
                            int centerY = Convert.ToInt32(item.At <float>(i, 1) * (float)mat.Height);
                            //Width BoundingBox is the 2 index result
                            int width = Convert.ToInt32(item.At <float>(i, 2) * (float)mat.Width);
                            //Height BoundingBox is the 2 index result
                            int height = Convert.ToInt32(item.At <float>(i, 3) * (float)mat.Height);

                            //Build NetResult
                            netResults.Add(NetResult.Build(centerX, centerY, width, height, label, probability));
                        }
                    }
                }

                return(netResults.ToArray());
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            //Directory contains the models and configuration files
            string dir = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "data");

            //Model of YoloV3
            string model      = System.IO.Path.Combine(dir, "yolov3.weights");
            string cfg        = System.IO.Path.Combine(dir, "yolov3.cfg");
            string labelsYolo = System.IO.Path.Combine(dir, "coco.names");


            //Model of face
            string modelFace = System.IO.Path.Combine(dir, "yolov3-wider_16000.weights");
            string cfgFace   = System.IO.Path.Combine(dir, "yolov3-face.cfg");

            //Model of Gender classifaction
            string modelGenderCaffe = System.IO.Path.Combine(dir, "gender_net.caffemodel");
            string cfgGenderCaffe   = System.IO.Path.Combine(dir, "deploy_gender.prototxt");

            //Image Path
            string testImage = System.IO.Path.Combine(dir, "friends.jpg");


            using (NetYoloV3 yoloV3 = new NetYoloV3())
                using (NetYoloV3 yoloV3Faces = new NetYoloV3())
                    using (NetCaffeAgeGender caffeGender = new NetCaffeAgeGender())
                        using (Bitmap bitmap = new Bitmap(testImage))
                            using (Bitmap resultImage = new Bitmap(testImage))
                            {
                                //Initialize models
                                yoloV3.Initialize(model, cfg, labelsYolo);
                                yoloV3Faces.Initialize(modelFace, cfgFace, new string[] { "faces" });
                                caffeGender.Initialize(modelGenderCaffe, cfgGenderCaffe, new string[] { "Male", "Female" });


                                //Get result of YoloV3
                                NetResult[] resultPersons = yoloV3.Detect(bitmap, labelsFilters: new string[] { "person" });


                                //Get result of YoloV3 faces train
                                NetResult[] resultFaces = yoloV3Faces.Detect(bitmap);

                                using (Graphics canvas = Graphics.FromImage(resultImage))
                                {
                                    Font font = new Font(FontFamily.GenericSansSerif, 15);


                                    foreach (NetResult item in resultFaces)
                                    {
                                        //Create a roi by each faces
                                        using (Bitmap roi = (Bitmap)bitmap.Clone(item.Rectangle, bitmap.PixelFormat))
                                        {
                                            NetResult resultGender = caffeGender.Detect(roi).FirstOrDefault();

                                            canvas.DrawString($"{resultGender.Label} {resultGender.Probability:0.0%}",
                                                              font,
                                                              new SolidBrush(Color.Green),
                                                              item.Rectangle.X - font.GetHeight(), item.Rectangle.Y - font.GetHeight());
                                        }

                                        canvas.DrawRectangle(new Pen(Color.Red, 2), item.Rectangle);
                                    }

                                    canvas.Save();
                                }

                                resultImage.Save(Path.Combine(dir, "result.jpg"));
                            }
        }