public static JObject GetWordInImage(string imagePath)
        {
            try
            {
                string Json;
                //var APP_ID = "123456";
                var API_KEY    = "wekdnFOhKEfK3hAdE3thjKrz";
                var SECRET_KEY = "7bITH3Xumw0ST29uepqB2fz3Nn3ZD1x5";
                var client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
                client.Timeout = 60000;
                var image  = File.ReadAllBytes(imagePath);
                var result = client.GeneralBasic(image);
                Console.WriteLine(result);
                // 如果有可选参数
                var options = new Dictionary <string, object>
                {
                    { "language_type", "CHN_ENG" },
                    //{"detect_direction", "true"},
                    //{"detect_language", "true"},
                    //{"probability", "true"}
                };
                result = client.GeneralBasic(image, options);
                //var words = result["words_result"];
                //var list = words.Select(t => t.Last).Select(x => x["words"]);

                ////Console.WriteLine(result);
                ////richTextBox1.Text = result.ToString();
                //Json = result.ToString();
                return(result);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Example #2
0
        private static JObject JudgeMethod(ApiVersion apiVersion, byte[] image)
        {
            JObject result;

            switch (apiVersion)
            {
            case ApiVersion.GeneralBasic:
                result = client.GeneralBasic(image);
                break;

            case ApiVersion.General:
                result = client.General(image);
                break;

            case ApiVersion.AccurateBasic:
                result = client.AccurateBasic(image);
                break;

            case ApiVersion.Accurate:
                result = client.Accurate(image);
                break;

            case ApiVersion.Numbers:
                result = client.Numbers(image);
                break;

            default:
                result = null;
                break;
            }
            return(result);
        }
Example #3
0
        public ImageFindOrc()
        {
            Dictionary <string, string> dic = new Dictionary <string, string>();

            CheckPath(".png|.jpg|.bmp|.psd|.tga|.tif|.dds", searchOption: SearchOption.AllDirectories).ForEachPaths(
                re =>
            {
#if imageOrc
                var imageOrc = File.ReadAllBytes(re);
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                var str = client.GeneralBasic(imageOrc).ToString();
                Console.WriteLine(str);
                var result = JsonMapper.ToObject(str);
                if (result.Keys.Contains("error_code"))
                {
                    Console.ReadKey();
                    return;
                }

                if (result["words_result_num"].ToString().AsInt() <= 0)
                {
                    return;
                }
#endif

                var newPatn = re.Replace(InputPath, InputPath + "_new");
                FileHelper.CreateDirectory(newPatn);
                File.WriteAllBytes(newPatn, File.ReadAllBytes(re));
                dic[re.Replace(InputPath, "")] = GetExcelCell(re);
            });
            WriteAllLines(dic, InputPath);
        }
Example #4
0
        public async Task <string> OrcBasic(string filePath)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    var image = File.ReadAllBytes(filePath);
                    // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获

                    var result = _client.GeneralBasic(image);
                    Console.WriteLine(result);
                    // 如果有可选参数
                    var options = new Dictionary <string, object> {
                        { "language_type", "CHN_ENG" },
                        { "detect_direction", "true" },
                        { "detect_language", "true" },
                        { "probability", "true" }
                    };
                    // 带参数调用通用文字识别, 图片参数为本地图片
                    result = _client.GeneralBasic(image, options);

                    return result.ToString();
                }
                catch (Exception e)
                {
                    _logger.LogError(null, e);
                    throw;
                }
            }));
        }
Example #5
0
        static void xx()
        {
            try
            {
                string Json;
                var    APP_ID     = "123456";
                var    API_KEY    = "wekdnFOhKEfK3hAdE3thjKrz";
                var    SECRET_KEY = "7bITH3Xumw0ST29uepqB2fz3Nn3ZD1x5";
                var    client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
                client.Timeout = 60000;
                var image  = File.ReadAllBytes(@"C:\Users\Administrator\Desktop\新建文件夹\esc.png");
                var result = client.GeneralBasic(image);
                Console.WriteLine(result);
                // 如果有可选参数
                var options = new Dictionary <string, object>
                {
                    { "language_type", "CHN_ENG" },
                    //{"detect_direction", "true"},
                    //{"detect_language", "true"},
                    //{"probability", "true"}
                };

                result = client.GeneralBasic(image, options);

                var words = result["words_result"];
                var list  = words.Select(t => t.Last).Select(x => x["words"]);

                //Console.WriteLine(result);
                //richTextBox1.Text = result.ToString();
                Json = result.ToString();
            }
            catch (Exception ex)
            {
            }
        }
