Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 牛津视觉项目API ocr例外_C#_.net_Ocr_Microsoft Cognitive - Fatal编程技术网

C# 牛津视觉项目API ocr例外

C# 牛津视觉项目API ocr例外,c#,.net,ocr,microsoft-cognitive,C#,.net,Ocr,Microsoft Cognitive,牛津视觉API项目有问题。来自的示例可以很好地识别图像上的文本。但我的代码引发了异常: 引发了类型为“Microsoft.ProjectOxford.Vision.ClientException”的异常。 位于Microsoft.ProjectOxford.Vision.VisionServiceClient.HandleException(异常) 在Microsoft.ProjectOxford.Vision.VisionServiceClient.b_uu39_u1[TRequest,Tre

牛津视觉API项目有问题。来自的示例可以很好地识别图像上的文本。但我的代码引发了异常:

引发了类型为“Microsoft.ProjectOxford.Vision.ClientException”的异常。 位于Microsoft.ProjectOxford.Vision.VisionServiceClient.HandleException(异常) 在Microsoft.ProjectOxford.Vision.VisionServiceClient.b_uu39_u1[TRequest,TreResponse](例外e) 位于System.AggregateException.Handle(Func
2谓词)
在Microsoft.ProjectOxford.Vision.VisionServiceClient.d_u39上
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
在Microsoft.ProjectOxford.Vision.VisionServiceClient.d_u32.MoveNext()上
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
在System.Runtime.CompilerServices.TaskAwaiter
1.GetResult()中
在..\\OcrWorker.cs中的..OcrWorker.d_u15.MoveNext()处:第165行\r\n
---来自引发异常的上一个位置的堆栈结束跟踪---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在System.Runtime.CompilerServices.TaskWaiter.HandleNonSuccessAndDebuggerNotification(任务任务)中
at System.Runtime.CompilerServices.TaskAwaiter
1.GetResult() 位于..\OcrWorker.cs中的..OcrWorker.d_u14.MoveNext():第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"; } }
    }
publicstringsubscriptionkey{get;set;}
公共字符串OCResultText
{
得到
{
if(fullocresult==null)
{
FullOcrResult=新的StringBuilder();
}
字符串响应=string.Empty;
如果(完成)
{
response=fullocresult.ToString();
}
其他的
{
响应=空;
}
返回响应;
}
}
private bool OcrDone=true;
公共bool IsOcrDone{get{return OcrDone;}}
私有StringBuilder结果;
公共OcrWorker(字符串appKey)
{
SubscriptionKey=appKey;
FullOcrResult=新的StringBuilder();
}
公共字符串DoWorkSync(列出图像)
{
如果(完成)
{
List iteartionItems=新列表();
int i=0;
OcrDone=false;
foreach(图像中的var图像)
{
IterationItem ocrIterationItem=新的IterationItem();
尝试
{
任务o=DoWorkForIterationSync(图像,i);
o、 等待();
ocrIterationItem=o.结果;
}
捕获(例外情况除外)
{
var a=ex.GetBaseException();
}
iteartionItems.Add(ocrIterationItem);
i++;
}
GetOcrResultFromIterations(iteartionItems);
OcrDone=true;
}
返回OCResultText;
}
public void WriteResultToFile(字符串路径)
{
如果(完成)
{
if(File.Exists(path))
{
删除(路径);
}
AppendAllText(路径,OCResultText);
}
}
私有void GetOcrResultFromIterations(列出迭代结果)
{
iterationResults=iterationResults.OrderBy(item=>item.Number).ToList();
foreach(iterationResults中的var iterationItem)
{
var results=iterationItem.OcrResult;
fullocresult.AppendLine();
foreach(results.Regions中的var项)
{
foreach(项目行中的变量行)
{
foreach(行中的var字。字)
{
fullocresult.Append(word.Text);
fullocresult.Append(“”);
}
fullocresult.AppendLine();
}
fullocresult.AppendLine();
}
}
}
/// 
///执行此场景的工作
/// 
///要针对场景运行的映像的URI
///如果[true],则将图像上载到ProjectOxford;如果[false],则将Uri作为远程url提交;
/// 
专用异步任务DoWorkForIterationSync(位图图像,int iterationNumber)
{
var_status=“正在执行OCR…”;
//
//上传图像
//
OcrResults ocrResult=等待上载和识别图像异步(图像,识别语言.ShortCode);
_status=“OCR完成”;
//
//日志窗口中的日志分析结果
//
返回新的IterationItem()
{
编号=迭代编号,
OcrResult=OcrResult
};
}
/// 
///将图像上载到ProjectOxford并执行OCR
/// 
///图像文件路径。
///要识别的语言代码
/// 
私有异步任务上载和认知异步(位图图像,字符串语言)
{
// -----------------------------------------------------------------------
//关键示例代码从这里开始
// -----------------------------------------------------------------------
//
//创建牛津视觉API服务客户端项目
//
VisionServiceClient VisionServiceClient=新的VisionServiceClient(SubscriptionKey);
日志(“创建了VisionServiceClient”);
使用(Stream imageMemoryStream=new MemoryStream())
{
保存(imageMemoryStream,ImageFormat.Bmp);
//