Ejemplo n.º 1
0
        public void BatchReadPdfFileInStreamTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "BatchReadPdfFileInStreamTest");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                    using (FileStream stream = new FileStream(GetTestImagePath("menu.pdf"), FileMode.Open))
                    {
                        BatchReadFileInStreamHeaders headers = client.BatchReadFileInStreamAsync(stream).Result;

                        Assert.NotNull(headers.OperationLocation);

                        ReadOperationResult readOperationResult = GetRecognitionResultWithPolling(client, headers.OperationLocation);

                        Assert.NotNull(readOperationResult);
                        Assert.Equal(TextOperationStatusCodes.Succeeded, readOperationResult.Status);

                        Assert.NotNull(readOperationResult.RecognitionResults);
                        Assert.Equal(1, readOperationResult.RecognitionResults.Count);

                        var recognitionResult = readOperationResult.RecognitionResults[0];

                        Assert.Equal(1, recognitionResult.Page);
                        Assert.Equal(8.5, recognitionResult.Width);
                        Assert.Equal(11, recognitionResult.Height);
                        Assert.Equal(TextRecognitionResultDimensionUnit.Inch, recognitionResult.Unit);

                        Assert.Equal(28, recognitionResult.Lines.Count);
                        Assert.Equal("Microsoft", recognitionResult.Lines[0].Text);
                    }
            }
        }
        public static async Task <string> ExtractUrlLocal(ComputerVisionClient client, string localImage)
        {
            const int numberOfCharsInOperationId = 36;

            using (Stream imageStream = File.OpenRead(localImage))
            {
                BatchReadFileInStreamHeaders localFileTextHeaders = await client.BatchReadFileInStreamAsync(imageStream);

                string operationLocation = localFileTextHeaders.OperationLocation;
                string operationId       = operationLocation.Substring
                                               (operationLocation.Length - numberOfCharsInOperationId);
                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = await client.GetReadOperationResultAsync(operationId);

                    await Task.Delay(1000);
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);
                StringBuilder sb = new StringBuilder();
                var           recognitionResults = results.RecognitionResults;
                foreach (TextRecognitionResult result in recognitionResults)
                {
                    foreach (Line line in result.Lines)
                    {
                        sb.Append($"{line.Text} ");
                    }
                }
                return(sb.ToString());
            }
        }
Ejemplo n.º 3
0
        // Recognize text from a local image
        private async Task ExtractLocalTextAsync(
            ComputerVisionClient computerVision, string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine(
                    "\nUnable to open or read localImagePath:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                // Start the async process to recognize the text
                try
                {
                    BatchReadFileInStreamHeaders textHeaders =
                        await computerVision.BatchReadFileInStreamAsync(
                            imageStream, textRecognitionMode);

                    await GetTextAsync(computerVision, textHeaders.OperationLocation);
                }
                catch (Exception err)
                {
                    Global.ProcessStatus = ProcessStatus.Error.ToString();
                    //Thread.Sleep(100);
                    OnReadDone?.Invoke(err, EventArgs.Empty);
                }
            }

            //DO FILTER
        }
Ejemplo n.º 4
0
        public async Task <IEnumerable <TextRecognitionResult> > ReadBitmapAsync(string fileName, CancellationToken token)
        {
            // Read text from URL
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                BatchReadFileInStreamHeaders textHeaders = await Client.BatchReadFileInStreamAsync(fs, token);

                // After the request, get the operation location (operation ID)
                string operationLocation = textHeaders.OperationLocation;
                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                // We only need the ID and not the full URL
                const int numberOfCharsInOperationId = 36;
                string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
                // Extract the text
                // Delay is between iterations and tries a maximum of 10 times.
                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                Console.WriteLine();
                do
                {
                    results = await Client.GetReadOperationResultAsync(operationId);

                    await Task.Delay(1000);

                    if (i == 9)
                    {
                        Console.WriteLine("Server timed out.");
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);
                return(results.RecognitionResults);
            }
        }
Ejemplo n.º 5
0
                    public async Task ExtractText(string data)
                    {
                        ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { });

                        //Endpoint
                        computerVision.Endpoint = Endpoint;

                        //Image data to Byte Array
                        byte[] imageBytes = Convert.FromBase64String(data);

                        //Byte Array To Stream
                        Stream stream = new MemoryStream(imageBytes);

                        try
                        {
                            //Starting the async process to recognize the text
                            BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(stream, textRecognitionMode);

                            await GetTextAsync(computerVision, textHeaders.OperationLocation);
                        }
                        catch (Exception e)
                        {
                            Error = e.Message;
                        }
                    }