Example #6
0
 /// <summary>
 /// 图片识别OCR
 /// </summary>
 /// <param name="imgData">二进制图片</param>
 /// <returns></returns>
 public static string readOCR(byte[] imgData)
 {
     try
     {
         var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
         var result = client.GeneralBasic(imgData);
         // 如果有可选参数
         var options = new Dictionary <string, object> {
             { "language_type", "CHN_ENG" },
             { "detect_direction", "true" },
             { "detect_language", "true" },
             { "probability", "true" }
         };
         // 带参数调用通用文字识别, 图片参数为本地图片
         result = client.GeneralBasic(imgData, options);
         StringBuilder stringBuilder = new StringBuilder();
         var           r             = JToken.Parse(result.ToString());
         int           indexs        = r["words_result_num"].ToString().ToInt();
         for (int i = 0; i < indexs; i++)
         {
             stringBuilder.Append(r["words_result"][i]["words"].ToString());
         }
         return(stringBuilder.ToString());
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
        public static void GeneralBasic()
        {
            var client = new Baidu.Aip.Ocr.Ocr("Api Key", "Secret Key");
            var image  = File.ReadAllBytes("图片文件路径");

            // 通用文字识别
            var result = client.GeneralBasic(image);

            // 图片url
            result = client.GeneralBasic("https://www.baidu.com/img/bd_logo1.png");
        }
Example #8
0
        //本地图片文字识别
        public static string GeneralBasic(string filename, string API_KEY, string SECRET_KEY)
        {
            try {
                //var APP_ID = "你的 App ID";
                //var API_KEY = "M5uerfD1rEdXT6ddwCYK2tYs";
                //var SECRET_KEY = "ZTG6GYmrmXU655njhs6RVAMGFGY7Is8E";
                var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);


                string dpath = Common.AppDirectory;
                dpath = dpath.Substring(0, dpath.LastIndexOf("\\"));
                dpath = dpath.Substring(0, dpath.LastIndexOf("\\"));
                dpath = dpath.Substring(0, dpath.LastIndexOf("\\") + 1);

                var image = File.ReadAllBytes(dpath + "image\\" + filename);
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                //var result = client.GeneralBasic(image);
                //Common.CqApi.AddLoger(Sdk.Cqp.Enum.LogerLevel.Error, "图片识别错误", result+"");
                // 如果有可选参数
                var options = new Dictionary <string, object> {
                    { "language_type", "CHN_ENG" },
                    { "detect_direction", "false" },
                    { "detect_language", "false" },
                    { "probability", "false" }
                };
                // 带参数调用通用文字识别, 图片参数为本地图片
                var result = client.GeneralBasic(image, options);
                return(result + "");
            }
            catch (Exception e)
            {
                Common.CqApi.AddLoger(Sdk.Cqp.Enum.LogerLevel.Error, "图片识别错误", e.ToString());
                return("");
            }
        }
Example #9
0
        public void BaiduAPI()
        {
            var API_KEY    = "p8Tgf4cVCWi0QOGjnqfu22G9";
            var SECRET_KEY = "UvzNMtiR728kmjai8UjMLEctfZ2eVPNm";
            var client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 6000;  // 修改超时时间
            var image = File.ReadAllBytes("jietu.jpg");

            try
            {
                var result = client.GeneralBasic(image);
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                for (int i = 0; i < result["words_result"].Count(); i++)
                {
                    OCRresult = OCRresult + result["words_result"][i]["words"].ToString() + "\r\n";
                }
            }
            catch (OverflowException)
            {
                info = "网络出错请重试";
                massage Ma = new massage();
                Ma.Show();
                return;
            }
        }
Example #10
0
        /// <summary>
        /// 通用文字识别
        /// </summary>
        /// <param name="bmp"></param>
        public static List <string> GeneralBasic(Image bmp)
        {
            string apiOrcKey    = ConfigUtil.GetConfigValue(YUConst.SETTING_BAIDUAPIORCKEY);
            string apiSecretKey = ConfigUtil.GetConfigValue(YUConst.SETTING_BAIDUORCSECRETKEY);

            if (apiOrcKey.IsNullOrEmptyOrWhiteSpace() || apiSecretKey.IsNullOrEmptyOrWhiteSpace())
            {
                throw new Exception("无法获取到Api Key和Secret Key,调用百度ORC识别失败。");
            }

            var client = new Baidu.Aip.Ocr.Ocr(apiOrcKey, apiOrcKey);
            var bytes  = ImageUtils.ImageToBytes(bmp);
            var result = client.GeneralBasic(bytes);

            if (result.ContainsKey("error_code") && result.ContainsKey("error_msg"))
            {
                throw new Exception(string.Format("调用百度ORC识别失败,错误码:{0},错误信息:{1}", result["error_code"], result["error_msg"]));
            }

            List <string> orcResults = new List <string>();

            if (result.ContainsKey("words_result_num") && result.ContainsKey("words_result"))
            {
                var wordResults = result["words_result"];
                if (wordResults != null && wordResults.Any())
                {
                    foreach (var word in wordResults)
                    {
                        orcResults.Add(word.Value <string>("words"));
                    }
                }
            }

            return(orcResults);
        }
Example #11
0
        public static string getImgString(string path)
        {
            var API_KEY    = "FGPi0QpCbZxZxBaN6dvqt87X";
            var SECRET_KEY = "HunNq6XsLjF3a7aCAuirVaVQO7CKBuwW";
            var client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000; // 修改超时时间
            var    img    = File.ReadAllBytes(path);
            var    result = client.GeneralBasic(img);
            JToken words  = null;

            try
            {
                //if (result.TryGetValue("words_result", out words))
                //{

                //    if (words[0].Contains("words"))
                //    {
                //        return words[0]["words"].ToString();
                //    }

                //}
                string ret = string.Join(";", result["words_result"].ToList().Select(a => a["words"]));
                return(ret);
            }
            catch (Exception ce)
            {
                return(result.ToString());
            }
            return(string.Format("<{0}>", result.ToString()));
        }
Example #12
0
 private void btnLogin_Click(object sender, EventArgs e)
 {
     if (tbxApiKey.Text != "" && tbxSecretKey.Text != "")
     {
         Program.ApiKey    = tbxApiKey.Text;
         Program.SecretKey = tbxSecretKey.Text;
         var client         = new Baidu.Aip.Ocr.Ocr(Program.ApiKey, Program.SecretKey);
         var result         = client.GeneralBasic(BitmapByte(Icon.ToBitmap()), null);
         AccessTokenModel a = JsonConvert.DeserializeObject <AccessTokenModel>(result.ToString());
         if (a.error_msg != null)
         {
             string rz = "验证失败!请输入有效的ApiKey和SecretKey!\n";
             MessageBox.Show(rz);
         }
         else
         {
             MessageBox.Show("成功登录,登录id:" + a.log_id.ToString());
             this.DialogResult = DialogResult.OK;
         }
     }
     else
     {
         MessageBox.Show("请输入值!");
     }
 }
Example #13
0
        public string getTextFromImage(string url)
        {
            try
            {
                var image = File.ReadAllBytes(url);

                var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
                client.Timeout = 5000;//修改超时时间

                // 如果有可选参数
                var options = new Dictionary <string, object> {
                    { "language_type", "CHN_ENG" },
                    { "detect_direction", "true" },
                    { "detect_language", "true" },
                    { "probability", "true" }
                };

                // 带参数调用通用文字识别, 图片参数为本地图片
                var result = client.GeneralBasic(image, options);

                return(result.ToString());
            }
            catch (Exception err)
            {
                return(null);
            }
        }
Example #14
0
        public static string RecognitionImage(byte[] image)
        {
            // 设置APPID/AK/SK
            var APP_ID     = "21512957";
            var API_KEY    = "OFez8onF6CqQ8khtNnecrWGD";
            var SECRET_KEY = "2aAt05myciGn6DvGPGLAL8LQ5v4kMm56";
            var client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间

            //   var image = File.ReadAllBytes(@"C:\Users\admin\Desktop\微信图片_20200930104921.png");
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result1 = client.GeneralBasic(image);

            try
            {
                var word = result1.GetValue("words_result");
                var a    = JsonConvert.DeserializeObject <List <Words> >(word.ToString());
                var b    = a.FirstOrDefault()?.words;
                Console.WriteLine("百度验证码结果" + b);
                b = CalcCode(b);
                return(b);
            }
            catch (Exception e)
            {
                return("");
            }
        }
Example #15
0
        public void AdvancedGeneralDemo(string filepath)
        {
            // 设置APPID/AK/SK
            //var APP_ID = "17767489";
            var API_KEY    = "uq1WqDv14GMpouhgDRKblm6L";
            var SECRET_KEY = "xhGGclgNBKWMKVU0Uf8KZLo7N7RTwRwQ";

            var client = new Baidu.Aip.ImageClassify.ImageClassify(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间


            var image   = File.ReadAllBytes(filepath);
            var client2 = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;                   // 修改超时时间

            var result = client2.GeneralBasic(image); //本地图图片


            //var image = File.ReadAllBytes(filepath);
            //// 调用通用物体识别,可能会抛出网络等异常,请使用try/catch捕获
            //var result = client.AdvancedGeneral(image);
            //Console.WriteLine(result);
            //// 如果有可选参数
            //var options = new Dictionary<string, object>{
            //    {"baike_num", 5}
            //};
            //// 带参数调用通用物体识别
            //result = client.AdvancedGeneral(image, options);
            //Console.WriteLine(result);
            textBox2.Text = result.ToString();
            //result.ToString().ToShow();
        }
Example #16
0
        public string Export(string id)
        {
            //AK/SK

            var API_KEY    = "szC3Ne2fkbFD09wxqEVVki4s";
            var SECRET_KEY = "zBdAmT3y7U3OX61PcVr9nZgwwk8e5ryg";

            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间


            var image = System.IO.File.ReadAllBytes("D:\\excel\\" + id + ".jpg");
            var url   = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564654456007&di=7832dd6f515e654bdf5074e47b6803b1&imgtype=0&src=http%3A%2F%2Fpic.962.net%2Fup%2F2018-5%2F2018527102938219310.jpg";

            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            //用户向服务请求识别某张图中的所有文字
            var result = client.GeneralBasic(image);        //本地图图片

            //var result = client.GeneralBasicUrl(url);     //网络图片
            //var result = client.Accurate(image);          //本地图片:相对于通用文字识别该产品精度更高,但是识别耗时会稍长。

            //var result = client.General(image);           //本地图片:通用文字识别(含位置信息版)
            //var result = client.GeneralUrl(url);          //网络图片:通用文字识别(含位置信息版)

            //var result = client.GeneralEnhanced(image);   //本地图片:调用通用文字识别(含生僻字版)
            //var result = client.GeneralEnhancedUrl(url);  //网络图片:调用通用文字识别(含生僻字版)

            //var result = client.WebImage(image);          //本地图片:用户向服务请求识别一些背景复杂,特殊字体的文字。
            //var result = client.WebImageUrl(url);         //网络图片:用户向服务请求识别一些背景复杂,特殊字体的文字。

            //Console.WriteLine(result);
            return(result.ToString());
        }
Example #17
0
        public string onlygetword(string path)
        {
            string word  = "";
            var    image = File.ReadAllBytes(path);

            Console.WriteLine("加载图片1");
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间
            Console.WriteLine("识别图片2");
            try
            {
                object result = client.GeneralBasic(image);
                // 带参数调用通用文字识别, 图片参数为本地图片
                JavaScriptSerializer js    = new JavaScriptSerializer();
                getword2             getwd = js.Deserialize <getword2>(result.ToString());
                for (int i = 0; i < getwd.words_result_num; i++)
                {
                    word += getwd.words_result[i].words + "\r\n";
                }
                Console.WriteLine("识别文字完成");
            }
            catch
            {
                return("对不起,图片质量差无法识别");
            }
            return(word);
        }
Example #18
0
        public String GeneralBasicDemo(String file)
        {
            var image = File.ReadAllBytes(file);
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            //var result = ocr.GeneralBasic(image);
            //Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };
            // 带参数调用通用文字识别, 图片参数为本地图片
            var result = ocr.GeneralBasic(image, options);

            Console.WriteLine(result);
            String end = null;

            rt.log_id           = result["log_id"].ToString();
            rt.direction        = result["direction"].ToString();
            rt.words_result_num = Int32.Parse(result["words_result_num"].ToString());
            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();
            jArray = result.Value <JArray>("words_result");
            JObject jObject;

            for (int i = 0; i < jArray.Count; i++)
            {
                jObject  = JObject.Parse(jArray[i].ToString());
                rt.words = rt.words + jObject["words"].ToString() + "\r\n";
            }
            return(rt.words);
        }
Example #19
0
        /// <summary>
        /// 使用百度AI识别图片文字
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        private String extractImg(Bitmap img)
        {
            showMessage("正在提取图片中的文字");
            byte[] bytes   = (byte[])TypeDescriptor.GetConverter(img).ConvertTo(img, typeof(byte[]));
            var    options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };
            // 带参数调用通用文字识别, 图片参数为本地图片
            var result = client.GeneralBasic(bytes, options);

            Console.WriteLine("识别结果:" + Environment.NewLine + result);

            int    wordsCount  = (int)result.SelectToken("words_result_num");
            var    wordsResult = result.SelectToken("words_result").ToList();
            String text        = "";

            wordsResult.ForEach(wordResult =>
            {
                String word = (String)wordResult.SelectToken("words");
                text       += word;
            });
            //Console.WriteLine("文字提取结果:" + text);
            showMessage("成功提取到文字:" + text);
            return(text);
        }
Example #20
0
        public void GeneralBasicDemo()
        {
            var client = new Baidu.Aip.Ocr.Ocr(API_Key, SECRE_KEY);

            client.Timeout = 60000;
            var image = File.ReadAllBytes(ImagePath);

            OutResult = client.GeneralBasic(image);
        }
Example #21
0
        /// <summary>
        /// 通用文字识别
        /// </summary>
        /// <param name="bitmap"></param>
        public static JObject GeneralBasicDemo(Bitmap bitmap)
        {
            var image = Bitmap2Byte(bitmap);//File.ReadAllBytes(imgFile);

            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.GeneralBasic(Bitmap2Byte(bitmap));

            return(result);
        }
Example #22
0
        public string GetText(string path)
        {
            var image = File.ReadAllBytes(path);
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            // var result = client.GeneralBasic(image);
            // Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "false" },
                { "probability", "true" }
            };
            // 带参数调用通用文字识别, 图片参数为本地图片
            var           result = client.GeneralBasic(image, options);
            StringBuilder str    = new StringBuilder();

            try
            {
                JsonSerializer serializer = new JsonSerializer();
                StringReader   sr         = new StringReader(result.ToString());
                object         o          = serializer.Deserialize(new JsonTextReader(sr), typeof(Root));

                Root t = o as Root;

                foreach (var v in t.words_result)
                {
                    foreach (var x in v.words)
                    {
                        str.Append(x.ToString());
                    }
                }

                TextDetect.Properties.Settings.Default.used_cnt++;
                TextDetect.Properties.Settings.Default.date_record = System.DateTime.Now.ToLongDateString();
                TextDetect.Properties.Settings.Default.Save();

                return(str.ToString());
            }
            catch (Exception ex)
            {
                return("");
            }
        }
