public async void Sample1Jpg() { await _api.Init("eng"); using (var stream = LoadSample("sample1.jpg")) { var result = await _api.SetImage(stream); Assert.IsTrue(result); Assert.AreEqual("The quick brown fox\njumped over the 5\nlazy dogs!\n\n", _api.Text); var data = _api.Results(PageIteratorLevel.Block).ToList(); Assert.AreEqual(1, data.Count); Assert.AreEqual("The quick brown fox\njumped over the 5\nlazy dogs!\n\n", data [0].Text); data = _api.Results(PageIteratorLevel.Paragraph).ToList(); Assert.AreEqual(1, data.Count); Assert.AreEqual("The quick brown fox\njumped over the 5\nlazy dogs!\n\n", data [0].Text); data = _api.Results(PageIteratorLevel.Symbol).ToList(); Assert.AreEqual(39, data.Count); data = _api.Results(PageIteratorLevel.Textline).ToList(); Assert.AreEqual(3, data.Count); Assert.AreEqual("The quick brown fox\n", data [0].Text); Assert.AreEqual("jumped over the 5\n", data [1].Text); Assert.AreEqual("lazy dogs!\n\n", data [2].Text); Assert.AreEqual(new Rectangle(37, 233, 415, 89), data [2].Box); data = _api.Results(PageIteratorLevel.Word).ToList(); Assert.AreEqual(10, data.Count); } }
public static async Task <OCRData> Detect(IEditableImage Img, Context Ctx, int RectWidth, int RectHeight) { if (TesAPI == null) { TesAPI = new TesseractApi(Ctx, AssetsDeployment.OncePerInitialization); await TesAPI.Init("eng"); TesAPI.SetVariable("tessedit_char_whitelist", "0123456789kmKM"); } OCRData Result = new OCRData(); Result.PngOriginal = Img.ToPng(); // Crop the detection region Img = Img.Crop((Img.Width / 2) - (RectWidth / 2), (Img.Height / 2) - (RectHeight / 2), RectWidth, RectHeight).ToMonochrome(); Result.PngCropped = Img.ToPng(); using (MemoryStream PngImage = new MemoryStream()) { using (Bitmap Pic = ProcessImage((Bitmap)Img.GetNativeImage())) await Pic.CompressAsync(Bitmap.CompressFormat.Png, 100, PngImage); PngImage.Seek(0, SeekOrigin.Begin); await TesAPI.SetImage(PngImage); Result.PngProcessed = PngImage.ToArray(); } Result.Text = TesAPI.Text; return(Result); }
async partial void BtnCropping_Activated(UIBarButtonItem sender) { Console.WriteLine(imagenToCrop.Image.Orientation); Console.WriteLine(imagenToCrop.Image.AccessibilityFrame); var croppedCGImage = imagenToCrop.Image.CGImage.WithImageInRect(cropArea); var croppedImage = new UIImage(croppedCGImage); imagenToCrop.Image = croppedImage; ScrollViewFoto.ZoomScale = 1; TesseractApi api = new TesseractApi(); if (await api.Init("eng")) { if (await api.SetImage(imagenToCrop.Image.ToNSData())) { //lblTexto.Text = api.Text; var okAlertController = UIAlertController.Create("Encontrado:", api.Text, UIAlertControllerStyle.Alert); okAlertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); PresentViewController(okAlertController, true, null); } } }
async void ExtractText() { try { //await CrossMedia.Current.Initialize(); var xFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { SaveToAlbum = true, Directory = "Sample", Name = "test.jpg" }); //svar filepath = "/storage/emulated/0/Android/data/Tesseract.Android.Tesseract.Android/files/Pictures/Sample/test_3.jpg"; dialog = new ProgressDialog(this); dialog.SetMessage("Extracting Text"); dialog.Show(); await api.SetImage(xFile.GetStream()); dialog.Hide(); Android.App.AlertDialog.Builder builder1 = new Android.App.AlertDialog.Builder(this); builder1.SetMessage(api.Text); builder1.SetCancelable(true); Android.App.AlertDialog alert11 = builder1.Create(); alert11.Show(); string text = api.Text; } catch (Exception e) { } }
private async Task _GetText(Bitmap cropped) { if (!TesseractApi.Initialized) { await TesseractApi.Init("eng"); } TesseractApi.SetRectangle(new Tesseract.Rectangle((int)(cropped.Width * 0.24), 10, (int)(cropped.Width * 0.35), (int)(cropped.Height * 0.065))); TesseractApi.SetWhitelist("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); if (await TesseractApi.SetImage(File.OpenRead(Path.ChangeExtension(ImagePath, "card")))) { string s = TesseractApi.Text; if (Name == "" || Name == "NO TEXT DETECTED") { if (s != "") { if (s != "" && s[0].ToString() == s[0].ToString().ToLower()) { s = s.Substring(1, s.Length - 1); } TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; s = textInfo.ToTitleCase(s.ToLower()); } else { s = "NO TEXT DETECTED"; } Name = s; } } }
public async void TestWithoutDispiose () { ITesseractApi api = new TesseractApi (Android.App.Application.Context, AssetsDeployment.OncePerInitialization); await api.Init ("eng"); for (int i = 0; i < 20; i++) { using (var stream = TesseractApiRecogniseTest.LoadSample ("sample2.png")) { var result = await api.SetImage (stream); Assert.IsTrue (result); Assert.AreEqual ("ABCDE FGHI\nJKLHN OPQR\nSTUVVJXYZ", api.Text); } } api.Dispose (); }
public async void TestWithoutDispiose () { ITesseractApi api = new TesseractApi (); await api.Init ("eng"); for (int i = 0; i < 20; i++) { using (var stream = TesseractApiRecogniseTest.LoadSample ("sample2.png")) { var result = await api.SetImage (stream); Assert.IsTrue (result); Assert.AreEqual ("ABCDE FGHI\nJKLHN OPQR\nSTUVVJXYZ\n\n", api.Text); } } api.Dispose (); }
public async void TestWithoutDispiose() { ITesseractApi api = new TesseractApi(Android.App.Application.Context, AssetsDeployment.OncePerInitialization); await api.Init("eng"); for (int i = 0; i < 20; i++) { using (var stream = TesseractApiRecogniseTest.LoadSample("sample2.png")) { var result = await api.SetImage(stream); Assert.IsTrue(result); Assert.AreEqual("ABCDE FGHI\nJKLHN OPQR\nSTUVVJXYZ", api.Text); } } api.Dispose(); }
public async void TestWithoutDispiose() { ITesseractApi api = new TesseractApi(); await api.Init("eng"); for (int i = 0; i < 20; i++) { using (var stream = TesseractApiRecogniseTest.LoadSample("sample2.png")) { var result = await api.SetImage(stream); Assert.IsTrue(result); Assert.AreEqual("ABCDE FGHI\nJKLHN OPQR\nSTUVVJXYZ\n\n", api.Text); } } api.Dispose(); }
async Task <string> IORC.ORCWorkDashbordVehicle(byte[] data) { string textResult = null; ITesseractApi api = new TesseractApi(Android.App.Application.Context, AssetsDeployment.OncePerVersion); bool initialised = await api.Init("eng"); if (initialised) { bool success = await api.SetImage(data); if (success) { textResult = api.Text; } } return(textResult); }
protected override async void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == PickImageId) { if (resultCode == Result.Ok && Intent != null) { Uri uri = data.Data; imageView.SetImageURI(uri); Stream stream = ContentResolver.OpenInputStream(uri); TesseractApi api = new TesseractApi(this, AssetsDeployment.OncePerVersion); await api.Init("chi_sim"); await api.SetImage(PathUtil.GetActualPathFromFile(this, data.Data)); string text = api.Text; textView.SetText(text, BufferType.Normal); } } }
public async void OnPreviewFrame(byte[] data, Android.Hardware.Camera camera) { if (syncObj) { return; } if (!_api.Initialized) { return; } syncObj = true; await _api.SetImage(ConvertYuvToJpeg (data, camera)); var results = _api.Results(PageIteratorLevel.Block); foreach (var result in results) { Log.Debug("TextureViewActivity", "Word: \"{0}\", confidence: {1}", result.Text, result.Confidence); } syncObj = false; }
public async Task <Tuple <string, ImageSource> > AndroidTesseractStart(ImageSource image) { Context context = Android.App.Application.Context; string result = ""; ImageSource resultImg = image; // Default try { string whitelist = "01234556789"; whitelist += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; whitelist += "abcdefghijklmnopqrstuvwxyz"; TesseractApi api = new TesseractApi(context, AssetsDeployment.OncePerInitialization); await api.Init("eng"); api.SetWhitelist(whitelist); Bitmap bitmap = await GetBitmapFromImageSourceAsync(image, context); //ImageSource -> Bitmap Bitmap rebitmap = BitMapWidthCutting(bitmap); //BitMap Width cut in half rebitmap = BitMapLineDelete(rebitmap, 2); //BitMap Line Delete //BitMapChack(rebitmap); //Console Write BitMap resultImg = BMPtoImgsource(rebitmap); // BitMap -> ImageSource byte[] bitmapData = ConvertBitmapToByte(rebitmap); //BitMap - > Byte[] bool success = await api.SetImage(bitmapData); if (success) { result = api.Text; } return(Tuple.Create(result, resultImg)); }catch (Exception e) { return(Tuple.Create(e.Message, resultImg));; } }
//Text aus Bild public static async Task <string> getText(Bitmap img) { if (api != null) { string textResult = ""; byte[] greyByte = ImageOp.getBytesFromBitmap(img); bool success = await api.SetImage(greyByte); if (success) { textResult = api.Text; } return(textResult); } else { System.Console.WriteLine("Error API not Set"); } return(null); }
public async Task onPictureTakeAsync(byte[] data, Camera camera) { /*ContextWrapper cw = new ContextWrapper(ApplicationContext); imageFileFolder = cw.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures); Calendar c = Calendar.Instance; imageFileName = new Java.IO.File(imageFileFolder, c.Time.Seconds + ".bmp"); imageFileName.CreateNewFile(); using (var os = new FileStream(imageFileName.AbsolutePath, FileMode.Create)) { os.Write(data, 0, data.Length); } */ TesseractApi tesseractApi = new TesseractApi(ApplicationContext, AssetsDeployment.OncePerInitialization); if (!tesseractApi.Initialized) await tesseractApi.Init("eng"); var tessResult = await tesseractApi.SetImage(data); if (tessResult) { var a = tesseractApi.Text; var b = a; } Bitmap cameraBitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length); int wid = cameraBitmap.Width; int hgt = cameraBitmap.Height; Bitmap resultImage = Bitmap.CreateBitmap(wid, hgt, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(resultImage); canvas.DrawBitmap(cameraBitmap, 0f, 0f, null); image.DrawingCacheEnabled = true; image.Measure(MeasureSpec.MakeMeasureSpec(300, MeasureSpecMode.Exactly), MeasureSpec.MakeMeasureSpec(300, MeasureSpecMode.Exactly)); image.Layout(0, 0, image.MeasuredWidth, image.MeasuredHeight); image.BuildDrawingCache(true); Bitmap layoutBitmap = Bitmap.CreateBitmap(image.DrawingCache); image.DrawingCacheEnabled = false; canvas.DrawBitmap(layoutBitmap, 80f, 0f, null); ContextWrapper cw = new ContextWrapper(ApplicationContext); imageFileFolder = cw.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures); imageFileName = new Java.IO.File(imageFileFolder, DateTime.Now.Ticks.ToString() + ".jpg"); imageFileName.CreateNewFile(); try { using (var os = new FileStream(imageFileName.AbsolutePath, FileMode.Create)) { resultImage.Compress(Bitmap.CompressFormat.Jpeg, 95, os); } } catch (Exception e) { Log.Debug("In Saving File", e + ""); } dialog.Dismiss(); var activity = new Intent(this, typeof(ImageActivity)); activity.PutExtra("AbsolutePath", imageFileName.AbsolutePath); StartActivity(activity); Finish(); //StartActivity(typeof(ImageActivity)); }
public async void NullStringTest() { await _api.Init("eng"); await _api.SetImage((string)null); }
protected override async void OnActivityResult(int requestCode, Android.App.Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); ProgressDialog progress = new ProgressDialog(this); progress.Indeterminate = true; progress.SetProgressStyle(ProgressDialogStyle.Spinner); progress.SetMessage("Kraunama..."); progress.SetCancelable(false); progress.Show(); try { System.Console.WriteLine("OnActivityLoad eventas"); Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); Uri contentUri = Uri.FromFile(Failosas._file); mediaScanIntent.SetData(contentUri); // SendBroadcast(mediaScanIntent); int height = Android.Content.Res.Resources.System.DisplayMetrics.HeightPixels; int width = Android.Content.Res.Resources.System.DisplayMetrics.WidthPixels; Failosas.bitmap = Failosas._file.Path.LoadAndResizeBitmap(width, height); if (Failosas.bitmap != null) { System.Console.WriteLine("Got bitmap, doing OCR..."); TesseractApi api = new TesseractApi(mContext, AssetsDeployment.OncePerInitialization); await api.Init("eng"); api.SetPageSegmentationMode(Tesseract.PageSegmentationMode.SparseText); await api.SetImage(Failosas._file.Path); RunOnUiThread(() => { string text = api.Text; System.Console.Error.WriteLine("Gautas text: " + text); Android.Widget.Toast.MakeText(this, "Pagaliau! :D", Android.Widget.ToastLength.Long).Show(); progress.Hide(); Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(this); alert.SetTitle("Gavom teksta"); alert.SetMessage(text); alert.SetPositiveButton("nieko gero! :D", (senderAlert, args) => { Android.Widget.Toast.MakeText(this, "Gerai kad supratai!", Android.Widget.ToastLength.Short).Show(); }); Dialog dialog = alert.Create(); dialog.Show(); }); } else { Android.Widget.Toast.MakeText(this, "Blogas image!", Android.Widget.ToastLength.Short).Show(); } } catch (Exception ex) { System.Console.WriteLine("Klaida darant OCR: " + ex.ToString()); progress.Hide(); Android.Widget.Toast.MakeText(this, "Klaida darant OCR!", Android.Widget.ToastLength.Long).Show(); } finally { GC.Collect(); progress.Hide(); } }