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(""); } }
private void OCRthread(Image imag, DateTime currentTime) { Image image = imag; if (image == null) { return; } if (image.Height < 15) { int newHeight = 15; double magnification = (double)newHeight / (double)image.Height; int newWidth = (int)(image.Width * magnification); Bitmap bitmap = new Bitmap(image, newWidth, newHeight); image = bitmap; } if (image.Width < 15) { int newWidth = 15; double magnification = (double)newWidth / (double)image.Width; int newHeight = (int)(image.Height * magnification); Bitmap bitmap = new Bitmap(image, newWidth, newHeight); image = bitmap; } if (image.Height > _config.Max_image_Height || image.Height < _config.Min_image_Height || image.Width > _config.Max_image_Width || image.Width < _config.Min_image_Width ) { label3.Text = @"超设置尺寸,本次不识别. W:" + image.Width.ToString() + @" H" + image.Height.ToString(); return; } else { label3.Text = @""; } label1.Text = currentTime.ToString("HH:mm:ss") + @" 从剪切板提取:"; while (ClipboardData.Rows.Count > 20) { ClipboardData.Rows[0].Delete(); } ClipboardData.Rows.Add("", currentTime.ToString("HH:mm:ss:fff"), "图片", "", ImageProcess.ImageToBytes(image)); Baidu_ocr baidu_Ocr = new Baidu_ocr(image, radioButton_Precision_True.Checked, currentTime); baidu_Ocr.API_KEY = _config.Baidu_ocr_API_KEY; baidu_Ocr.APP_ID = _config.Baidu_ocr_APP_ID; baidu_Ocr.SECRET_KEY = _config.Baidu_ocr_SECRET_KEY; baidu_Ocr.UpdateUIDelegate += UpdataUIStatus;//绑定更新任务状态的委托 //baidu_Ocr.OCR(pictureBox1.Image, radioButton2.Checked); Thread OCR_thread = new Thread(baidu_Ocr.ThreadOCR); OCR_thread.IsBackground = true; OCR_thread.Start(); }