Project OXFO​​RD VISION API OCR异常 [英] Project oxford vision API ocr exception

查看:80
本文介绍了Project OXFO​​RD VISION API OCR异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决了项目oxford vision API的问题.来自项目牛津git 的示例可以很好地工作并识别图像上的文本.但是我的代码抛出异常:

Got a problem with project oxford vision API. The example from project oxford git works fine and recognise text on images. But my code throws exception:

引发了类型为"Microsoft.ProjectOxford.Vision.ClientException"的异常. 在Microsoft.ProjectOxford.Vision.VisionServiceClient.HandleException(异常异常) 在Microsoft.ProjectOxford.Vision.VisionServiceClient.b__39_1 [TRequest,TResponse](异常e) 在System.AggregateException.Handle(Func 2 predicate) at Microsoft.ProjectOxford.Vision.VisionServiceClient.<SendAsync>d__39 2.MoveNext() ---从上一个引发异常的位置开始的堆栈结束跟踪--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在Microsoft.ProjectOxford.Vision.VisionServiceClient.d__32.MoveNext() ---从上一个引发异常的位置开始的堆栈结束跟踪--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在System.Runtime.CompilerServices.TaskAwaiter 1.GetResult() at ..OcrWorker.<UploadAndRecognizeImageAsync>d__15.MoveNext() in ..\\OcrWorker.cs:line 165\r\n --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 1.GetResult() 在.. \ OcrWorker.cs:第127行中的..OcrWorker.d__14.MoveNext()处

Exception of type 'Microsoft.ProjectOxford.Vision.ClientException' was thrown. at Microsoft.ProjectOxford.Vision.VisionServiceClient.HandleException(Exception exception) at Microsoft.ProjectOxford.Vision.VisionServiceClient.b__39_1[TRequest,TResponse](Exception e) at System.AggregateException.Handle(Func2 predicate) at Microsoft.ProjectOxford.Vision.VisionServiceClient.<SendAsync>d__392.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.ProjectOxford.Vision.VisionServiceClient.d__32.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at ..OcrWorker.<UploadAndRecognizeImageAsync>d__15.MoveNext() in ..\\OcrWorker.cs:line 165\r\n --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at ..OcrWorker.d__14.MoveNext() in ..\OcrWorker.cs:line 127

类代码:

public string SubscriptionKey { get; set; }
    public string OcrResultText
    {
        get
        {
            if (FullOcrResult == null)
            {
                FullOcrResult = new StringBuilder();
            }
            string response = string.Empty;
            if (OcrDone)
            {
                response = FullOcrResult.ToString();
            }
            else
            {
                response = null;
            }
            return response;
        }
    }
    private bool OcrDone = true;
    public bool IsOcrDone { get { return OcrDone; } }
    private StringBuilder FullOcrResult;

    public OcrWorker(string appKey)
    {
        SubscriptionKey = appKey;
        FullOcrResult = new StringBuilder();
    }

    public string DoWorkSync(List<Bitmap> images)
    {
        if (OcrDone)
        {
            List<IterationItem> iteartionItems = new List<IterationItem>();
            int i = 0;
            OcrDone = false;
            foreach (var image in images)
            {
                IterationItem ocrIterationItem = new IterationItem();
                try
                {
                    Task<IterationItem> o = DoWorkForIterationAsync(image, i);
                    o.Wait();
                    ocrIterationItem = o.Result;
                }
                catch (Exception ex)
                {
                    var a = ex.GetBaseException();
                }
                iteartionItems.Add(ocrIterationItem);
                i++;
            }
            GetOcrResultFromIterations(iteartionItems);
            OcrDone = true;
        }
        return OcrResultText;
    }

    public void WriteResultToFile(string path)
    {
        if (OcrDone)
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.AppendAllText(path, OcrResultText);
        }
    }

    private void GetOcrResultFromIterations(List<IterationItem> iterationResults)
    {
        iterationResults = iterationResults.OrderBy(item => item.Number).ToList();
        foreach (var iterationItem in iterationResults)
        {
            var results = iterationItem.OcrResult;
            FullOcrResult.AppendLine();
            foreach (var item in results.Regions)
            {
                foreach (var line in item.Lines)
                {
                    foreach (var word in line.Words)
                    {
                        FullOcrResult.Append(word.Text);
                        FullOcrResult.Append(" ");
                    }
                    FullOcrResult.AppendLine();
                }
                FullOcrResult.AppendLine();
            }
        }
    }

    /// <summary>
    /// Perform the work for this scenario
    /// </summary>
    /// <param name="imageUri">The URI of the image to run against the scenario</param>
    /// <param name="upload">Upload the image to Project Oxford if [true]; submit the Uri as a remote url if [false];</param>
    /// <returns></returns>
    private async Task<IterationItem> DoWorkForIterationAsync(Bitmap image, int iterationNumber)
    {
        var _status = "Performing OCR...";

        //
        // Upload an image
        //
        OcrResults ocrResult = await UploadAndRecognizeImageAsync(image, RecognizeLanguage.ShortCode);
        _status = "OCR Done";

        //
        // Log analysis result in the log window
        //
        return new IterationItem()
        {
            Number = iterationNumber,
            OcrResult = ocrResult
        };
    }

    /// <summary>
    /// Uploads the image to Project Oxford and performs OCR
    /// </summary>
    /// <param name="imageFilePath">The image file path.</param>
    /// <param name="language">The language code to recognize for</param>
    /// <returns></returns>
    private async Task<OcrResults> UploadAndRecognizeImageAsync(Bitmap image, string language)
    {
        // -----------------------------------------------------------------------
        // KEY SAMPLE CODE STARTS HERE
        // -----------------------------------------------------------------------

        //
        // Create Project Oxford Vision API Service client
        //
        VisionServiceClient VisionServiceClient = new VisionServiceClient(SubscriptionKey);
        Log("VisionServiceClient is created");

        using (Stream imageMemoryStream = new MemoryStream())
        {
            image.Save(imageMemoryStream, ImageFormat.Bmp);
            //
            // Upload an image and perform OCR
            //
            Log("Calling VisionServiceClient.RecognizeTextAsync()...");
            OcrResults ocrResult = await VisionServiceClient.RecognizeTextAsync(imageMemoryStream, language);
            return ocrResult;
        }

        // -----------------------------------------------------------------------
        // KEY SAMPLE CODE ENDS HERE
        // -----------------------------------------------------------------------
    }

    //get ocred text
    class IterationItem
    {
        public int Number { get; set; }
        public OcrResults OcrResult { get; set; }
    }
    public static class RecognizeLanguage
    {
        public static string ShortCode { get { return "en"; } }
        public static string LongName { get { return "English"; } }
    }

有人有同样的问题吗,我该如何解决?

Did anyone have same problem and how can i solve it?

推荐答案

已解决!为了正确工作,您应该使用imageMemoryStream.Seek(0,SeekOrigin.Begin);从图像复制流之后

Solved! For correct work you should use imageMemoryStream.Seek(0, SeekOrigin.Begin); after copy stream from image

这篇关于Project OXFO​​RD VISION API OCR异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