Beispiel #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            //抓取key
            var VisionApiKey = textBoxkey.Text.Trim();
            //讀取圖檔
            var openDlg = new OpenFileDialog();

            //圖檔過濾類型
            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg|*.png|*.png";
            //沒選檔案
            if (openDlg.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            //取得選擇的檔案名稱
            string filePath = openDlg.FileName;

            //顯示原始圖片
            var FileStream = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);

            pictureBox1.Image = System.Drawing.Image.FromStream(FileStream);
            FileStream.Close();

            //OCR OcrResults
            OcrResults OcrResults;
            //建立VisionServiceClient
            var visionClient = new Microsoft.ProjectOxford.Vision.VisionServiceClient(VisionApiKey);

            using (var fs = new FileStream(filePath, FileMode.Open))
            {
                this.textBox.Text = "辨識中...";
                //以繁體中文辨識
                OcrResults        = visionClient.RecognizeTextAsync(fs, LanguageCodes.AutoDetect).Result;
                this.textBox.Text = "";
            }

            this.textBox.Text = "";
            //抓取每一區塊的辨識結果
            foreach (var Region in OcrResults.Regions)
            {
                //抓取每一行
                foreach (var line in Region.Lines)
                {
                    //抓取每一個字
                    foreach (var Word in line.Words)
                    {
                        //顯示辨識結果
                        this.textBox.Text += Word.Text;
                    }
                    //加換行
                    this.textBox.Text += "\n";
                }
            }
        }
