Exemple #1
0
        /// <summary>
        /// 根据图片地址
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public static string ImageToWord(string imagePath)
        {
            string res = "";

            try
            {
                if (!File.Exists(imagePath))
                {
                    return(res);
                }
                // 设置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(imagePath);
                var client2 = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
                client2.Timeout = 60000;                  // 修改超时时间

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

                //Movie m = JsonConvert.DeserializeObject<Movie>(result);
                //string name = m.Name;
                Info info = JsonConvert.DeserializeObject <Info>(result.ToString());
                int  num  = info.words_result_num.ToInt();
                for (int i = 0; i < num; i++)
                {
                    res += info.words_result[i].words + "\r\n";
                }
            }
            catch (Exception ex)
            {
                ex.ToString().ToLog();
            }
            return(res);
        }
Exemple #2
0
        /// <summary>
        /// 百度识别接口
        /// </summary>
        /// <param name="base64String"></param>
        /// <returns></returns>
        public static string GetOcrResult(string base64String, OCRConfig oCRConfig)
        {
            Baidu.Aip.Ocr.Ocr client = new Baidu.Aip.Ocr.Ocr(oCRConfig.API_KEY, oCRConfig.SECRET_KEY);
            client.Timeout = 1000;  //修改超时时间

            byte[] imageBytes = Convert.FromBase64String(base64String);

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

            Console.WriteLine(result);
            var s = result["words_result"][0]["words"];

            return(s.ToString());
        }
Exemple #3
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);
        }
Exemple #4
0
        /// <summary>
        /// 车牌识别
        /// </summary>
        public void LicensePlateDemo()
        {
            var ApiKey    = "Sd5OH4BMmAqwKZvG6O56oqed";
            var SecretKey = "UX70FFACkOGb0at4q3ljzkYTaKC87vgG";
            var client    = new Baidu.Aip.Ocr.Ocr(ApiKey, SecretKey);

            var image = ImageToBase64(pictureBox.BackgroundImage, System.Drawing.Imaging.ImageFormat.Jpeg);

            if (image == null)
            {
                MessageBox.Show("请先加载图片");
                return;
            }

            // 调用车牌识别,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.LicensePlate(image);

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

            // 带参数调用车牌识别
            result = client.LicensePlate(image, options);

            OcrResult ocrResult = result.ToObject <OcrResult>();

            if (ocrResult.words_result == null)
            {
                MessageBox.Show("未检测到车牌");
                return;
            }
            foreach (var item in ocrResult.words_result)
            {
                txtResult.AppendText(item.color + "牌" + item.number + "\n");
            }
            //  Console.WriteLine(result);
        }
Exemple #5
0
        public Main()
        {
            InitializeComponent();

            // These are testing OCR api and will be expired soon. Please create your own from here: https://ai.baidu.com/tech/ocr/general
            var APP_ID     = "17917707";
            var API_KEY    = "34cIesqLIgj2advlwktx0D0K";
            var SECRET_KEY = "GUmlGTeFtIfqctLWLRabiV2aWrliPltB";

            _client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY)
            {
                Timeout = 60000
            };

            // load fonts
            _fontCollections = new FontCollections();

            foreach (string file in Directory.EnumerateFiles(_fontBasePath, "*.*", SearchOption.AllDirectories))
            {
                _fontCollections.AddFont(file, Path.GetFileNameWithoutExtension(file));
            }

            // load class label

            foreach (string line in _classDefination)
            {
                string[] lineContents = line.Split(',');

                int lineNum = -1;
                int.TryParse(lineContents[0], out lineNum);

                if (lineNum >= 0)
                {
                    _classLabel.Add(lineNum, lineContents[1]);
                }
            }

            Text = "智能图片文字字体鉴别 V" + Application.ProductVersion + "(科研专用)";
        }
        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);
        }
        public String send(byte[] image)
        {
            Console.WriteLine("Start OCR!");
            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" }
            };
            // 带参数调用通用文字识别, 图片参数为本地图片
            var result = client.GeneralBasic(image, options);

            // Console.WriteLine(result);

            if (result == null)
            {
                return("");
            }

            String trans = "";

            foreach (var words in result.GetValue("words_result"))
            {
                // Console.WriteLine(words);
                var w = words.Value <String>("words");
                trans += w;
            }

            Console.WriteLine(trans);
            return(trans);
        }