Example #23
0
        public static String GeneralBasic(string imgpath)
        {
            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
            var image  = File.ReadAllBytes(imgpath);

            // 通用文字识别
            var result = client.GeneralBasic(image, null);

            return(result.ToString());
        }
        private string OCR_AccurateBasic(Image image, bool GeneralOrAccurate)
        {
            if (image.Width > 4096 || image.Height > 4096)
            {
                return("图片尺寸太大了,图片尺寸改小些再试试.最大边长不能超过4096像素 Width:" + image.Width.ToString() + " Height:" + image.Height.ToString());
            }


            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间
            var imageByte = ImageProcess.ImageToBytes(image);

            /*
             * // 如果有可选参数
             * var options = new Dictionary<string, object>{
             *  {"language_type", "CHN_ENG"},
             *  {"detect_direction", "true"},
             *  {"detect_language", "true"},
             *  {"probability", "true"}
             * };
             * // 带参数调用通用文字识别, 图片参数为本地图片
             * var result = client.GeneralBasic(image, options);
             */


            JObject result;

            if (GeneralOrAccurate)
            {
                result = client.AccurateBasic(imageByte);
            }
            else
            {
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                result = client.GeneralBasic(imageByte);
            }

            JToken words_result_num = result.SelectToken("words_result_num");

            if (Convert.ToInt32(words_result_num) > 0)
            {
                var    words = result.SelectToken("words_result").Select(p => p["words"]).ToList();
                string temp  = "";
                foreach (var word in words)
                {
                    temp = temp + word.ToString() + "\r\n";
                }
                return(temp);
            }
            else
            {
                return("");
            }
        }
