2016-11-10 56 views
1

項目牛津視覺API有問題。從project oxford git的例子工作正常,並識別圖像上的文字。但是,我的代碼會拋出異常:項目牛津視覺API ocr異常

引發「Microsoft.ProjectOxford.Vision.ClientException」類型的異常。 在Microsoft.ProjectOxford.Vision.VisionServiceClient.HandleException(例外的例外) 在Microsoft.ProjectOxford.Vision.VisionServiceClient.b__39_1 [TRequest,τ響應(例外五) 在System.AggregateException.Handle(Func鍵2 predicate) at Microsoft.ProjectOxford.Vision.VisionServiceClient.<SendAsync>d__39 2.MoveNext() ---從先前的位置在那裏引發異常--- 在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任務task) 堆棧跟蹤的結尾處System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任務task) 在Microsoft.ProjectOxford.Vision.VisionServiceClient.d__32.MoveNext() ---從以前位置拋出異常的堆棧跟蹤結束--- at System.Runtime.CompilerServices.Tas kAwaiter.ThrowForNonSuccess(任務task) 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任務task) 在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.d__14.MoveNext()英寸\ OcrWorker.cs:行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"; } } 
    } 

有沒有人有同樣的問題,我該如何解決呢?

+0

解決! 對於正確的工作,你應該使用: File.OpenRead(imageFilePath)在UploadAndRecognizeImageAsync方法代替:創建的MemoryStream和位圖複製到它 所以只要不通過內存流** ** RecognizeTextAsync SDK – Nemo

+0

通過FileStream的方法解決方案是好的,但是如果你想讓MemoryStream出於任何原因工作(例如,在調用OCR之前需要裁剪或操作圖像),所有你需要做的就是首先通過調用'imageMemoryStream.Position = 0'。否則,您在'MemoryStream'上的'read'指針在'image.Save()'後面的末尾。 – cthrash

回答

2

解決!爲了正確的工作,你應該使用imageMemoryStream.Seek(0,SeekOrigin.Begin);從圖像複製流後