Exemple #8
0
        public static string getString(string url)
        {
            //AK/SK
            var API_KEY    = "FGPi0QpCbZxZxBaN6dvqt87X";
            var SECRET_KEY = "HunNq6XsLjF3a7aCAuirVaVQO7CKBuwW";
            var client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 60000; // 修改超时时间
            //var image = File.ReadAllBytes("E:\\Work Demo\\图片提取文字\\Recognition\\Recognition\\Image\\img.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);//网络图片:用户向服务请求识别一些背景复杂,特殊字体的文字。
            return(result.ToString());
        }
Exemple #9
0
        public string getwordandfix(string path)
        {
            string word = "";

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

            client.Timeout = 60000;  // 修改超时时间
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };

            Console.WriteLine("识别图片");
            try
            {
                object result1 = client.GeneralBasic(image, options);

                JavaScriptSerializer js = new JavaScriptSerializer();
                getword getwd           = js.Deserialize <getword>(result1.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);
        }
Exemple #10
0
        public static JObject BaiDuOCR(string fileName)
        {
            // 设置APPID/AK/SK
            var APP_ID     = Singleton.GetInstance().APP_ID;
            var API_KEY    = Singleton.GetInstance().API_KEY;
            var SECRET_KEY = Singleton.GetInstance().SECRET_KEY;
            var client     = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

            client.Timeout = 3000;  // 修改超时时间
            var image = File.ReadAllBytes(fileName);
            // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
            var result = client.GeneralBasic(image);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" },
                { "detect_direction", "true" },
                { "detect_language", "true" },
                { "probability", "true" }
            };
            // 带参数调用通用文字识别, 图片参数为本地图片
            JObject j = client.GeneralBasic(image, options);

            return(j);
        }
Exemple #11
0
        public string GeneralBasicDemo(string type, string value)
        {
            byte[] image  = new byte[1];
            var    client = new Baidu.Aip.Ocr.Ocr(this.key, this.secret);

            client.Timeout = 60000;
            if (type == "screen")
            {
                image = File.ReadAllBytes("screen.jpg");
            }
            if (type == "file")
            {
                image = File.ReadAllBytes(value);
            }
            var result = client.GeneralBasic(image);

            if (type == "url")
            {
                result = client.GeneralBasicUrl(value);
            }
            Console.WriteLine(result);
            JObject jObject = JObject.Parse(result.ToString());

            if (jObject.Property("error_code") != null)
            {
                return(jObject["error_msg"].ToString());
            }
            var list         = jObject["words_result"];
            var returnResult = "";

            foreach (JObject ll in list)
            {
                returnResult += ll["words"] + "\r\n";
            }
            return(returnResult);
        }
Exemple #12
0
        //链接图片识别文字
        public static void GeneralBasicUrl(string url, string API_KEY, string SECRET_KEY)
        {
            try {
                var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);

                // 调用通用文字识别, 图片参数为远程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);
            }
            catch (Exception e)
            {
                Common.CqApi.AddLoger(Sdk.Cqp.Enum.LogerLevel.Error, "网络图片识别错误", e.ToString());
            }
        }