Example #25
0
        /// <summary>
        /// 通用文字识别
        /// </summary>
        /// <param name="imgPath">图片地址</param>
        /// <returns></returns>
        public string Ocr_Baidu(string imgPath)
        {
            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间

            var image = File.ReadAllBytes(imgPath);

            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.GeneralBasic(image);

            //Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                //CHN_ENG:中英文混合;
                { "language_type", "CHN_ENG" },
                //是否检测图像朝向,默认不检测,- true:检测朝向;
                { "detect_direction", "true" },
                //是否检测语言,默认不检测。- true:检测语言;
                { "detect_language", "true" },
                //是否返回识别结果中每一行的置信度
                { "probability", "true" }
            };

            // 带参数调用通用文字识别, 图片参数为本地图片
            result = client.GeneralBasic(image, options);

            //Console.WriteLine(result);

            string str        = result.ToString();
            var    StrJOb     = JObject.Parse(str);
            var    text       = from obj in (JArray)StrJOb["words_result"] select(string) obj["words"];
            string coordinate = "";

            foreach (var r in text)
            {
                coordinate = r;
            }

            return(coordinate);
        }
        public string GeneralBasicDemoA(string path)
        {
            var image = File.ReadAllBytes(path);
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.GeneralBasic(image);

            Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };

            // 带参数调用通用文字识别, 图片参数为本地图片
            result = client.GeneralBasic(image, options);
            string res = JsonConvert.SerializeObject(result);

            return(res);
        }