Ejemplo n.º 6
0
        /*
         *	EXTRACT TEXT - LOCALFILE IMAGE
         */
        public async Task ExtractText(string localImage)
        {
            const int numberOfCharsInOperationId = 36;

            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("EXTRACT TEXT - LOCAL IMAGE");
            Console.WriteLine();

            Console.WriteLine($"Extracting text from local image {Path.GetFileName(localImage)}...");
            Console.WriteLine();
            using (Stream imageStream = File.OpenRead(localImage))
            {
                // Read the text from the local image
                BatchReadFileInStreamHeaders localFileTextHeaders = await _client.BatchReadFileInStreamAsync(imageStream);

                // Get the operation location (operation ID)

                // After the request, get the operation location (operation ID)
                string operationLocation = localFileTextHeaders.OperationLocation;

                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                // We only need the ID and not the full URL

                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

                // Extract the text
                // Delay is between iterations and tries a maximum of 10 times.
                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;

                do
                {
                    results = await _client.GetReadOperationResultAsync(operationId);

                    Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                    await Task.Delay(1000);
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

                // Display the found text.
                Console.WriteLine();
                var recognitionResults = results.RecognitionResults;
                foreach (TextRecognitionResult result in recognitionResults)
                {
                    foreach (var line in result.Lines)
                    {
                        Console.WriteLine($"Checking... {line.Text}");
                        if (_reNumberPlate.IsMatch(line.Text))
                        {
                            Console.WriteLine(line.Text);
                        }
                    }
                }
                Console.WriteLine();
            }
        }
Ejemplo n.º 7
0
        // ocr
        async void RecognizeText(object sender, System.EventArgs e)
        {
            try
            {
                await CrossMedia.Current.Initialize();

                if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                {
                    await DisplayAlert("No Camera", ":( No camera available.", "OK");

                    return;
                }

                var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
                {
                    Directory = "Sample",
                    Name      = "FaceDetectionSample.jpg"
                });

                if (file == null)
                {
                    return;
                }

                var image = new Image();

                image.Source = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    return(stream);
                });

                var client = new ComputerVisionClient(
                    new ApiKeyServiceClientCredentials(Constants.COMPUTER_VISION_KEY),
                    new System.Net.Http.DelegatingHandler[] { })
                {
                    Endpoint = Constants.COMPUTER_VISION_ROOT
                };

                var description = String.Empty;
                BatchReadFileInStreamHeaders textHeaders =
                    await client.BatchReadFileInStreamAsync(
                        file.GetStream());

                using (UserDialogs.Instance.Loading("Recognizing Text"))
                {
                    description = await GetTextAsync(client, textHeaders.OperationLocation);
                }

                await DisplayAlert("Detected Text", description, "OK");
            }

            catch (Exception ex) {
                await DisplayAlert("Oh no!!!", ex.Message, "OK");
            }
        }