Exemple #13
0
        /// <summary>
        /// 图片上文字识别方式
        /// </summary>
        /// <param name="imgUrl">图片路径</param>
        /// <param name="way">GeneralBasic(普通识别);AccurateBasic(高精度识别)</param>
        private void RecognitionWay(string imgUrl, string way)
        {
            var image  = File.ReadAllBytes(imgUrl);
            var client = new Baidu.Aip.Ocr.Ocr(ApiMessage.API_KEY, ApiMessage.SECRET_KEY);

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

            var result = client.AccurateBasic(image);
            // 如果有可选参数
            var options = new Dictionary <string, object> {
                { "language_type", "CHN_ENG" }, //语言
                { "detect_direction", "true" }, //图片方向
                { "probability", "true" }//图片识别成功可能性
            };

            // 带参数调用通用文字识别,识别方式有很多种,我只是取了其中常用的两种,其它方式可以查看官网帮助文档
            switch (way)
            {
            case "AccurateBasic":
                result = client.AccurateBasic(image, options);
                break;

            case "GeneralBasic":
                result = client.GeneralBasic(image, options);
                break;
            }
            string getJson = result.ToString();                                          //关键:result返回的是一个一串Json格式的数据,具体大家可以单独输出查看;       //所以要解析这个JSON,还需一个帮助类JsonImage,然后用JSON反序列化,最后StringBuilder拼接

            JsonImage.Root rt = JsonConvert.DeserializeObject <JsonImage.Root>(getJson); //JSON反序列化
            StringBuilder  sb = new StringBuilder();

            for (int i = 0; i < rt.words_result.Count; i++)
            {
                textBox1.Text = sb.AppendLine(rt.words_result[i].words).ToString();
            }
        }
Exemple #14
0
        /// <summary>
        /// 高精度文字识别
        /// </summary>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public string Ocr_Acc_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.AccurateBasic(image);

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

            // 带参数调用通用文字识别(高精度版)
            result = client.AccurateBasic(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);
        }
Exemple #15
0
        public static Image GeneralBasic(Image imageIn)
        {
            bool isBegin = false;

            location fwloc   = new ImageRotate.location();
            location dyczloc = new ImageRotate.location();


            var     client = new Baidu.Aip.Ocr.Ocr(apiKey, secretKey);
            var     image  = ImageToByteArray(imageIn);
            JObject result = client.GeneralWithLocatin(image, null);

            JToken js = result["words_result"];

            for (int i = 0; i < js.Count(); i++)
            {
                JToken item = js[i];
                if (item["words"].ToString().Contains("发文时间"))
                {
                    fwloc.X = int.Parse(item["location"]["left"].ToString());
                    fwloc.Y = int.Parse(item["location"]["top"].ToString());
                    fwloc.H = int.Parse(item["location"]["height"].ToString());
                    fwloc.W = int.Parse(item["location"]["width"].ToString());
                }
                else if (item["words"].ToString().Contains("本打印操作"))
                {
                    dyczloc.X = int.Parse(item["location"]["left"].ToString());
                    dyczloc.Y = int.Parse(item["location"]["top"].ToString());
                    dyczloc.H = int.Parse(item["location"]["height"].ToString());
                    dyczloc.W = int.Parse(item["location"]["width"].ToString());
                }
            }


            Bitmap   bitmap  = new Bitmap(imageIn.Width - 40, dyczloc.Y - fwloc.Y - fwloc.H - 40);
            Graphics graphic = Graphics.FromImage(bitmap);

            //截取原图相应区域写入作图区
            graphic.DrawImage(imageIn, 0, 0, new Rectangle(20, fwloc.Y + 20 + fwloc.H, imageIn.Width - 40, dyczloc.Y - fwloc.Y - fwloc.H - 60), GraphicsUnit.Pixel);
            //从作图区生成新图
            Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());

            return(saveImage);

            //string rid = null, aid = null;
            //int index = 0;
            //foreach (var j in js)
            //{
            //    var s = j["words"].ToString();

            //    if (s.StartsWith("发文时间"))
            //    {
            //        DateTime dt = DateTime.Parse(s.Split(':')[1]);

            //    }

            //    if (isBegin)
            //    {
            //        switch (index)
            //        {
            //            case 0:
            //                index++;
            //                rid = s;
            //                break;
            //            case 1:
            //                index++;
            //                aid = s;
            //                break;
            //            case 2:

            //                index = 0;
            //                break;
            //        }
            //    }
            //    if (s.StartsWith("本打印操作"))
            //    {
            //        isBegin = false;
            //    }
            //    if (s == "备注")
            //    {
            //        isBegin = true;
            //    }
            //}
            return(null);
        }
