public static void Run() { // ExStart:WorkingWithDifferentLanguages // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set the Image property by loading the image from file path location or an instance of Stream ocrEngine.Image = ImageStream.FromFile(dataDir + "SpanishOCR.bmp"); // Clear the default language (English) ocrEngine.LanguageContainer.Clear(); // Load the resources of the language from file path location or an instance of Stream ocrEngine.LanguageContainer.AddLanguage(LanguageFactory.Load(dataDir + "Aspose.OCR.Spanish.Resources.zip")); // Process the image if (ocrEngine.Process()) { // Display the recognized text Console.WriteLine(ocrEngine.Text); } // ExEnd:WorkingWithDifferentLanguages }
public async Task <string> Run() { foreach (string argument in arguments) { if (!System.IO.File.Exists(argument)) { continue; } System.IO.FileInfo info = new System.IO.FileInfo(argument); if (!info.Exists) { continue; } StorageFile file = await StorageFile.GetFileFromPathAsync(info.FullName); IRandomAccessStreamWithContentType stream = await file.OpenReadAsync(); var decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap image = await decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied); OcrEngine engine = OcrEngine.TryCreateFromUserProfileLanguages(); OcrResult result = await engine.RecognizeAsync(image); Console.WriteLine(result.Text); return(result.Text); } return(null); }
public static async Task <OcrResult?> GetOcrResultFromRegion(Rectangle region) { Language?selectedLanguage = GetOCRLanguage(); if (selectedLanguage == null) { return(null); } Bitmap bmp = new(region.Width, region.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); g.CopyFromScreen(region.Left, region.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy); OcrResult?ocrResult; await using (MemoryStream memory = new()) { bmp.Save(memory, ImageFormat.Bmp); memory.Position = 0; BitmapDecoder bmpDecoder = await BitmapDecoder.CreateAsync(memory.AsRandomAccessStream()); SoftwareBitmap softwareBmp = await bmpDecoder.GetSoftwareBitmapAsync(); OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(selectedLanguage); ocrResult = await ocrEngine.RecognizeAsync(softwareBmp); } return(ocrResult); }
public static void Run() { // ExStart:GetLocationAndSizeExample // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); // Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); // Retrieve an array of recognized text by parts IRecognizedPartInfo[] text = ocrEngine.Text.PartsInfo; // Iterate over the text parts foreach (var recognizedPartInfo in text) { var symbol = (IRecognizedTextPartInfo)recognizedPartInfo; // Display the part information Console.WriteLine("Symbol:" + symbol.Text); // Get the rectangle sourronding the symbol Rectangle box = symbol.Box; // Display the rectangle location on the image canvas Console.WriteLine("Box Location:" + box.Location); // Display the rectangle dimensions Console.WriteLine("Box Size:" + box.Size); } } // ExEnd:GetLocationAndSizeExample }
public static void Run() { // ExStart:OCROnMultipageTIFF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR() + "SampleTiff.tiff"; // Create an initialize an instance of OcrEngine OcrEngine engine = new OcrEngine(); // Set the OcrEngine.Image property by loading a multipage TIFF from disk, memory or URL engine.Image = ImageStream.FromFile(dataDir); // Set OcrEngine.ProcessAllPages to true in order to process all pages of TIFF in single run engine.ProcessAllPages = true; // Call OcrEngine.Process method to perform OCR operation if (engine.Process()) { // Retrieve the list of Pages Page[] pages = engine.Pages; // Iterate over the list of Pages foreach (Page page in pages) { // Display the recognized text from each Page Console.WriteLine(page.PageText); } } // ExStart:OCROnMultipageTIFF }
public static IServiceCollection AddCoreServices(this IServiceCollection services, CancellationToken token, Type replayProvider) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddEnvironmentVariables("HEROES_REPLAY_") .Build(); var focusCalculator = typeof(IFocusCalculator); var calculators = focusCalculator.Assembly.GetTypes().Where(type => type.IsClass && focusCalculator.IsAssignableFrom(type)); foreach (var calculatorType in calculators) { services.AddSingleton(focusCalculator, calculatorType); } var settings = configuration.Get <Settings>(); return(services .AddLogging(builder => builder.AddConfiguration(configuration.GetSection("Logging")).AddConsole().AddEventLog(config => config.SourceName = "Heroes Replay")) .AddSingleton <IConfiguration>(configuration) .AddSingleton(settings) .AddSingleton(new CancellationTokenProvider(token)) .AddSingleton(OcrEngine.TryCreateFromUserProfileLanguages()) .AddSingleton(typeof(CaptureStrategy), settings.Capture.Method switch { CaptureMethod.None => typeof(CaptureStub), CaptureMethod.BitBlt => typeof(CaptureBitBlt), CaptureMethod.CopyFromScreen => typeof(CaptureFromScreen), _ => typeof(CaptureBitBlt) })
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR(); // Create an initialize an instance of OcrEngine OcrEngine engine = new OcrEngine(); // Set the OcrEngine.Image property by loading an image from disk, memory or URL engine.Image = ImageStream.FromFile(dataDir + "Sample.bmp"); // Create text recognition block by supplying X,Y coordinates and Width,Height values IRecognitionBlock block = RecognitionBlock.CreateTextBlock(6, 9, 120, 129); // Set the Whitelist property by specifying a new block whitelist block.Whitelist = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // YOU CAN ADD MORE TEXT BLOCK AND SET WHITE LISTS. // Set different configurations and add recognition block(s) engine.Config.ClearRecognitionBlocks(); engine.Config.AddRecognitionBlock(block); engine.Config.DetectTextRegions = false; // Call OcrEngine.Process method to perform OCR operation if (engine.Process()) { // Display the recognized text from each Page Console.WriteLine(engine.Text); } }
static async System.Threading.Tasks.Task Main(string[] args) { var loadResult = @".\lib_\loadResult.txt"; var language = new Language("ja"); if (!OcrEngine.IsLanguageSupported(language)) { File.WriteAllText(loadResult, "False"); throw new Exception($"{ language.LanguageTag } is not supported in this system."); } else { File.WriteAllText(loadResult, "True"); } var inputPath = @".\lib_\input.jpg"; var outputPath = @".\lib_\output.txt"; if (File.Exists(inputPath)) { var stream = File.OpenRead(inputPath); var decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); var bitmap = await decoder.GetSoftwareBitmapAsync(); var engine = OcrEngine.TryCreateFromLanguage(language); var ocrResult = await engine.RecognizeAsync(bitmap).AsTask(); Console.WriteLine(ocrResult.Text); File.WriteAllText(outputPath, ocrResult.Text); } }
public static void Run() { // ExStart:ExtractingText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Clear notifier list ocrEngine.ClearNotifies(); // Clear recognition blocks ocrEngine.Config.ClearRecognitionBlocks(); // Add 2 rectangles to user defined recognition blocks ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(27, 63, 34, 38)); // Detecting A ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(209, 111, 28, 34)); // Detecting 6 // Ignore everything else on the image other than the user defined recognition blocks ocrEngine.Config.DetectTextRegions = false; // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "sampleocr.bmp"); // Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); } // ExEnd:ExtractingText }
public static void Run() { // ExStart:ExtractingText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Clear notifier list ocrEngine.ClearNotifies(); // Clear recognition blocks ocrEngine.Config.ClearRecognitionBlocks(); // Add 2 rectangles to user defined recognition blocks ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(27, 63, 34, 38)); // Detecting A ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(209, 111, 28, 34)); // Detecting 6 // Ignore everything else on the image other than the user defined recognition blocks ocrEngine.Config.DetectTextRegions = false; // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "sampleocr.bmp"); // Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); } // ExEnd:ExtractingText }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); //Get an instance of INotifier INotifier processorWord = NotifierFactory.WordNotifier(); //Write a delegate to handle the Elapsed event processorWord.Elapsed += delegate { //Display the recognized text on screen Console.WriteLine(processorWord.Text); }; // Add the word processor to the OcrEngine ocrEngine.AddNotifier(processorWord); //Process the image ocrEngine.Process(); }
private void SelectOmniPageEngine() { if (_omniPage == null) { try { OmniPageLoader loader = new OmniPageLoader(); if (loader != null) { // try to create an OmniPage engine _omniPage = new OmniPageEngine(); InitializeEngine(_omniPage); } } catch (AtalasoftLicenseException ex) { LicenseCheckFailure("Using OmniPage OCR requires both an Atalasoft DotImage OCR License.", ex.Message); } catch (Exception err) { InfoBox(err.Message); } } if (_omniPage != null) { _engine = _omniPage; UpdateMenusForEngine(); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); setLanguageList(); bool hasCamera = await setCameraListAsync(); if (hasCamera) { await InitializeMediaCaptureAsync(); } return; #region local functions in OnNavigatedTo void setLanguageList() { // サポート言語の一覧を得る IReadOnlyList <Language> langList = OcrEngine.AvailableRecognizerLanguages; // コンボボックスにサポート言語の一覧を表示する this.LangComboBox.ItemsSource = langList; // 選択肢として表示するのはDisplayNameプロパティ(「日本語」など) this.LangComboBox.DisplayMemberPath = nameof(Windows.Globalization.Language.DisplayName); // SelectedValueとしてLanguageTagプロパティを使う(「ja」など) this.LangComboBox.SelectedValuePath = nameof(Windows.Globalization.Language.LanguageTag); // ユーザープロファイルに基いてOCRエンジンを作ってみる var ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); // その認識言語をコンボボックスで選択状態にする this.LangComboBox.SelectedValue = ocrEngine.RecognizerLanguage.LanguageTag; } async Task <bool> setCameraListAsync() { var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); if (devices.Count == 0) { HideCameraUI(); return(false); } setupCameraComboBox(devices); return(true); void setupCameraComboBox(IReadOnlyList <DeviceInformation> deviceList) { this.CameraComboBox.ItemsSource = deviceList; this.CameraComboBox.DisplayMemberPath = nameof(DeviceInformation.Name); this.CameraComboBox.SelectedValuePath = nameof(DeviceInformation.Id); this.CameraComboBox.SelectedIndex = 0; } } #endregion } // OnNavigatedTo
/// <summary> /// Microsoft OCR の呼び出し /// </summary> /// <param name="bitmap"></param> /// <returns></returns> public async Task <OcrResult> detect(SoftwareBitmap bitmap) { var ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); var ocrResult = await ocrEngine.RecognizeAsync(bitmap); return(ocrResult); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); //Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); //Retrieve an array of recognized text by parts IRecognizedPartInfo[] text = ocrEngine.Text.PartsInfo; //Iterate over the text parts foreach (IRecognizedTextPartInfo symbol in text) { //Display the part information Console.WriteLine("Symbol:" + symbol.Text); //Get the rectangle sourronding the symbol Rectangle box = symbol.Box; //Display the rectangle location on the image canvas Console.WriteLine("Box Location:" + box.Location); //Display the rectangle dimensions Console.WriteLine("Box Size:" + box.Size); } } }
public Form1() { InitializeComponent(); var engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en-US")); //string filePath = TestData.GetFilePath("testimage.png"); var file = Windows.Storage.StorageFile.GetFileFromPathAsync(@"C:\Cases\3333.jpg").GetAwaiter().GetResult(); var stream = file.OpenAsync(Windows.Storage.FileAccessMode.Read).GetAwaiter().GetResult(); var decoder = Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream).GetAwaiter().GetResult(); var softwareBitmap = decoder.GetSoftwareBitmapAsync().GetAwaiter().GetResult(); var ocrResult = engine.RecognizeAsync(softwareBitmap).GetAwaiter().GetResult(); List <OcrLine> lines = ocrResult.Lines.ToList(); StringBuilder sb = new StringBuilder(); foreach (var line in lines) { sb.Append(line.Text); sb.Append("\n\n"); } Console.WriteLine(sb.ToString()); //CreateDocument(words); }
public async void Init(OcrEngine ocrEngine, StorageFile file, CoreInputDeviceTypes inputTypesForMarking = CoreInputDeviceTypes.Mouse, Image myDebugImage = null) { if (ocrEngine == null) { this.OCREngine = OcrEngine.TryCreateFromLanguage(new Language("en")); } else { this.OCREngine = ocrEngine; } if (inputTypesForMarking == CoreInputDeviceTypes.None) { InputTypesForMarking = CoreInputDeviceTypes.Mouse; } else { InputTypesForMarking = inputTypesForMarking; } MyImageSourcePath = file.Path; DebugCropImage = myDebugImage; BitmapImage bim = new BitmapImage(new Uri(MyImageSourcePath)); bim.SetSource(await file.OpenReadAsync()); MyImage.Source = bim; MyInkCanvas.InkPresenter.InputDeviceTypes = InputTypesForMarking; }
public static async Task <string> ExtractTextAsync(Image img, string lang) { MemoryStream memoryStream = new MemoryStream(); InMemoryRandomAccessStream randStream = new InMemoryRandomAccessStream(); string result = ""; try { img.Save(memoryStream, ImageFormat.Bmp); await randStream.WriteAsync(memoryStream.ToArray().AsBuffer()); if (!OcrEngine.IsLanguageSupported(new Language(lang))) { Console.Write("This language is not supported!"); } OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(new Language(lang)); if (ocrEngine == null) { ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); } var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(randStream); OcrResult ocrResult = await ocrEngine.RecognizeAsync(await decoder.GetSoftwareBitmapAsync()); result = ocrResult.Text; return(result); } finally { memoryStream.Dispose(); randStream.Dispose(); GC.Collect(0); } }
public static void Run() { // ExStart:ExtractPreprocessedImages // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir + "sample1.jpg"); ocrEngine.Config.SavePreprocessedImages = true; // Process the image if (ocrEngine.Process()) { // Save binarized,filtered image on disc ocrEngine.PreprocessedImages.BinarizedImage.Save(dataDir + "BinarizedImage_out.png", System.Drawing.Imaging.ImageFormat.Png); ocrEngine.PreprocessedImages.FilteredImage.Save(dataDir + "FilteredImage_out.png", System.Drawing.Imaging.ImageFormat.Png); // Save image after removing non-textual fragments, skew correction and textual block detection ocrEngine.PreprocessedImages.NonTextRemovedImage.Save(dataDir + "NonTextRemovedImage_out.png", System.Drawing.Imaging.ImageFormat.Png); ocrEngine.PreprocessedImages.RotatedImage.Save(dataDir + "RotatedImage_out.png", System.Drawing.Imaging.ImageFormat.Png); ocrEngine.PreprocessedImages.TextBlocksImage.Save(dataDir + "TextBlocksImage_out.png", System.Drawing.Imaging.ImageFormat.Png); } // ExEnd:ExtractPreprocessedImages }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Clear notifier list ocrEngine.ClearNotifies(); //Clear recognition blocks ocrEngine.Config.ClearRecognitionBlocks(); //Add 2 rectangles to user defined recognition blocks ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(27, 63, 34, 38)); //Detecting A ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(209, 111, 28, 34)); //Detecting 6 //Ignore everything else on the image other than the user defined recognition blocks ocrEngine.Config.DetectTextRegions = false; //Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "sampleocr.bmp"); //Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); } }
public static void Run() { // ExStart:ReadPartInformation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); // Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); // Retrieve an array of recognized text by parts IRecognizedPartInfo[] text = ocrEngine.Text.PartsInfo; // Iterate over the text parts foreach (IRecognizedTextPartInfo symbol in text) { // Display part intomation Console.WriteLine("Text : " + symbol.Text); Console.WriteLine("isItalic : " + symbol.Italic); Console.WriteLine("Language : " + symbol.Language); } } // ExStart:ReadPartInformation }
private async void UserOption() { if (BitmapLang.ocrEngine != null && BitmapLang.softwareBitmap != null) { //Aparat ocrEngine = BitmapLang.ocrEngine; bitmap = BitmapLang.softwareBitmap; var imgSource = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight); bitmap.CopyToBuffer(imgSource.PixelBuffer); PreviewImage.Source = imgSource; OCR(); } if (BitmapLang.ocrEngine != null && BitmapLang.softwareBitmap == null) { //Zdjecie ocrEngine = BitmapLang.ocrEngine; PhotoPicker(); } if (BitmapLang.ocrEngine == null && BitmapLang.softwareBitmap == null) { Windows.UI.Popups.MessageDialog msg = new Windows.UI.Popups.MessageDialog("Coś poszło źle, spróbuj ponownie. :("); await msg.ShowAsync(); this.Frame.Navigate(typeof(MainPage)); } }
public static void Run() { // ExStart:DetectingTextBlocks // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); // Remove non-textual blocks ocrEngine.Config.RemoveNonText = true; // Run recognition process if (ocrEngine.Process()) { // Display text block locations foreach (IRecognizedPartInfo part in ocrEngine.Text.PartsInfo) { Console.WriteLine(part.Box); } } // ExEnd:DetectingTextBlocks }
public MainPage() { this.InitializeComponent(); Language ocrLanguage = new Language("en"); ocrEngine = OcrEngine.TryCreateFromLanguage(ocrLanguage); }
public async Task <List <string> > RecognizeAsync(List <StorageFile> pickedFiles) { List <string> results = new List <string>(); // OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en-US")); OcrEngine engine = OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("pl")); int i = 0; foreach (StorageFile file in pickedFiles) { Informator.Log(" OCR - " + i + " out of " + pickedFiles.Count); StringBuilder text = new StringBuilder(); var stream = await file.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync(); OcrResult ocrResult = await engine.RecognizeAsync(softwareBitmap); foreach (OcrLine line in ocrResult.Lines) { text.Append(line.Text + "\n"); } results.Add(text.ToString()); i++; } return(results); }
private async void ClickBottonBrowse(object sender, RoutedEventArgs e) { FileOpenPicker fileOpenPicker = new FileOpenPicker(); fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; fileOpenPicker.FileTypeFilter.Add(".jpg"); fileOpenPicker.ViewMode = PickerViewMode.Thumbnail; var inputFile = await fileOpenPicker.PickSingleFileAsync(); if (inputFile == null) { return; } SoftwareBitmap bitmap; using (IRandomAccessStream stream = await inputFile.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); bitmap = await decoder.GetSoftwareBitmapAsync(); } Language ocrLanguage = new Language("en"); OcrEngine ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); OcrResult ocrResult = await ocrEngine.RecognizeAsync(bitmap); string result = ocrResult.Text; Frame.Navigate(typeof(SelectTextAppoinmentPage), result); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); //Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); // Retrieve an array of recognized text by parts IRecognizedPartInfo[] text = ocrEngine.Text.PartsInfo; // Iterate over the text parts foreach (IRecognizedTextPartInfo symbol in text) { // Display part intomation Console.WriteLine("Text : " + symbol.Text); Console.WriteLine("isItalic : " + symbol.Italic); Console.WriteLine("isUnderline : " + symbol.Underline); Console.WriteLine("isBold : " + symbol.Bold); Console.WriteLine("FontSize : " + symbol.FontSize); Console.WriteLine("Language : " + symbol.Language); } } }
public static void Run() { // ExStart:DetectingTextBlocks // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); // Remove non-textual blocks ocrEngine.Config.RemoveNonText = true; // Run recognition process if (ocrEngine.Process()) { // Display text block locations foreach (IRecognizedPartInfo part in ocrEngine.Text.PartsInfo) { Console.WriteLine(part.Box); } } // ExEnd:DetectingTextBlocks }
private async Task RunOcrAndTranslate() { SoftwareBitmap softwareBitmap = captureImage.Tag as SoftwareBitmap; OcrEngine ocrEngine = OcrEngine.TryCreateFromLanguage(sourceLanguageComboBox.SelectedItem as Windows.Globalization.Language); var ocrResult = await ocrEngine.RecognizeAsync(softwareBitmap); String resultString = ocrResult.Text; if (ocrEngine.RecognizerLanguage.LanguageTag == "ja") { resultString = resultString.Replace(" ", ""); } var sourceLanguage = sourceLanguageComboBox.SelectedItem as Windows.Globalization.Language; String sourceLanguageTag = sourceLanguage.LanguageTag; if (sourceLanguageTag.StartsWith("en")) { sourceLanguageTag = "en"; } String destinationLanguageTag = GoogleLanguageTags[destinationLanguageComboBox.SelectedItem as String]; String textURL = HttpUtility.UrlEncode(resultString); String navigateURL = $"https://translate.google.com/m/translate#{sourceLanguageTag}/{destinationLanguageTag}/{textURL}"; WebBrowserExtensions.LoadHtml(browser, ""); browser.Address = navigateURL; }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); //Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); // Retrieve an array of recognized text by parts IRecognizedPartInfo[] text = ocrEngine.Text.PartsInfo; // Iterate over the text parts foreach (IRecognizedTextPartInfo symbol in text) { // Display part intomation Console.WriteLine("Text : " + symbol.Text); Console.WriteLine("isItalic : " + symbol.Italic); Console.WriteLine("isUnderline : " + symbol.Underline); Console.WriteLine("isBold : " + symbol.Bold); Console.WriteLine("FontSize : " + symbol.FontSize); Console.WriteLine("Language : " + symbol.Language); } } }
private async void GetOCRAsync(SoftwareBitmap inputBitmap) { if (_ocrRunning) { return; } _ocrRunning = true; SoftwareBitmap localBitmap = SoftwareBitmap.Copy(inputBitmap); var ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); var recognizeAsync = await ocrEngine.RecognizeAsync(localBitmap); var str = new StringBuilder(); foreach (var ocrLine in recognizeAsync.Lines) { str.AppendLine(ocrLine.Text); } var readText = str.ToString(); if (readText != "") { WinOCRResult = readText; } _ocrRunning = false; return; }
private static async Task <int> GetNewKDA(int previousKDA) { string fileName = "X:\\Programming\\C#\\LoLTaser\\Captured Pictures\\Capture.png"; await GetScreen(fileName); // Creates the specified file (image) try { //Do the thing Language language = new Language("en"); var stream = File.OpenRead(fileName); var decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()); var bitmap = await decoder.GetSoftwareBitmapAsync(); var engine = OcrEngine.TryCreateFromLanguage(language); var ocrResult = await engine.RecognizeAsync(bitmap).AsTask(); string r = SplitStart('/', ocrResult.Text); r = SplitEnd('/', r); stream.Close(); File.Delete(fileName); int result = Convert.ToInt32(r); return(result); } catch (Exception err) { Console.WriteLine(err.Message); File.Delete(fileName); } return(previousKDA); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); //Get an instance of INotifier INotifier processorWord = NotifierFactory.WordNotifier(); //Write a delegate to handle the Elapsed event processorWord.Elapsed += delegate { //Display the recognized text on screen Console.WriteLine(processorWord.Text); }; // Add the word processor to the OcrEngine ocrEngine.AddNotifier(processorWord); //Process the image ocrEngine.Process(); }
public async Task <List <string> > ProcessImage(string image) { List <string> result = new List <string>(); BitmapDecoder bmpDecoder; SoftwareBitmap softwareBmp; OcrEngine ocrEngine; OcrResult ocrResult; try { await using (var fileStream = File.OpenRead(image)) { bmpDecoder = await BitmapDecoder.CreateAsync(fileStream.AsRandomAccessStream()); softwareBmp = await bmpDecoder.GetSoftwareBitmapAsync(); ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); ocrResult = await ocrEngine.RecognizeAsync(softwareBmp); foreach (var line in ocrResult.Lines) { result.Add(line.Text); } } } catch (Exception ex) { throw (ex); } return(result); }
public async Task ExtractWords() { OcrEngine ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); if (ocrEngine != null) { foreach (var pdfPage in PdfPages) { if (pdfPage.Image.PixelWidth > OcrEngine.MaxImageDimension || pdfPage.Image.PixelHeight > OcrEngine.MaxImageDimension) { return; } var ocrResult = await ocrEngine.RecognizeAsync(pdfPage.Image); foreach (var line in ocrResult.Lines) { foreach (var word in line.Words) { pdfPage.Words.Add(word); } } } } }
public static void Run() { // ExStart:GettingNotification // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); // Get an instance of INotifier INotifier processorWord = NotifierFactory.WordNotifier(); //Write a delegate to handle the Elapsed event processorWord.Elapsed += delegate { // Display the recognized text on screen Console.WriteLine(processorWord.Text); }; // Add the word processor to the OcrEngine ocrEngine.AddNotifier(processorWord); // Process the image ocrEngine.Process(); // ExEnd:GettingNotification }
public static void Run() { // ExStart:ReadPartInformation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); // Run recognition process if (ocrEngine.Process()) { Console.WriteLine(ocrEngine.Text); // Retrieve an array of recognized text by parts IRecognizedPartInfo[] text = ocrEngine.Text.PartsInfo; // Iterate over the text parts foreach (IRecognizedTextPartInfo symbol in text) { // Display part intomation Console.WriteLine("Text : " + symbol.Text); Console.WriteLine("isItalic : " + symbol.Italic); Console.WriteLine("Language : " + symbol.Language); } } // ExStart:ReadPartInformation }
public static void Run() { // ExStart:GettingNotification // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); // Get an instance of INotifier INotifier processorWord = NotifierFactory.WordNotifier(); //Write a delegate to handle the Elapsed event processorWord.Elapsed += delegate { // Display the recognized text on screen Console.WriteLine(processorWord.Text); }; // Add the word processor to the OcrEngine ocrEngine.AddNotifier(processorWord); // Process the image ocrEngine.Process(); // ExEnd:GettingNotification }
private async void ClickButtonMakePhoto(object sender, RoutedEventArgs e) { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg; StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (photo == null) { return; } IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read); BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync(); Language ocrLanguage = new Language("en"); OcrEngine ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages(); OcrResult ocrResult = await ocrEngine.RecognizeAsync(bitmap); string result = ocrResult.Text; Frame.Navigate(typeof(SelectTextAppoinmentPage), result); }
public string OcrImage(string img) { string res = String.Empty; List <string> wrds = new List <string>(); try { if (File.Exists(img)) { using (Image <Bgr, byte> i = new Image <Bgr, byte>(img)) { if (OcrEngine != null) { OcrEngine.Recognize(i); res = OcrEngine.GetText().TrimEnd(); wrds.AddRange(res.Split(new string[] { " ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList()); this.Words = wrds?.ToArray(); } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return(res); }
private static async Task <string> RunOcr(MemoryStream memoryStream) { if (memoryStream == null || memoryStream.Length == 0) { return(""); } using (var memoryRandomAccessStream = new InMemoryRandomAccessStream()) { await memoryRandomAccessStream.WriteAsync(memoryStream.ToArray().AsBuffer()); OcrEngine engine = null; if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["LanguageCode"])) { engine = OcrEngine.TryCreateFromLanguage(new Language(ConfigurationManager.AppSettings["LanguageCode"])); } if (engine == null) { engine = OcrEngine.TryCreateFromUserProfileLanguages(); } var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryRandomAccessStream); OcrResult result = await engine.RecognizeAsync(await decoder.GetSoftwareBitmapAsync()); return(result.Text); } }
public MainPage() { InitializeComponent(); Loaded += MainPage_LoadedAsync; // Init OCR engine with English language. _ocrEngine = OcrEngine.TryCreateFromLanguage(new Language("en")); }
private static async Task<OcrResult> Recognize(string fileName, OcrLanguage language) { var ocrEngine = new OcrEngine(language); using (var stream = File.OpenRead(fileName)) { var winRtStream = stream.AsRandomAccessStream(); var decoder = await BitmapDecoder.CreateAsync(winRtStream); var bitmap = await decoder.GetPixelDataAsync(); return await ocrEngine.RecognizeAsync(decoder.PixelHeight, decoder.PixelWidth, bitmap.DetachPixelData()); } }
public static void Run() { // ExStart:AddingUserDefinedRecognitionBlocks // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Clear notifier list ocrEngine.ClearNotifies(); // Clear recognition blocks ocrEngine.Config.ClearRecognitionBlocks(); // Add 3 rectangle blocks to user defined recognition blocks ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(0, 10, 20, 40)); ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(0, 4, 5, 6)); ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(0, 5, 5, 6)); // Ignore everything else on the image other than the user defined recognition blocks ocrEngine.Config.DetectTextRegions = false; // Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir + "sample1.jpg"); // Run recognition process if (ocrEngine.Process()) { // Retrieve user defined blocks that determines the paye layout var blocks = ocrEngine.Config.RecognitionBlocks; // Loop over the list of blocks foreach (var block in blocks) { // Display if block is set to be recognized Console.WriteLine(block.ToRecognize); // Check if block has recognition data if (block.RecognitionData == null) { Console.WriteLine("Null{0}", Environment.NewLine); continue; } // Display dimension & size of rectangle that defines the recognition block Console.WriteLine("Block: {0}", block.Rectangle); if (block.RecognitionData is IRecognizedTextPartInfo) { // Display the recognition results IRecognizedTextPartInfo textPartInfo = (IRecognizedTextPartInfo)block.RecognitionData; Console.WriteLine("Text: {0}{1}", textPartInfo.Text, Environment.NewLine); } } } // ExEnd:AddingUserDefinedRecognitionBlocks }
public BasicPage1() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; this.navigationHelper.SaveState += this.NavigationHelper_SaveState; this.ocrEngine = new OcrEngine(OcrLanguage.ChineseSimplified); TextOverlay.Children.Clear(); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Clear notifier list ocrEngine.ClearNotifies(); //Clear recognition blocks ocrEngine.Config.ClearRecognitionBlocks(); //Add 3 rectangle blocks to user defined recognition blocks ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(0, 60, 700, 50)); ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreateTextBlock(0, 10, 700, 50)); ocrEngine.Config.AddRecognitionBlock(RecognitionBlock.CreatePictureBlock(0, 10, 700, 50)); //Ignore everything else on the image other than the user defined recognition blocks ocrEngine.Config.DetectTextRegions = false; //Set Image property by loading an image from file path ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); //Run recognition process if (ocrEngine.Process()) { //Retrieve user defined blocks that determines the paye layout var blocks = ocrEngine.Config.RecognitionBlocks; //Loop over the list of blocks foreach (var block in blocks) { //Display if block is set to be recognized Console.WriteLine(block.ToRecognize); //Check if block has recognition data if (block.RecognitionData == null) { Console.WriteLine("Null{0}", Environment.NewLine); continue; } //Display dimension & size of rectangle that defines the recognition block Console.WriteLine("Block: {0}", block.Rectangle); if (block.RecognitionData is IRecognizedTextPartInfo) { //Display the recognition results IRecognizedTextPartInfo textPartInfo = (IRecognizedTextPartInfo)block.RecognitionData; Console.WriteLine("Text: {0}{1}", textPartInfo.Text, Environment.NewLine); } } } }
public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; ocrEngine = new OcrEngine(OcrLanguage.English); // Load all available languages from OcrLanguage enum in combo box. LanguageList.ItemsSource = Enum.GetNames(typeof(OcrLanguage)).OrderBy(name => name.ToString()); LanguageList.SelectedItem = ocrEngine.Language.ToString(); LanguageList.SelectionChanged += LanguageList_SelectionChanged; }
// Constructor public MainPage() { InitializeComponent(); ocrEngine = new OcrEngine(OcrLanguage.English); saveContactTask = new SaveContactTask(); saveContactTask.Completed += new EventHandler<SaveContactResult>(saveContactTask_Completed); saveContactTask.FirstName = "John"; saveContactTask.LastName = "Doe"; saveContactTask.MobilePhone = "2065550123"; saveContactTask.Show(); }
public ExtractText() { rootPage = MainPage.Current; this.InitializeComponent(); ocrEngine = new OcrEngine(OcrLanguage.Turkish); // Load all available languages from OcrLanguage enum in combo box. LanguageList.ItemsSource = Enum.GetNames(typeof(OcrLanguage)).OrderBy(name => name.ToString()); LanguageList.SelectedItem = ocrEngine.Language.ToString(); LanguageList.SelectionChanged += LanguageList_SelectionChanged; }
public async void TestOcr(string fileName) { var ocrEngine = new OcrEngine(OcrLanguage.English); using (var stream = File.OpenRead(fileName)) { var winRtStream = stream.AsRandomAccessStream(); var decoder = await BitmapDecoder.CreateAsync(winRtStream); var bitmap = await decoder.GetPixelDataAsync(); var ocrResult = await ocrEngine.RecognizeAsync(decoder.PixelHeight, decoder.PixelWidth, bitmap.DetachPixelData()); var text = string.Join(Environment.NewLine, ocrResult.Lines); Trace.WriteLine(text); } }
public static void Run() { // ExStart:GetTextPartHierarchy // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); // Process the image if (ocrEngine.Process()) { // Retrieve the first block of the recognized text part IRecognizedTextPartInfo firstBlock = (ocrEngine.Text.PartsInfo[0] as IRecognizedTextPartInfo); // Get the children of the first block that will the the lines in the block if (firstBlock != null) { IRecognizedPartInfo[] linesOfFirstBlock = firstBlock.Children; // Retrieve the fist line from the collection of lines IRecognizedTextPartInfo firstLine = (linesOfFirstBlock[0] as IRecognizedTextPartInfo); // Display the level of line if (firstLine != null) { Console.WriteLine(firstLine.Level); // Retrieve the fist word from the collection of words IRecognizedTextPartInfo firstWord = (firstLine.Children[0] as IRecognizedTextPartInfo); // Display the level of word Console.WriteLine(firstWord.Level); // Retrieve the fist character from the collection of characters IRecognizedTextPartInfo firstCharacter = (firstWord.Children[0] as IRecognizedTextPartInfo); // Display the level of character Console.WriteLine(firstCharacter.Level); } } } // ExEnd:GetTextPartHierarchy }
public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; try { ocrEngine = new OcrEngine(OcrLanguage.English); } catch (Exception ex) { new Windows.UI.Popups.MessageDialog(ex.Message).ShowAsync(); } TextOverlay.Children.Clear(); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); //Process the image if (ocrEngine.Process()) { //Display the recognized text Console.WriteLine(ocrEngine.Text); } }
public static void Run() { // ExStart:PerformOCROnImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OMR(); // Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); // Set the Image property by loading the image from file path location or an instance of MemoryStream ocrEngine.Image = ImageStream.FromFile(dataDir + "Sampleocr.bmp"); // Process the image if (ocrEngine.Process()) { // Display the recognized text Console.WriteLine(ocrEngine.Text); } // ExEnd:PerformOCROnImage }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Initialize an instance of OcrEngine OcrEngine ocrEngine = new OcrEngine(); //Retrieve the OcrConfig of the OcrEngine object OCRConfig ocrConfig = ocrEngine.Config; //Set the Whitelist property to recognize numbers only ocrConfig.Whitelist = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }; //Set the Image property of OcrEngine object ocrEngine.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); //Call the Process method to retrieve the results ocrEngine.Process(); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.OCR.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create an instance of OcrEngine class OcrEngine ocr = new OcrEngine(); //Set the Image property of OcrEngine by reading an image file ocr.Image = ImageStream.FromFile(dataDir+ "Sampleocr.bmp"); //Set the RemoveNonText to true ocr.Config.RemoveNonText = true; //Perform OCR operation if (ocr.Process()) { //Display results Console.WriteLine(ocr.Text); } }
public static void Run() { // ExStart:PreprocesImagesFromOCROperation // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR() + "Sampleocr.bmp"; // Initialize an instance of OcrEngine. OcrEngine ocr = new OcrEngine(); // Set the Image property by loading the image from file path location. ocr.Image = ImageStream.FromFile(dataDir); // Set the SavePreprocessedImages property to false. ocr.Config.SavePreprocessedImages = true; if (ocr.Process()) { // Do processing } // ExEnd:PreprocesImagesFromOCROperation }
public static void Run() { // ExStart:AutomaticallyCorrectTheSpellings // The path to the documents directory. string dataDir = RunExamples.GetDataDir_OCR(); // Create an instance of OcrEngine class OcrEngine ocr = new OcrEngine(); // Set the Image property of OcrEngine by reading an image file ocr.Image = ImageStream.FromFile(dataDir + "sampleocr_spell.bmp"); // Set the DoSpellingCorrection to true ocr.Config.DoSpellingCorrection = true; // Perform OCR operation if (ocr.Process()) { // Display results Console.WriteLine(ocr.Text); } // ExEnd:AutomaticallyCorrectTheSpellings }