Ejemplo n.º 8
0
        // </snippet_extract_display>

        /*
         * END - BATCH READ FILE - URL IMAGE
         */

        /*
         * BATCH READ FILE - LOCAL IMAGE
         * This API call offers an improvement of results over the Recognize Text calls.
         */
        public static async Task BatchReadFileLocal(ComputerVisionClient client, string localImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("BATCH READ FILE - LOCAL IMAGE");
            Console.WriteLine();

            // Helps calucalte starting index to retrieve operation ID
            const int numberOfCharsInOperationId = 36;

            Console.WriteLine($"Extracting text from local image {Path.GetFileName(localImage)}...");
            Console.WriteLine();
            using (Stream imageStream = File.OpenRead(localImage))
            {
                // Read the text from the local image
                BatchReadFileInStreamHeaders localFileTextHeaders = await client.BatchReadFileInStreamAsync(imageStream);

                // Get the operation location (operation ID)
                string operationLocation = localFileTextHeaders.OperationLocation;

                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

                // Extract text, wait for it to complete.
                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = await client.GetReadOperationResultAsync(operationId);

                    Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                    await Task.Delay(1000);

                    if (maxRetries == 9)
                    {
                        Console.WriteLine("Server timed out.");
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

                // Display the found text.
                Console.WriteLine();
                var textRecognitionLocalFileResults = results.RecognitionResults;
                foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
                {
                    foreach (Line line in recResult.Lines)
                    {
                        Console.WriteLine(line.Text);
                    }
                }
                Console.WriteLine();
            }
        }
Ejemplo n.º 9
0
        //-------------------------------------------------------------



        public async Task BatchReadFileLocal(ComputerVisionClient client, string localImage)
        {
            // Helps calucalte starting index to retrieve operation ID
            const int numberOfCharsInOperationId = 36;

            addDebugMessage($"Extracting text from local image {Path.GetFileName(localImage)}...");
            Console.WriteLine();
            using (Stream imageStream = File.OpenRead(localImage))
            {
                // Read the text from the local image
                BatchReadFileInStreamHeaders localFileTextHeaders = await client.BatchReadFileInStreamAsync(imageStream);

                addDebugMessage("Read text from local image.");
                // Get the operation location (operation ID)
                string operationLocation = localFileTextHeaders.OperationLocation;
                addDebugMessage("Got the operation location.");
                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
                addDebugMessage("Got the URI.");
                // Extract text, wait for it to complete.
                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = await client.GetReadOperationResultAsync(operationId);

                    await Task.Delay(1000);

                    if (i == 9)
                    {
                        addDebugMessage("Server timed out.");
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

                // Display the found text.
                Console.WriteLine();
                var textRecognitionLocalFileResults = results.RecognitionResults;
                foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
                {
                    foreach (Line line in recResult.Lines)
                    {
                        textBox2.AppendText(line.Text + Environment.NewLine);
                    }
                }
            }

            button1.Enabled = true;
            button2.Enabled = true;
            button2.Text    = "Detect";
        }
Ejemplo n.º 10
0
        public async Task <ExtractTextFromPictureResult> ExtractTextFromPicture(Stream pictureStream)
        {
            try
            {
                BatchReadFileInStreamHeaders textHeaders = await _computerVisionClient.BatchReadFileInStreamAsync(pictureStream);

                string operationLocation = textHeaders.OperationLocation;

                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                // We only need the ID and not the full URL
                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

                // Extract the text
                // Delay is between iterations and tries a maximum of 10 times.
                int numberOfRetries = 0;
                ReadOperationResult results;

                do
                {
                    results = await _computerVisionClient.GetReadOperationResultAsync(operationId);

                    await Task.Delay(1000);

                    if (numberOfRetries == 9)
                    {
                        return(new ExtractTextFromPictureResult {
                            ErrorMessage = "Server timed out."
                        });
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && numberOfRetries++ < maxNumberOfRetries);

                var            textRecognitionLocalFileResults = results.RecognitionResults;
                IList <string> textLines = new List <string>();
                foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
                {
                    foreach (Line line in recResult.Lines)
                    {
                        textLines.Add(line.Text);
                    }
                }

                return(new ExtractTextFromPictureResult(textLines.ToArray()));
            }
            catch (Exception e)
            {
                return(new ExtractTextFromPictureResult {
                    ErrorMessage = e.Message
                });
            }
        }
        private async Task BatchReadFileFromStreamAsync(ComputerVisionClient computerVision, string imagePath, int numberOfCharsInOperationId)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(imageStream);
                await GetTextAsync(computerVision, textHeaders.OperationLocation, numberOfCharsInOperationId);
            }
        }
Ejemplo n.º 12
0
        private async Task <string> OCR(byte[] contentBytes)
        {
            var    textFromImage = "";
            var    visionClient  = GetComputerVisionClient();
            Stream stream        = new MemoryStream(contentBytes);
            BatchReadFileInStreamHeaders textHeaders = await visionClient.BatchReadFileInStreamAsync(stream);

            string    operationLocation          = textHeaders.OperationLocation;
            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            // Delay is between iterations and tries a maximum of 10 times.
            int i          = 0;
            int maxRetries = 10;
            ReadOperationResult results;

            Console.WriteLine($"Extracting text from image");
            Console.WriteLine();

            do
            {
                results = await visionClient.GetReadOperationResultAsync(operationId);

                Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                await Task.Delay(1000);

                if (i == 9)
                {
                    Console.WriteLine("Server timed out.");
                }
            }while ((results.Status == TextOperationStatusCodes.Running || results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

            // Display the found text.
            Console.WriteLine();
            var textRecognitionLocalFileResults = results.RecognitionResults;

            foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
            {
                foreach (Line line in recResult.Lines)
                {
                    textFromImage += " " + line.Text;
                    Console.WriteLine(line.Text);
                }
            }
            Console.WriteLine();

            return(textFromImage);
        }
Ejemplo n.º 13
0
        // Recognize text from a local image
        private static async Task ExtractTextFromStreamAsync(ComputerVisionClient computerVision, string imagePath, int numberOfCharsInOperationId, TextRecognitionMode textRecognitionMode)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                // Start the async process to recognize the text
                BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(imageStream, textRecognitionMode);
                await GetTextAsync(computerVision, textHeaders.OperationLocation, numberOfCharsInOperationId);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Распознать рукописный текст
        /// </summary>
        /// <param name="localImagePath"></param>
        /// <returns></returns>
        public static async Task <string> ReadHandwrittenText(string localImagePath)
        {
            const int numberOfCharsInOperationId = 36;

            using (Stream imageStream = File.OpenRead(localImagePath))
            {
                BatchReadFileInStreamHeaders localFileTextHeaders = await AuthenticationComputerVision.client.BatchReadFileInStreamAsync(imageStream);

                string operationLocation = localFileTextHeaders.OperationLocation;
                string operationId       = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = await AuthenticationComputerVision.client.GetReadOperationResultAsync(operationId);

                    await Task.Delay(1000);

                    if (maxRetries == 9)
                    {
                        throw new TextDetectorException("Превышено время связи с сервером");
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

                string textResult = null;
                foreach (TextRecognitionResult recResult in results.RecognitionResults)
                {
                    foreach (var line in recResult.Lines)
                    {
                        textResult += line.Text + " ";
                    }
                }

                if (textResult == null)
                {
                    throw new TextDetectorException("Ничего не распознано");
                }
                else
                {
                    return(textResult);
                }
            };
        }
        public static async Task ExtractTextLocal(ComputerVisionClient client, string localImage)
        {
            // Helps calucalte starting index to retrieve operation ID
            const int numberOfCharsInOperationId = 36;

            using (Stream imageStream = File.OpenRead(localImage))
            {
                // Read the text from the local image
                BatchReadFileInStreamHeaders localFileTextHeaders = await client.BatchReadFileInStreamAsync(imageStream);

                // Get the operation location (operation ID)
                string operationLocation = localFileTextHeaders.OperationLocation;
                // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
                // Extract text, wait for it to complete.
                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = await client.GetReadOperationResultAsync(operationId);

                    await Task.Delay(1000);

                    if (maxRetries == 9)
                    {
                        throw new Exception("Azure API timed out");
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);
                // Display the found text.
                var textRecognitionLocalFileResults = results.RecognitionResults;
                foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
                {
                    using (StreamWriter sw = new StreamWriter(@"C:\Users\35385\source\repos\BookingSystem\BookingSystem\surveytest.txt"))
                    {
                        foreach (Line line in recResult.Lines)
                        {
                            sw.WriteLine(line.Text);
                        }
                    }
                }
            }
        }
        private static async Task <string> GetTextFromImage(Stream imageStream, ILogger logger)
        {
            string cognitiveServiceApiKey   = GetEnvVarValue(COGNITIVESERVICE_KEY);
            string cognitiveServiceEndpoint = GetEnvVarValue(COGNITIVESERVICE_ENDPOINT);

            ComputerVisionClient computerVisionClient = new ComputerVisionClient(
                new ApiKeyServiceClientCredentials(cognitiveServiceApiKey),
                new System.Net.Http.DelegatingHandler[] { });

            computerVisionClient.Endpoint = cognitiveServiceEndpoint;

            // Start the async process to recognize the text
            BatchReadFileInStreamHeaders textHeaders =
                await computerVisionClient.BatchReadFileInStreamAsync(imageStream);

            var t = GetTextAsync(computerVisionClient, textHeaders.OperationLocation);

            t.Wait();
            return(t.Result);
        }
Ejemplo n.º 17
0
                        public async Task ExtractText(string data, bool flag)
                        {
                            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { });

                            //Endpoint
                            computerVision.Endpoint = Endpoint;

                            if (flag)
                            {
                                if (!Uri.IsWellFormedUriString(data, UriKind.Absolute))
                                {
                                    Error = "Invalid remoteImageUrl: " + data;
                                }

                                //Starting the async process to read the text
                                BatchReadFileHeaders textHeaders = await computerVision.BatchReadFileAsync(data, textRecognitionMode);

                                await GetTextAsync(computerVision, textHeaders.OperationLocation);
                            }
                            else
                            {
                                //Image data to Byte Array
                                byte[] imageBytes = Convert.FromBase64String(data);

                                //Byte Array To Stream
                                Stream stream = new MemoryStream(imageBytes);

                                try
                                {
                                    //Starting the async process to recognize the text
                                    BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(stream, textRecognitionMode);

                                    await GetTextAsync(computerVision, textHeaders.OperationLocation);
                                }
                                catch (Exception e)
                                {
                                    Error = e.Message;
                                }
                            }
                        }
Ejemplo n.º 18
0
        private String BatchReadFileLocal(ComputerVisionClient client, String localImage)
        {
            StringBuilder stringBuilder = new StringBuilder();
            const Int32   numberOfCharsInOperationId = 36;

            using (Stream imageStream = System.IO.File.OpenRead(localImage))
            {
                BatchReadFileInStreamHeaders localFileTextHeaders = client.BatchReadFileInStreamAsync(imageStream).Result;
                string operationLocation = localFileTextHeaders.OperationLocation;

                string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

                int i          = 0;
                int maxRetries = 10;
                ReadOperationResult results;
                do
                {
                    results = client.GetReadOperationResultAsync(operationId).Result;
                    Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                    Task.Delay(1000);
                    if (i == 9)
                    {
                        return(String.Empty);
                    }
                }while ((results.Status == TextOperationStatusCodes.Running ||
                         results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

                var textRecognitionLocalFileResults = results.RecognitionResults;
                foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
                {
                    foreach (Line line in recResult.Lines)
                    {
                        stringBuilder.Append(line.Text);
                    }
                }
            }

            return(stringBuilder.ToString());
        }
Ejemplo n.º 19
0
        public static async Task <IList <TextRecognitionResult> > GetTextAsync(Stream imageToAnalyze)
        {
            BatchReadFileInStreamHeaders textHeaders = await _computerVisionClient.BatchReadFileInStreamAsync(imageToAnalyze);

            string operationLocation = textHeaders.OperationLocation;
            string operationId       = operationLocation.Substring(operationLocation.Length - NumberOfCharsInOperationId);

            ReadOperationResult result = await _computerVisionClient.GetReadOperationResultAsync(operationId);

            int i          = 0;
            int maxRetries = 10;

            while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries)
            {
                await Task.Delay(1000);

                result = await _computerVisionClient.GetReadOperationResultAsync(operationId);
            }

            IList <TextRecognitionResult> recResults = result.RecognitionResults;

            return(recResults);
        }
Ejemplo n.º 20
0
        public void BatchReadFileInStreamTest()
        {
            using (MockContext context = MockContext.Start(this.GetType().FullName))
            {
                HttpMockServer.Initialize(this.GetType().FullName, "BatchReadFileInStreamTest");

                using (IComputerVisionClient client = GetComputerVisionClient(HttpMockServer.CreateInstance()))
                    using (FileStream stream = new FileStream(GetTestImagePath("whiteboard.jpg"), FileMode.Open))
                    {
                        BatchReadFileInStreamHeaders headers = client.BatchReadFileInStreamAsync(stream).Result;

                        Assert.NotNull(headers.OperationLocation);

                        ReadOperationResult readOperationResult = GetRecognitionResultWithPolling(client, headers.OperationLocation);

                        Assert.NotNull(readOperationResult);
                        Assert.Equal(TextOperationStatusCodes.Succeeded, readOperationResult.Status);

                        Assert.NotNull(readOperationResult.RecognitionResults);
                        Assert.Equal(1, readOperationResult.RecognitionResults.Count);

                        var recognitionResult = readOperationResult.RecognitionResults[0];

                        Assert.Equal(1, recognitionResult.Page);
                        Assert.Equal(1000, recognitionResult.Width);
                        Assert.Equal(664, recognitionResult.Height);
                        Assert.Equal(TextRecognitionResultDimensionUnit.Pixel, recognitionResult.Unit);

                        Assert.Equal(
                            new string[] { "you must be the change", "you want to see in the world!" }.OrderBy(t => t),
                            recognitionResult.Lines.Select(line => line.Text).OrderBy(t => t));
                        Assert.Equal(2, recognitionResult.Lines.Count);
                        Assert.Equal(5, recognitionResult.Lines[0].Words.Count);
                        Assert.Equal(7, recognitionResult.Lines[1].Words.Count);
                    }
            }
        }