Exemple #16
0
 public static void Link()
 {
     Identification.client         = new Baidu.Aip.Ocr.Ocr(Identification.API_KEY, Identification.SECRET_KEY);
     Identification.client.Timeout = 60000;// 修改超时时间
 }
 public static void VehicleLicense()
 {
     var client = new Baidu.Aip.Ocr.Ocr("Api Key", "Secret Key");
     var image  = File.ReadAllBytes("图片文件路径");
     var result = client.VehicleLicense(image);
 }
Exemple #18
0
        protected override void Execute(NativeActivityContext context)
        {
            // var match = Element.Get(context);
            var    wordlimit     = WordLimit.Get(context);
            var    lang          = Config.local.ocrlanguage;
            var    casesensitive = CaseSensitive.Get(context);
            var    isfrontside   = IsFrontSide.Get(context);
            string basepath      = Interfaces.Extensions.DataDirectory;
            string path          = System.IO.Path.Combine(basepath, "tessdata");
            //ocr.TesseractDownloadLangFile(path, Config.local.ocrlanguage);
            //ocr.TesseractDownloadLangFile(path, "osd");
            var ele = Element.Get(context);

            // ele.element.Save(@"c:\temp\dump.png", System.Drawing.Imaging.ImageFormat.Png);

            // var result = ocr.GetIdTextcomponents(path, Config.local.ocrlanguage, ele.element);
            // var result = ocr.GetIdTextcomponents(path, Config.local.ocrlanguage, @"c:\temp\dump.png");

            ImageElement[] result;
            // 百度OCR
            var _ocr = new Baidu.Aip.Ocr.Ocr(ocr.API_KEY, ocr.SECRET_KEY);

            _ocr.Timeout = 60000;//设置超时时间
            //_ocr.Init(path, lang.ToString(), Emgu.CV.OCR.OcrEngineMode.TesseractLstmCombined);
            //_ocr.PageSegMode = Emgu.CV.OCR.PageSegMode.SparseText;

            // OpenRPA.Interfaces.Image.Util.SaveImageStamped(ele.element, "OCR");
            Bitmap sourceimg = null;

            if (ele is ImageElement)
            {
                // 传入的是图片
                sourceimg = ((ImageElement)ele).element;
            }
            else
            {
                // 传入非图片,开始截图
                sourceimg = Interfaces.Image.Util.Screenshot(ele.Rectangle.X, ele.Rectangle.Y, ele.Rectangle.Width, ele.Rectangle.Height);
            }
            String idCardSide;

            if (isfrontside)
            {
                idCardSide = "front";
            }
            else
            {
                idCardSide = "back";
            }
            MemoryStream ms = new MemoryStream();

            sourceimg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] imageBytes = ms.GetBuffer();
            ms.Close();

            var word_results = _ocr.Idcard(imageBytes, idCardSide);

            context.SetValue(Result, word_results["words_result"]);

            var image_status = word_results["image_status"].ToString();

            context.SetValue(OcrStatus, image_status);

            //IEnumerator<ImageElement> _enum = result.ToList().GetEnumerator();
            //context.SetValue(_elements, _enum);
            //bool more = _enum.MoveNext();
            //if (more)
            //{
            //    context.ScheduleAction(Body, _enum.Current, OnBodyComplete);
            //}
        }
Exemple #19
0
 public static void DrivingLicense()
 {
     var client = new Baidu.Aip.Ocr.Ocr(AiKeySecret.ApiKey, AiKeySecret.SecretKey);
     var image  = File.ReadAllBytes("图片文件路径");
     var result = client.DrivingLicense(image);
 }