Beispiel #2
0
        public static async Task Run([BlobTrigger("handwritten/{name}", Connection = "storage")] string content, string name, TraceWriter log)
        {
            var client = new Microsoft.ProjectOxford.Vision.VisionServiceClient(
                Environment.GetEnvironmentVariable("Computer-Vision-Ocp-Apim-Subscription-Key"),
                Environment.GetEnvironmentVariable("Computer-Vision-Api-Root"));

            HandwritingRecognitionOperationResult result = null;

            try
            {
                var operation = await client.CreateHandwritingRecognitionOperationAsync($"https://sqlsat707.blob.core.windows.net/handwritten/{name}");

                result = await client.GetHandwritingRecognitionOperationResultAsync(operation);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // now insert

            var connectionString = Environment.GetEnvironmentVariable("ConnectionString");

            using (var conn = new SqlConnection(connectionString))
            {
                conn.Open();

                var cmd = conn.CreateCommand();
                cmd.CommandText = "ImportTemperatureEvent";
                cmd.CommandType = CommandType.StoredProcedure;

                var deviceId    = cmd.Parameters.Add("@DeviceId", SqlDbType.NVarChar, 32);
                var timestamp   = cmd.Parameters.Add("@Timestamp", SqlDbType.DateTimeOffset);
                var temperature = cmd.Parameters.Add("@Temperature", SqlDbType.Float);

                foreach (var line in result.RecognitionResult.Lines)
                {
                    deviceId.Value    = line.Words[0].Text;
                    timestamp.Value   = DateTimeOffset.Now;
                    temperature.Value = double.Parse(line.Words[1].Text);
                    cmd.ExecuteNonQuery();
                }

                conn.Close();
            }
        }
Beispiel #3
0
        //this code is revised from http://studyhost.blogspot.com/2016/08/microsoft-cognitive-services-2-vision.html
        public static string GetOcrResults(string subscriptionKey, string apiRoot, byte[] filebody, string languageCodes)
        {
            string result = string.Empty;

            OcrResults OcrResults = default(OcrResults);

            //建立VisionServiceClient
            var visionClient = new Microsoft.ProjectOxford.Vision.VisionServiceClient(subscriptionKey, apiRoot);

            using (var ms = new MemoryStream(filebody, true))
            {
                //以繁體中文辨識
                //OcrResults = visionClient.RecognizeTextAsync(ms, LanguageCodes.AutoDetect).Result;
                OcrResults = visionClient.RecognizeTextAsync(ms, languageCodes).Result;
            }

            //抓取每一區塊的辨識結果
            foreach (var Region in OcrResults.Regions)
            {
                //抓取每一行
                foreach (var line_loopVariable in Region.Lines)
                {
                    var     line  = line_loopVariable;
                    dynamic aline = "";
                    //抓取每一個字
                    foreach (var Word_loopVariable in line.Words)
                    {
                        var Word = Word_loopVariable;
                        //顯示辨識結果
                        aline += Word.Text;
                    }

                    //加換行
                    result += aline + "\n";
                }
            }

            return(result);
        }
        async Task SelectImage(bool selectImageFromCamera)
        {
            MediaFile image;

            if (selectImageFromCamera)
            {
                image = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions()
                {
                    AllowCropping      = true,
                    DefaultCamera      = CameraDevice.Rear,
                    CompressionQuality = 60,
                });
            }
            else
            {
                image = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions()
                {
                    CompressionQuality = 60
                });
            }

            if (image == null)
            {
                return;
            }

            var dlg = DependencyService.Get <IShowInProgressDialog>();

            dlg.Show("Processing the image...");

            var spot = new FavouriteSpot()
            {
                Name            = "Spot",
                RatingOutOfFive = 5,
                AddedById       = App.AuthenticatedUser != null ? App.AuthenticatedUser.UserId : "",
            };

            var processingTask = GetCurrentDevicePositionAsync().ContinueWith((locationTask) =>
            {
                var location = locationTask.Result;

                spot.Latitude  = location.Latitude;
                spot.Longitude = location.Longitude;

                new Geocoder()
                .GetAddressesForPositionAsync(new Position(location.Latitude, location.Longitude))
                .ContinueWith((possibleAddressMatches) =>
                {
                    if (possibleAddressMatches.Result.Count() > 0)
                    {
                        spot.Address = possibleAddressMatches.Result.First();
                    }
                });
            });

            // Get the description of the image using Azure Cognative Services
            var visionClient = new Microsoft.ProjectOxford.Vision.VisionServiceClient(MobileServiceClientConstants.CognativeServicesVisionApiKey);

            var processImage = visionClient.DescribeAsync(image.GetStream()).ContinueWith((imageDescriptionTask) =>
            {
                // Process the Cognative Services Result
                var suggestedCategories = String.Join(", ", imageDescriptionTask.Result.Description.Tags);
                if (String.IsNullOrEmpty(spot.Category))
                {
                    spot.Category = suggestedCategories;
                }

                var suggestedDescription = imageDescriptionTask.Result.Description.Captions.First();
                if (suggestedDescription != null && String.IsNullOrEmpty(spot.Description))
                {
                    spot.Description = suggestedDescription.Text;
                }
            });

            // Wait for the operations to finish
            await Task.WhenAll(processingTask, processImage);

            dlg.Hide();

            // Show the edit page to let them save the record or not
            var editPage = new AddEditSpotPage(Data, spot, image);
            await Navigation.PushAsync(editPage);
        }
        //private BlobStorageAsync bs;

        public TextRecognitionService()
        {
            this._entityLinkClient = new Microsoft.ProjectOxford.EntityLinking.EntityLinkingServiceClient("8ac77dcbac034f239d735088bc51c51c", "https://westus.api.cognitive.microsoft.com");
            this._visionClient     = new Microsoft.ProjectOxford.Vision.VisionServiceClient(this._subscriptionKey, "https://westeurope.api.cognitive.microsoft.com/vision/v1.0");
            //this.bs = new BlobStorageAsync("XamarinHackaton", "DefaultEndpointsProtocol=https;AccountName=storagetestcognitive;AccountKey=PpjUl52zALHyVIWbLnIOb66shgzT5A9L3XKq7i6OK/xnaR1UFsBE+a8IDJJZGESCuy+mu2Vo5yyE499azRDytw==;EndpointSuffix=core.windows.net");
        }