Example #27
0
        public void send(String filePath)
        {
            client         = new Baidu.Aip.Ocr.Ocr(m_key, m_secret);
            client.Timeout = 60000;  // 修改超时时间

            var image = File.ReadAllBytes(filePath);
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.GeneralBasic(image);

            Console.WriteLine(result);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "ENG" },
                { "detect_direction", "true" },
                { "detect_language", "false" },
                { "probability", "true" }
            };

            // 带参数调用通用文字识别, 图片参数为本地图片
            result = client.GeneralBasic(image, options);
            Console.WriteLine(result);
        }
Example #28
0
        /// <summary>
        /// 文字识别
        /// </summary>
        static void RecognitionImage()
        {
            // 设置APPID/AK/SK
            var APP_ID     = "21512957";
            var API_KEY    = "OFez8onF6CqQ8khtNnecrWGD";
            var SECRET_KEY = "2aAt05myciGn6DvGPGLAL8LQ5v4kMm56";

            var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000;  // 修改超时时间
            var url = "https://ai.bdstatic.com/file/3986A65C9EDA45AF8877DD42D5256403";

            //        // 调用通用文字识别, 图片参数为远程url图片,可能会抛出网络等异常,请使用try/catch捕获
            //        var result = client.GeneralBasicUrl(url);
            //        Console.WriteLine(result);
            //        // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };
            //        // 带参数调用通用文字识别, 图片参数为远程url图片
            //        result = client.GeneralBasicUrl(url, options);
            //        Console.WriteLine(result);

            var image = File.ReadAllBytes(@"C:\Users\admin\Desktop\微信图片_20200930104921.png");
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result1 = client.GeneralBasic(image);

            Console.WriteLine(result1);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            // 带参数调用通用文字识别, 图片参数为本地图片
            var result = client.GeneralBasic(image, options);

            Console.WriteLine(result);
        }
Example #29
0
        public static void TrainTicketDemo()
        {
            var image = File.ReadAllBytes(filePath);

            //预先识别检查是否为一张可以识别的火车票
            try
            {
                var firstresult = client.GeneralBasic(image);
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("识别错误{0}", e), "车票识别", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // 调用火车票识别
            try
            {
                var result = client.TrainTicket(image);
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("识别错误{0}", e), "车票识别", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #30
0
        public List <String> GeneralBasicParse(Bitmap screenshot)
        {
            var           image         = Bitmap2Byte(screenshot);
            var           resultjObject = client.GeneralBasic(image);
            List <string> rows          = new List <string>();

            JArray jlist = JArray.Parse(resultjObject["words_result"].ToString());

            for (int i = 0; i < jlist.Count; ++i)
            {
                var rowJObject = JObject.Parse(jlist[i].ToString());
                rows.Add(rowJObject["words"].ToString());
            }
            return(rows);
        }