Exemple #20
0
        static void Main(string[] args)
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            //DateTime start = DateTime.Now;

            //IntPtr ptr = (IntPtr)0x20BA6;
            //Rect AppRect = new Rect();
            //GetWindowRect(ptr, ref AppRect);
            //Rectangle rect = new Rectangle(AppRect.Left, AppRect.Top, (AppRect.Right - AppRect.Left), (AppRect.Bottom - AppRect.Top));
            //Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
            //Graphics g = Graphics.FromImage(bmp);
            //g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);

            //// make sure temp directory is there or it will throw.



            //bmp.Save(@"c:\test.jpg", ImageFormat.Jpeg);
            //List<IntPtr> listWnd = new List<IntPtr>();
            //EnumChildWindows(ptr, new EnumWindowProc(delegate (IntPtr hwnd, IntPtr lParam)
            //{
            //    int length = GetTextBoxTextLength(hwnd);
            //    StringBuilder sb = new StringBuilder();
            //    GetWindowText(hwnd, sb, length + 1);
            //    Console.WriteLine(sb.ToString());
            //    return true;

            //}), (IntPtr)0);
            //var list = GetAllChildrenWindowHandles(ptr, 1000);
            //foreach(var item in list)
            //{
            //    Console.WriteLine(item);
            //    EnumChildWindows(item, new EnumWindowProc(delegate (IntPtr hwnd, IntPtr lParam)
            //    {
            //        int length = GetTextBoxTextLength(hwnd);
            //        StringBuilder sb = new StringBuilder();
            //        GetWindowText(hwnd, sb, length + 1);
            //        Console.WriteLine(sb.ToString());
            //        return true;

            //    }), (IntPtr)0);
            //}
            var fileList   = new string[] { "A", "B", "C", "D" };
            var APP_ID     = "14565074";
            var API_KEY    = "nN5shGjIsPuVK0dN3cZP56rN";
            var SECRET_KEY = "pyik6Od7p1kgnL4BdX3MefAqjHM2SNHd";

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

            foreach (var fItem in fileList)
            {
                //var ocr = new TesseractEngine("./tessdata", "chi_sim", EngineMode.Default);
                //ocr.SetVariable("tessedit_char_whitelist", "委买卖一");

                var img   = new Bitmap(@"C:\Saved Pictures\" + fItem + ".png");
                var image = File.ReadAllBytes(@"C:\Saved Pictures\" + fItem + ".png");
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                var options = new Dictionary <string, object> {
                    { "recognize_granularity", "big" },
                    { "language_type", "CHN_ENG" },
                    { "detect_direction", "true" },
                    { "detect_language", "true" },
                    { "vertexes_location", "true" },
                    { "probability", "true" }
                };
                // 带参数调用通用文字识别(含位置信息版), 图片参数为本地图片
                var result = client.General(image, options);
                var show   = result["words_result"].ToList();
                var one    = show.Where(a => a["words"].ToString().StartsWith("委买队列")).FirstOrDefault();
                Pen myPen  = new Pen(System.Drawing.Color.BurlyWood, 3);

                var g      = Graphics.FromImage(img);
                int width  = Convert.ToUInt16(one["location"]["width"].ToString());
                int height = Convert.ToUInt16(one["location"]["height"].ToString());
                int x      = Convert.ToUInt16(one["location"]["left"].ToString());
                int y      = Convert.ToUInt16(one["location"]["top"].ToString());

                g.DrawRectangle(myPen, new Rectangle(x, y, width, height));
                Console.WriteLine(one);



                ////var img = CaptureScreen(1525, 187, 200, 20);
                //Pen myPen = new Pen(System.Drawing.Color.BurlyWood, 3);
                //var g = Graphics.FromImage(img);
                //var page = ocr.Process(img);
                //using (var iterator = page.GetIterator())
                //{

                //    iterator.Begin();
                //    do
                //    {
                //        string currentWord = iterator.GetText(PageIteratorLevel.Word);
                //        //do something with bounds
                //        Tesseract.Rect bounds;
                //        iterator.TryGetBoundingBox(PageIteratorLevel.Word, out bounds);
                //        Console.WriteLine("x1" + bounds.X1.ToString());
                //        Console.WriteLine("Y1" + bounds.Y1.ToString());
                //        Console.WriteLine("x2" + bounds.X2.ToString());
                //        Console.WriteLine("y2" + bounds.Y2.ToString());
                //        Console.WriteLine(currentWord);
                //        //if (currentWord.IndexOf("委") > 0 && (currentWord.IndexOf("买") > 0 || currentWord.IndexOf("卖") > 0))
                //        //{
                //        //    g.DrawRectangle(myPen, new Rectangle(bounds.X1, bounds.Y1, bounds.X2, bounds.Y2));
                //        //}
                //        if (currentWord.IndexOf("一") > 0 && (currentWord.IndexOf("买") > 0 || currentWord.IndexOf("卖") > 0))
                //        {
                //            g.DrawRectangle(myPen, new Rectangle(bounds.X1, bounds.Y1, bounds.X2, bounds.Y2));
                //        }

                //    }
                //    while (iterator.Next(PageIteratorLevel.Word));
                //}


                Bitmap bmp = new Bitmap(img);
                img.Dispose();
                bmp.Save(@"C:\Saved Pictures\" + fItem + "_b.png"); //
            }


            //var result = page.GetText();
            //Console.WriteLine(result);

            //var ProcessList = Process.GetProcesses();
            //var DzhProcessId = 0;
            //foreach (var item in ProcessList)
            //{
            //    if (item.MainWindowTitle.IndexOf("Notepad++") > 0 && item.ProcessName == "notepad++")
            //    {
            //        DzhProcessId = item.Id;
            //        break;
            //    }
            //}

            //var result = Process.GetProcessById(DzhProcessId).MainWindowHandle;
            //var hWnd = result;
            //IntPtr hscrdc = Win32Api.GetWindowDC(hWnd);
            //Rectangle windowRect = new Rectangle();
            //Win32Api.GetWindowRect(hWnd, ref windowRect);
            //int width = Math.Abs(windowRect.X - windowRect.Width);
            //int height = Math.Abs(windowRect.Y - windowRect.Height);
            //IntPtr hbitmap = Win32Api.CreateCompatibleBitmap(hscrdc, width, height);
            //IntPtr hmemdc = Win32Api.CreateCompatibleDC(hscrdc);
            //DateTime start = DateTime.Now;
            //Win32Api.SelectObject(hmemdc, hbitmap);
            //Win32Api.PrintWindow(hWnd, hmemdc, 0);
            //Bitmap bmp = Image.FromHbitmap(hbitmap);
            //DateTime end = DateTime.Now;
            //Win32Api.DeleteDC(hscrdc);//删除用过的对象
            //Win32Api.DeleteDC(hmemdc);//删除用过的对象
            //bmp.Save(@"c:\dd"+ DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg");

            //Parallel.Invoke(Ocr(bmp, 0), Ocr(bmp, 1), Ocr(bmp, 2));

            sw.Stop();
            Console.WriteLine("{0}", sw.ElapsedMilliseconds);
            Console.Read();
        }
Exemple #21
0
 /// <summary>
 /// 初始化百度AI客户端
 /// </summary>
 public void initAIClient()
 {
     client         = new Baidu.Aip.Ocr.Ocr(Settings.Default.BAIDU_API_KEY, Settings.Default.BAIDU_SECRET_KEY);
     client.Timeout = 10000;
 }
        public string GeneralBasicDemo(string path)
        {
            byte[] arr;
            client         = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
            client.Timeout = 60000;
            using (Bitmap bmp = new Bitmap(path))
            {
                FileInfo fileInfo = new FileInfo(path);
                double   length   = Convert.ToDouble(fileInfo.Length);
                double   Size     = length / 1024 / 1024;
                if (Size > 1.8)
                {
                    int width  = 1500;
                    int height = 0;
                    if (width == 0)
                    {
                        width = height * bmp.Width / bmp.Height;
                    }
                    if (height == 0)
                    {
                        height = width * bmp.Height / bmp.Width;
                    }

                    Image    imgSource = bmp;
                    Bitmap   outBmp    = new Bitmap(width, height);
                    Graphics g         = Graphics.FromImage(outBmp);
                    g.Clear(Color.Transparent);
                    // 设置画布的描绘质量
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode      = SmoothingMode.HighQuality;
                    g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(imgSource, new Rectangle(0, 0, width, height + 1), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
                    g.Dispose();
                    imgSource.Dispose();
                    bmp.Dispose();
                    MemoryStream ms = new MemoryStream();
                    outBmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    arr         = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();
                }
                else
                {
                    MemoryStream ms = new MemoryStream();
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    arr         = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();
                }

                //return outBmp;
            }

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

            return(res);
        }
Exemple #23
0
        public void TestMethod1()
        {
            var fileList = new string[] { "A", "B", "C", "D" };


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

            foreach (var fItem in fileList)
            {
                //var ocr = new TesseractEngine("./tessdata", "chi_sim", EngineMode.Default);
                //ocr.SetVariable("tessedit_char_whitelist", "委买卖一");

                var img   = new Bitmap(@"F:\byj\pic\" + fItem + ".png");
                var image = File.ReadAllBytes(@"F:\byj\pic\" + fItem + ".png");
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                var options = new Dictionary <string, object> {
                    { "recognize_granularity", "big" },
                    { "language_type", "CHN_ENG" },
                    { "detect_direction", "true" },
                    { "detect_language", "true" },
                    { "vertexes_location", "true" },
                    { "probability", "true" }
                };
                // 带参数调用通用文字识别(含位置信息版), 图片参数为本地图片
                var result = client.General(image, options);
                var show   = result["words_result"].ToList();
                var one    = show.Where(a => a["words"].ToString().StartsWith("委买队列")).FirstOrDefault();
                Newtonsoft.Json.Linq.JToken buyone = null;
                if (one == null)
                {
                    var AccurateOptions = new Dictionary <string, object> {
                        { "recognize_granularity", "big" },
                        { "detect_direction", "true" },
                        { "vertexes_location", "true" },
                        { "probability", "true" }
                    };
                    result = client.Accurate(image, AccurateOptions);
                    show   = result["words_result"].ToList();
                    one    = show.Where(a => a["words"].ToString().StartsWith("委买队列")).FirstOrDefault();
                }
                if (one == null)
                {
                    throw new Exception("分析失败 ");
                }
                Pen myPen  = new Pen(System.Drawing.Color.BurlyWood, 3);
                var g      = Graphics.FromImage(img);
                int width  = Convert.ToUInt16(one["location"]["width"].ToString());
                int height = Convert.ToUInt16(one["location"]["height"].ToString());
                int x      = Convert.ToUInt16(one["location"]["left"].ToString());
                int y      = Convert.ToUInt16(one["location"]["top"].ToString());

                g.DrawRectangle(myPen, new Rectangle(x, y, width, height));

                g.DrawRectangle(myPen, new Rectangle(x - 68, y + height, 55, height));

                //g.DrawRectangle(myPen, new Rectangle(x - 40, y + 37, 80, 31));

                g.DrawRectangle(myPen, new Rectangle(x + 36, y + height, 40, height));

                g.DrawRectangle(myPen, new Rectangle(x + 89, y + height, 30, height));
                Bitmap bmp = new Bitmap(img);
                img.Dispose();
                bmp.Save(@"F:\byj\pic\" + fItem + "_b.png"); //
            }
        }
Exemple #24
0
        /// <summary>
        /// 初始化函数
        /// </summary>
        public CoreAnalysis()
        {
            OcrEngine    = new List <TesseractEngine>(3);
            OcrEngine2   = new List <Baidu.Aip.Ocr.Ocr>(3);
            _monitorList = new List <MonitorLocation>();

            var te0 = new TesseractEngine("./tessdata", "eng", EngineMode.CubeOnly);

            te0.SetVariable("tessedit_char_whitelist", "0123456789");
            OcrEngine.Add(te0);

            var te1 = new TesseractEngine("./tessdata", "eng", EngineMode.TesseractOnly);

            te1.SetVariable("tessedit_char_whitelist", "0123456789");
            OcrEngine.Add(te1);

            var te2 = new TesseractEngine("./tessdata", "eng", EngineMode.CubeOnly);

            te2.SetVariable("tessedit_char_whitelist", "0123456789");
            OcrEngine.Add(te2);

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

            OcrEngine2.Add(client0);
            var client1 = new Baidu.Aip.Ocr.Ocr(BaiduHelper.API_KEY2, BaiduHelper.SECRET_KEY2);

            OcrEngine2.Add(client1);
            var client2 = new Baidu.Aip.Ocr.Ocr(BaiduHelper.API_KEY, BaiduHelper.SECRET_KEY);

            OcrEngine2.Add(client2);

            var one = new MonitorLocation();

            one.Width  = 40;
            one.Height = 20;
            one.Name   = "买一价";
            _monitorList.Add(one);
            var two = new MonitorLocation();

            two.Width  = 40;
            two.Height = 20;
            two.Name   = "买一量";
            _monitorList.Add(two);
            var three = new MonitorLocation();

            three.Width  = 30;
            three.Height = 20;
            three.Name   = "买一笔";
            _monitorList.Add(three);
            var four = new MonitorLocation();

            four.Width  = 40;
            four.Height = 20;
            four.Name   = "买一价";
            _monitorList.Add(four);
            var five = new MonitorLocation();

            five.Width  = 40;
            five.Height = 20;
            five.Name   = "买一量";
            _monitorList.Add(five);
            var six = new MonitorLocation();

            six.Width  = 30;
            six.Height = 20;
            six.Name   = "买一笔";
            _monitorList.Add(six);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(System.IO.File.ReadAllText(Application.StartupPath + @"\stocklist.json", System.Text.Encoding.Default));
            MarketList = Newtonsoft.Json.JsonConvert.DeserializeObject <Market>(sb.ToString());
        }
        public string GeneralBasicDemoB(string path)
        {
            try
            {
                client         = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
                client.Timeout = 30000;
                var image = File.ReadAllBytes(path);
                //var image = by;
                // 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
                //var result = client.GeneralBasic(image);
                // 如果有可选参数
                var options = new Dictionary <string, object> {
                    { "language_type", "CHG_ENG" },
                    { "detect_direction", "true" },
                    { "detect_language", "true" },
                    { "probability", "true" }
                };
                // 带参数调用通用文字识别, 图片参数为本地图片
                var result = client.GeneralBasic(image, options);
                if (result != null)
                {
                    WriteLog("path:" + path + ",Result" + JsonConvert.SerializeObject(result));
                }

                string str = string.Empty;
                for (int i = 0; i < result["words_result"].Count(); i++)
                {
                    var words  = result["words_result"][i]["words"]?.ToString();
                    var en     = Regex.Replace(words, "[^a-zA-Z]+", "", RegexOptions.IgnoreCase);
                    var shu    = Regex.Replace(words, "[^0-9]+", "", RegexOptions.IgnoreCase);
                    var en_shu = "";
                    if (string.IsNullOrEmpty(shu))
                    {
                        continue;
                    }
                    if (!string.IsNullOrWhiteSpace(en))
                    {
                        en_shu += en;
                    }
                    if (!string.IsNullOrWhiteSpace(shu))
                    {
                        en_shu += shu;
                    }

                    if (!string.IsNullOrWhiteSpace(en_shu))
                    {
                        en_shu += ",";
                    }

                    if (!string.IsNullOrWhiteSpace(en) && !string.IsNullOrWhiteSpace(shu) && !string.IsNullOrWhiteSpace(en_shu))
                    {
                        en_shu += shu + en + ",";
                    }

                    str += en_shu;
                    //str += result["words_result"][i]["words"] + ",";
                }
                var resultEnd = str.TrimEnd(',');
                if (resultEnd.Length > 200)
                {
                    return(resultEnd.Substring(0, 200));
                }

                return(resultEnd);
            }
            catch (Exception ex)
            {
                WriteLog("path:" + path + ",Message:" + ex.Message);
                return("");
            }
        }
 static ImageFindOrc()
 {
     client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
 }
Exemple #27
0
 public Api()
 {
     ocr         = new Baidu.Aip.Ocr.Ocr(ApiKey, secretKey);
     ocr.Timeout = 6000;
 }