public void FullScan(Emgu.CV.Image <Emgu.CV.Structure.Bgra, byte> pColorImage) { if (OnCodeDetected == null) { return; } BarcodeReader reader = new BarcodeReader(); ZXing.Common.DecodingOptions options = new ZXing.Common.DecodingOptions(); options.TryHarder = TryHarder; reader.Options = options; var barcodeBitmap = pColorImage.Bitmap; // detect and decode the barcode inside the bitmap Result[] result = reader.DecodeMultiple(barcodeBitmap); // do something with the result foreach (Result r in result) { if (r != null) { handleResult(r); } } }
/// <summary> /// Reads the given barcade into a string[]. /// </summary> /// <param name="bmp">The barcode.</param> /// <param name="scanQRCodeOnly">Should only scan QR codes.</param> /// <returns>The text from the given barcode.</returns> public static string[] BarcodeScan(Bitmap bmp, bool scanQRCodeOnly = false) { try { BarcodeReader barcodeReader = new BarcodeReader { AutoRotate = true, TryInverted = true, Options = new DecodingOptions { TryHarder = true } }; if (scanQRCodeOnly) { barcodeReader.Options.PossibleFormats = new List <BarcodeFormat>() { BarcodeFormat.QR_CODE }; } Result[] results = barcodeReader.DecodeMultiple(bmp); if (results != null) { return(results.Where(x => x != null && !string.IsNullOrEmpty(x.Text)).Select(x => x.Text).ToArray()); } } catch { } return(null); }
private Result[] decodeMulti(Uri uri, string originalInput, IDictionary <DecodeHintType, object> hints) { Bitmap image; try { image = (Bitmap)Bitmap.FromFile(uri.LocalPath); } catch (Exception) { throw new FileNotFoundException("Resource not found: " + uri); } using (image) { LuminanceSource source; if (config.Crop == null) { source = new BitmapLuminanceSource(image); } else { int[] crop = config.Crop; source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]); } var reader = new BarcodeReader { AutoRotate = config.AutoRotate, TryInverted = true }; foreach (var entry in hints) { reader.Options.Hints.Add(entry.Key, entry.Value); } Result[] results = reader.DecodeMultiple(source); if (results != null && results.Length > 0) { foreach (var result in results) { var points = ""; for (int i = 0; i < result.ResultPoints.Length; i++) { if (i > 0) { points += ","; } ResultPoint rp = result.ResultPoints[i]; points += "{\"x\":" + rp.X + ",\"y\":" + rp.Y + "}"; } var resultString = "{\"type\":\"" + result.BarcodeFormat + "\",\"data\":\"" + result.Text + "\",\"orientation\":" + result.ResultMetadata[ResultMetadataType.ORIENTATION] + ",\"points\":[" + points + "]}"; Console.Out.WriteLine(resultString); } return(results); } return(null); } }
private static void detectCode(Image <Gray, Byte> bitmap, decodeMode mode, out List <string> outputStr, out List <System.Windows.Point> location) { outputStr = new List <string>(); location = new List <System.Windows.Point>(); //var bitmap = new Image<Bgr, byte>(img); result = null; if (mode == decodeMode.SINGLE) { //Single code result = new Result[1]; if (reader.Decode(bitmap.ToBitmap()) != null) { result[0] = reader.Decode(bitmap.ToBitmap());//.Bytes, imgWidth, imgHeight, RGBLuminanceSource.BitmapFormat.Unknown); } if (result[0] != null) { location.Add(new System.Windows.Point(result[0].ResultPoints[0].X, result[0].ResultPoints[0].Y)); outputStr.Add("Content: " + result[0].Text + "\n" + result[0].BarcodeFormat.ToString()); } else { outputStr.Add("NULL"); } } else { //Multiple codes try { result = reader.DecodeMultiple(bitmap.ToBitmap()); } catch (Exception) { ; } if (result != null) { for (int i = 0; i < result.Length; i++) { if (result[i] != null) { location.Add(new System.Windows.Point(result[i].ResultPoints[0].X, result[i].ResultPoints[0].Y)); outputStr.Add("Content: " + result[i].Text + "\n" + result[i].BarcodeFormat.ToString()); } else { outputStr.Add("NULL"); } } } } }
private String Decode(Bitmap image, bool tryMultipleBarcodes, IList <BarcodeFormat> possibleFormats) { String decodedText = string.Empty; BarcodeReader barcodeReader = new BarcodeReader { AutoRotate = true, TryInverted = true, Options = new DecodingOptions { TryHarder = true } }; barcodeReader.ResultFound += result => { }; Result[] results = null; if (tryMultipleBarcodes) { results = barcodeReader.DecodeMultiple(image); } else { var result = barcodeReader.Decode(image); if (result != null) { //results = new[] { result }; return(result.Text); } } if (results == null) { decodedText = "No barcode recognized"; } if (results != null) { foreach (var result in results) { decodedText += result.Text; } } return(decodedText); }
public List <string> QRDecodeMulti(Bitmap qrImage, bool showMask = true) { using ( qrImage ) { #if DEBUG qrImage.Save("screensnap.png"); #endif //var br = new BarcodeReader( null, // bitmap => new BitmapLuminanceSource(bitmap), // luminance => new GlobalHistogramBinarizer(luminance)); var br = new BarcodeReader(); setDecodeOptions(br); try { var results = br.DecodeMultiple(qrImage); if (results != null) { var textList = new List <string>(); foreach (var result in results) { if (showMask) { ShowQRCodeMask(result, qrImage); } textList.Add(result.Text); } //SystemSounds.Asterisk.Play(); SystemSounds.Beep.Play(); return(textList); } else { #if DEBUG MessageBox.Show(this, "Failed to find Code!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); #endif SystemSounds.Exclamation.Play(); return(new List <string>()); } } catch { SystemSounds.Exclamation.Play(); return(new List <string>()); } } }
public static async Task <string> Decode(this WriteableBitmap image) { string result = string.Empty; if (image == null) { return(result); } if (image.PixelWidth < 32 || image.PixelHeight < 32) { return(result); } var br = new BarcodeReader(); SetDecodeOptions(br); try { //var qrResult = br.Decode(image); //if (qrResult != null) //{ // result = qrResult.Text; //} //var qrResults = br.DecodeMultiple(image); var qrResults = br.DecodeMultiple(image); var textList = new List <string>(); if (qrResults == null) { return(result); } foreach (var line in qrResults) { textList.Add(line.Text); } if (textList.Count >= 0) { result = string.Join("\n\r", textList); } } catch (Exception ex) { await new MessageDialog(ex.Message.T(), "ERROR".T()).ShowAsync(); } return(result); }
private void tsBarcode_Click(object sender, EventArgs e) { IMultipleBarcodeReader multiReader = new BarcodeReader(); multiReader.Options.TryHarder = true; var test = scannedImageRenderer.Render(ImageList.Images[ImageIndex]); var barcodeResult = multiReader.DecodeMultiple(test); if (barcodeResult != null) { foreach (var barcode in barcodeResult) { //MessageBox.Show(string.Format(MiscResources.ConfirmDeleteItems, 1), MiscResources.Delete, MessageBoxButtons.OKCancel, MessageBoxIcon.Question); MessageBox.Show(barcode.BarcodeFormat + " " + barcode.Text, MiscResources.Delete, MessageBoxButtons.OKCancel, MessageBoxIcon.Question); //System.Diagnostics.Debug.WriteLine(barcode); } } }
private void DecodeImage(Bitmap bmp) { BarcodeReader barcodeReader = new BarcodeReader { AutoRotate = true, TryInverted = true, Options = new DecodingOptions { TryHarder = true } }; Result[] results = barcodeReader.DecodeMultiple(bmp); string output = ""; if (results != null) { output = string.Join(Environment.NewLine + Environment.NewLine, results.Where(x => x != null && !string.IsNullOrEmpty(x.Text)).Select(x => x.Text)); } txtDecodeResult.Text = output.Trim(); }
bool TryRecognize(Mat imageMat, out string value) { using (var matG = imageMat.CvtColor(ColorConversionCodes.BGR2GRAY)) using (var matB = matG.Threshold(0, 255, ThresholdTypes.Otsu)) using (var image = matB.ToBitmap()) { var reader = new BarcodeReader(); reader.Options = new DecodingOptions() { TryHarder = true, PossibleFormats = new[] { BarcodeFormat.EAN_13 }, }; var results = reader.DecodeMultiple(image); if (results == null || results.Length == 0) { value = default(string); return(false); } value = results.Select(x => x.Text).FirstOrDefault(); return(value != null); } }
//Interesting method //public static string decodeQRImage(string path) //{ // Bitmap bMap = BitmapFactory.DecodeFile(path); // string decoded = null; // int[] intArray = new int[bMap.Width * bMap.Height]; // Java.IO.InputStream ist = getResources().openRawResource(R.drawable.balloons); // byte[] data = new byte[ist.Available()]; // bMap.GetPixels(intArray, 0, bMap.Width, 0, 0, bMap.Width, bMap.Height); // LuminanceSource source = new RGBLuminanceSource(data, bMap.Width, bMap.Height); // BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); // Reader reader = new QRCodeReader(); // ZXing.Result result = reader.decode(bitmap); // decoded = result.Text; // return decoded; //} // Something I am trying to get image scanning private void ReadBarcode() { try { var imageBytes = GetImage("file:///android_asset/QR_Code_Test.jpg"); var width = GetWidth("file:///android_asset/QR_Code_Test.jpg"); var height = GetHeight("file:///android_asset/QR_Code_Test.jpg"); LuminanceSource source = new ZXing.RGBLuminanceSource(imageBytes, (int)width, (int)height); HybridBinarizer hb = new HybridBinarizer(source); var a = hb.createBinarizer(source); BinaryBitmap bBitmap = new BinaryBitmap(a); BarcodeReader reader = new BarcodeReader(); reader.Options.TryHarder = true; MultiFormatReader reader1 = new MultiFormatReader(); try { var r = reader1.decodeWithState(bBitmap); var result = reader.Decode(source); var result2 = reader.DecodeMultiple(source); if (result != null) { return; } return; } catch (Java.Lang.Exception ex) { //HandleError("ReadBarcode Error: ", ex.Message); } } catch (Java.Lang.Exception ex) { //HandleError("ReadBarcode Error: ", ex.Message); } }
private void Decode(IEnumerable <Bitmap> bitmaps, bool tryMultipleBarcodes, IList <BarcodeFormat> possibleFormats) { resultPoints.Clear(); lastResults.Clear(); txtContent.Text = String.Empty; var timerStart = DateTime.Now.Ticks; IList <Result> results = null; var previousFormats = barcodeReader.Options.PossibleFormats; if (possibleFormats != null) { barcodeReader.Options.PossibleFormats = possibleFormats; } foreach (var bitmap in bitmaps) { if (tryMultipleBarcodes) { results = barcodeReader.DecodeMultiple(bitmap); } else { var result = barcodeReader.Decode(bitmap); if (result != null) { if (results == null) { results = new List <Result>(); } results.Add(result); } } } var timerStop = DateTime.Now.Ticks; barcodeReader.Options.PossibleFormats = previousFormats; if (results == null) { txtContent.Text = "No barcode recognized"; } labDuration.Text = new TimeSpan(timerStop - timerStart).ToString(); if (results != null) { foreach (var result in results) { if (result.ResultPoints.Length > 0) { var offsetX = picBarcode.SizeMode == PictureBoxSizeMode.CenterImage ? (picBarcode.Width - picBarcode.Image.Width) / 2 : 0; var offsetY = picBarcode.SizeMode == PictureBoxSizeMode.CenterImage ? (picBarcode.Height - picBarcode.Image.Height) / 2 : 0; var rect = new Rectangle((int)result.ResultPoints[0].X + offsetX, (int)result.ResultPoints[0].Y + offsetY, 1, 1); foreach (var point in result.ResultPoints) { if (point.X + offsetX < rect.Left) { rect = new Rectangle((int)point.X + offsetX, rect.Y, rect.Width + rect.X - (int)point.X - offsetX, rect.Height); } if (point.X + offsetX > rect.Right) { rect = new Rectangle(rect.X, rect.Y, rect.Width + (int)point.X - (rect.X - offsetX), rect.Height); } if (point.Y + offsetY < rect.Top) { rect = new Rectangle(rect.X, (int)point.Y + offsetY, rect.Width, rect.Height + rect.Y - (int)point.Y - offsetY); } if (point.Y + offsetY > rect.Bottom) { rect = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + (int)point.Y - (rect.Y - offsetY)); } } using (var g = picBarcode.CreateGraphics()) { g.DrawRectangle(Pens.Green, rect); } } } } }
public static double ZXingCodeRecog() { DateTime t1 = DateTime.Now, t2 = t1; float r = ImageShow.shapes[shapeIndex].R; float x1 = ImageShow.shapes[shapeIndex].P1.X; float y1 = ImageShow.shapes[shapeIndex].P1.Y; float x2 = ImageShow.shapes[shapeIndex].P2.X; float y2 = ImageShow.shapes[shapeIndex].P2.Y; PointF[] pts = new PointF[4]; pts[0] = new PointF(x2, y2); double a = Math.Sin((double)r), b = -Math.Cos((double)r), c = 0 - x1 * a - y1 * b; pts[1] = new PointF((float)(x2 - 2 * a * ((a * x2 + b * y2 + c) / (a * a + b * b))), (float)(y2 - 2 * b * ((a * x2 + b * y2 + c) / (a * a + b * b)))); pts[2] = new PointF((x1 * 2 - x2), (y1 * 2 - y2)); a = Math.Sin((double)(r - Math.PI / 2.0)); b = -Math.Cos((double)(r - Math.PI / 2.0)); c = 0 - x1 * a - y1 * b; pts[3] = new PointF((float)(x2 - 2 * a * ((a * x2 + b * y2 + c) / (a * a + b * b))), (float)(y2 - 2 * b * ((a * x2 + b * y2 + c) / (a * a + b * b)))); float x, y, width, height; x = Math.Min(pts[0].X, Math.Min(pts[1].X, Math.Min(pts[2].X, pts[3].X))); y = Math.Min(pts[0].Y, Math.Min(pts[1].Y, Math.Min(pts[2].Y, pts[3].Y))); width = Math.Max(pts[0].X, Math.Max(pts[1].X, Math.Max(pts[2].X, pts[3].X))) - x + 1; height = Math.Max(pts[0].Y, Math.Max(pts[1].Y, Math.Max(pts[2].Y, pts[3].Y))) - y + 1; if (x < 0) { width += x; x = 0; } if (y < 0) { height += y; y = 0; } Bitmap source = new Bitmap(ImageShow.nowFile); if (x + width >= source.Width) { width = source.Width - x - 1; } if (y + height >= source.Height) { height = source.Height - y - 1; } Rectangle section = new Rectangle(new Point((int)x, (int)y), new Size((int)width, (int)height)); Bitmap CroppedImage = CropImage(source, section); string tempfile = Environment.CurrentDirectory + '\\' + DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString().Replace(":", "_") + ".bmp"; CroppedImage.Save(tempfile); Bitmap img = new Bitmap(tempfile); //Bitmap img = new Bitmap(ImageShow.nowFile); t1 = DateTime.Now; Result[] results = new Result[1000]; results = reader.DecodeMultiple(img); t2 = DateTime.Now; codeType.Clear(); codeContent.Clear(); int num = 0; try { while (results[num] != null) { codeType.Add(results[num].BarcodeFormat.ToString()); codeContent.Add(results[num].Text); num++; } } catch (Exception ex) { Object aa = new object(); ex.Equals(aa); } codeNum = num; return((t2 - t1).TotalMilliseconds); }
void Update() { #if UNITY_EDITOR if (framerate++ % 10 == 0) { #else if (framerate++ % 8 == 0) { #endif if (e_DeviceController.isPlaying && !decoding) { W = e_DeviceController.dWebCam.Width(); // get the image width H = e_DeviceController.dWebCam.Height(); // get the image height if (W < 100 || H < 100) { return; } if (!isInit && W > 100 && H > 100) { blockWidth = (int)((Math.Min(W, H) / 3f) * 2); isInit = true; } if (targetColorARR == null) { targetColorARR = new Color32[blockWidth * blockWidth]; } int posx = ((W - blockWidth) >> 1);// int posy = ((H - blockWidth) >> 1); orginalc = e_DeviceController.dWebCam.GetPixels(posx, posy, blockWidth, blockWidth);// get the webcam image colors //convert the color(float) to color32 (byte) for (int i = 0; i != blockWidth; i++) { for (int j = 0; j != blockWidth; j++) { targetColorARR[i + j * blockWidth].r = (byte)(orginalc[i + j * blockWidth].r * 255); targetColorARR[i + j * blockWidth].g = (byte)(orginalc[i + j * blockWidth].g * 255); targetColorARR[i + j * blockWidth].b = (byte)(orginalc[i + j * blockWidth].b * 255); targetColorARR[i + j * blockWidth].a = 255; } } // scan the qrcode Loom.RunAsync(() => { try { // Result data; // data = barReader.Decode(targetColorARR,blockWidth,blockWidth);//start decode // // if (data != null) // if get the result success // { // decoding = true; // set the variable is true // dataText = data.Text; // use the variable to save the code result // } Result[] data; data = barReader.DecodeMultiple(targetColorARR, blockWidth, blockWidth); //start decode if (!data[0].Equals("") || data[0].Text != null) // if get the result success { decoding = true; // set the variable is true foreach (Result r in data) { dataText = r.Text + " | "; // use the variable to save the code result } } } catch (Exception e) { decoding = false; } }); } if (decoding) { // if the status variable is change if (tempDecodeing != decoding) { onQRScanFinished(dataText);//triger the scan finished event; } tempDecodeing = decoding; } } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Somewhere in your app, call the initialization code: MobileBarcodeScanner.Initialize(Application); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //Create a new instance of our Scanner scanner = new MobileBarcodeScanner(); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.myButton); button.Click += delegate { _imageView = FindViewById <ImageView>(Resource.Id.imageView1); //BitmapFactory.Options options = new BitmapFactory.Options //{ // InJustDecodeBounds = false //}; //// The result will be null because InJustDecodeBounds == true. //Bitmap bitmapToDisplay = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.download1); //_imageView.SetImageBitmap(bitmapToDisplay); _imageView.SetImageBitmap( decodeSampledBitmapFromResource(Resources, Resource.Drawable.qrcode, 375, 375)); }; Button buttonScan = FindViewById <Button>(Resource.Id.buttonScan); //buttonScan.Click += async delegate { //var scanner = new ZXing.Mobile.MobileBarcodeScanner(); //var result = await scanner.Scan(); //if (result != null) // Console.WriteLine("Scanned Barcode: " + result.Text); //}; buttonScan.Click += delegate { //var fullName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images", "download.png"); String path = System.Environment.CurrentDirectory; BitmapFactory.Options options = new BitmapFactory.Options { InPreferredConfig = Bitmap.Config.Argb8888 }; //BitmapFactory.Options options = new BitmapFactory.Options //{ // InJustDecodeBounds = true //}; // The result will be null because InJustDecodeBounds == true. //Bitmap bitmap = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.download1, options); Bitmap bitmap = decodeSampledBitmapFromResource(Resources, Resource.Drawable.qrcode, 375, 375); // var imageHeight = options.OutHeight; //var imageWidth = options.OutWidth; var imageHeight = (int)bitmap.GetBitmapInfo().Height; var imageWidth = (int)bitmap.GetBitmapInfo().Width; //using (var stream = new MemoryStream()) //{ // bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); // bitmapData = stream.ToArray(); //} int size = (int)bitmap.RowBytes * (int)bitmap.GetBitmapInfo().Height; Java.Nio.ByteBuffer byteBuffer = Java.Nio.ByteBuffer.Allocate(size); bitmap.CopyPixelsToBuffer(byteBuffer); byte[] byteArray = new byte[byteBuffer.Remaining()]; var imageBytes = byteBuffer.Get(byteArray); LuminanceSource source = new ZXing.RGBLuminanceSource(byteArray, (int)imageWidth, (int)imageHeight); var barcodeReader = new BarcodeReader(); barcodeReader.Options.TryHarder = true; //barcodeReader.Options.ReturnCodabarStartEnd = true; //barcodeReader.Options.PureBarcode = true; //barcodeReader.Options.PossibleFormats = new List<BarcodeFormat>(); //barcodeReader.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE); ZXing.Result result = barcodeReader.Decode(source); var result2 = barcodeReader.DecodeMultiple(source); ZXing.Result result3 = barcodeReader.Decode(byteArray, (int)imageWidth, (int)imageHeight, RGBLuminanceSource.BitmapFormat.RGB24); ZXing.Result result4 = barcodeReader.Decode(source); HybridBinarizer hb = new HybridBinarizer(source); var a = hb.createBinarizer(source); BinaryBitmap bBitmap = new BinaryBitmap(a); MultiFormatReader reader1 = new MultiFormatReader(); var r = reader1.decodeWithState(bBitmap); int[] intarray = new int[((int)imageHeight * (int)imageWidth)]; bitmap.GetPixels(intarray, 0, (int)bitmap.GetBitmapInfo().Width, 0, 0, (int)imageWidth, (int)imageHeight); LuminanceSource source5 = new RGBLuminanceSource(byteArray, (int)imageWidth, (int)imageHeight); BinaryBitmap bitmap3 = new BinaryBitmap(new HybridBinarizer(source)); ZXing.Reader reader = new DataMatrixReader(); //....doing the actually reading ZXing.Result result10 = reader.decode(bitmap3); //InputStream is = this.Resources.OpenRawResource(Resource.Id.imageView1); //Bitmap originalBitmap = BitmapFactory.decodeStream(is); //UIImage //var barcodeBitmap = (Bitmap)Bitmap.FromFile(@"C:\Users\jeremy\Desktop\qrimage.bmp"); }; Button buttonScan2 = FindViewById <Button>(Resource.Id.buttonScan2); buttonScan2.Click += async delegate { //Tell our scanner to activiyt use the default overlay scanner.UseCustomOverlay = false; //We can customize the top and bottom text of the default overlay scanner.TopText = "Hold the camera up to the barcode\nAbout 6 inches away"; scanner.BottomText = "Wait for the barcode to automatically scan!"; //Start scanning var result = await scanner.Scan(); // Handler for the result returned by the scanner. HandleScanResult(result); }; }
private void Run(IEnumerable <string> filesToImport, Action <ScannedImage> imageCallback, bool oneFile) { foreach (var fileName in filesToImport) { try { Status.StatusText = string.Format(MiscResources.ImportingFormat, Path.GetFileName(fileName)); InvokeStatusChanged(); var images = scannedImageImporter.Import(fileName, (i, j) => { if (oneFile) { Status.CurrentProgress = i; Status.MaxProgress = j; InvokeStatusChanged(); } return(!cancel); }); ScanProfile profile = profileManager.DefaultProfile; foreach (var img in images) { //Squeeze Barcode Separation if (profile.AutoSaveSettings.Separator == SaveSeparator.Barcode) { IMultipleBarcodeReader multiReader = new BarcodeReader(); multiReader.Options.TryHarder = true; if (profile.AutoSaveSettings.BarcodeType != null && profile.AutoSaveSettings.BarcodeType != "") { switch (profile.AutoSaveSettings.BarcodeType) { case "2of5 interleaved": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.ITF); break; case "Code 39": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_39); break; case "Code 93": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_93); break; case "Code 128": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_128); break; case "EAN 8": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.EAN_8); break; case "EAN13": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.EAN_13); break; } } var test = scannedImageRenderer.Render(img); var barcodeResult = multiReader.DecodeMultiple(test); if (barcodeResult != null) { foreach (var barcode in barcodeResult) { if (profile.AutoSaveSettings.BarcodeRegEx != "") { Regex regex = new Regex(@"^" + profile.AutoSaveSettings.BarcodeRegEx + "$"); Match match = regex.Match(barcode.Text); if (match.Success) { if (barcode.Text != profile.AutoSaveSettings.BarcodeIgnore) { img.Barcode = barcode.Text; System.Diagnostics.Debug.WriteLine(barcode.BarcodeFormat + " = " + barcode.Text); break; } } } else { img.Barcode = barcode.Text; System.Diagnostics.Debug.WriteLine(barcode.BarcodeFormat + " = " + barcode.Text); break; } } } } imageCallback(img); } } catch (Exception ex) { Log.ErrorException(string.Format(MiscResources.ImportErrorCouldNot, Path.GetFileName(fileName)), ex); InvokeError(string.Format(MiscResources.ImportErrorCouldNot, Path.GetFileName(fileName)), ex); } if (!oneFile) { Status.CurrentProgress++; InvokeStatusChanged(); } } Status.Success = true; }
private void Decode(Bitmap image, bool tryMultipleBarcodes, IList <BarcodeFormat> possibleFormats) { resultPoints.Clear(); lastResults.Clear(); txtContent.Text = String.Empty; var timerStart = DateTime.Now.Ticks; Result[] results = null; var previousFormats = barcodeReader.Options.PossibleFormats; if (possibleFormats != null) { barcodeReader.Options.PossibleFormats = possibleFormats; } if (tryMultipleBarcodes) { results = barcodeReader.DecodeMultiple(image); } else { var result = barcodeReader.Decode(image); if (result != null) { results = new[] { result }; } } var timerStop = DateTime.Now.Ticks; barcodeReader.Options.PossibleFormats = previousFormats; if (results == null) { txtContent.Text = "No barcode recognized"; } labDuration.Text = new TimeSpan(timerStop - timerStart).ToString(); if (results != null) { foreach (var result in results) { if (result.ResultPoints.Length > 0) { var rect = new Rectangle((int)result.ResultPoints[0].X, (int)result.ResultPoints[0].Y, 1, 1); foreach (var point in result.ResultPoints) { if (point.X < rect.Left) { rect = new Rectangle((int)point.X, rect.Y, rect.Width + rect.X - (int)point.X, rect.Height); } if (point.X > rect.Right) { rect = new Rectangle(rect.X, rect.Y, rect.Width + (int)point.X - rect.X, rect.Height); } if (point.Y < rect.Top) { rect = new Rectangle(rect.X, (int)point.Y, rect.Width, rect.Height + rect.Y - (int)point.Y); } if (point.Y > rect.Bottom) { rect = new Rectangle(rect.X, rect.Y, rect.Width, rect.Height + (int)point.Y - rect.Y); } } using (var g = picBarcode.CreateGraphics()) { g.DrawRectangle(Pens.Green, rect); } } } } }
/// <summary> /// Performs the analysis on the image /// </summary> public void Analyze(bool thorough = true) { if (m_disposed) { throw new ObjectDisposedException("ImageProcessor"); } if (IsScannable) { return; } LuminanceSource source = new BitmapLuminanceSource(m_bitmap); var binarizer = new HybridBinarizer(source); var binBitmap = new BinaryBitmap(binarizer); // Try to extract the form data var barReader = new BarcodeReader(); barReader.AutoRotate = true; barReader.Options.TryHarder = thorough; barReader.Options.PossibleFormats = new List <BarcodeFormat> { BarcodeFormat.CODE_128 }; m_barcodeResults = barReader.DecodeMultiple(source); // Look for barcode markers if possible if (m_barcodeResults != null) { MarkerCodes = m_barcodeResults.Where(o => o.Text.StartsWith("OMR:")).ToArray(); } IsScannable = true; // Get the template data var markerCode = MarkerCodes == null ? null : MarkerCodes.FirstOrDefault(o => o.Text.StartsWith("OMR:TL") || o.Text.StartsWith("OMR:ID")); // Get the guiding points by circles var grayFilter = new GrayscaleY(); var thresholdFilter = new Threshold(127); var invertFilter = new Invert(); using (var searchImage = invertFilter.Apply(thresholdFilter.Apply(grayFilter.Apply(m_bitmap)))) { // Blobs var blobCounter = new BlobCounter(); blobCounter.FilterBlobs = true; blobCounter.MinHeight = 30; blobCounter.MinWidth = 30; // Check for circles blobCounter.ProcessImage(searchImage); var blobs = blobCounter.GetObjectsInformation(); var shapeChecker = new SimpleShapeChecker(); var controlPoints = new List <Point>(); var currentCheck = 45; while ((currentCheck-- > 20) && (controlPoints.Count != 4)) { controlPoints.Clear(); // Get the positions foreach (var blob in blobs) { var center = new Point(); float radius = 0; if (shapeChecker.IsCircle(blobCounter.GetBlobsEdgePoints(blob), out center, out radius) && (radius > currentCheck)) { controlPoints.Add(center); } } } // Control points IsScannable &= controlPoints.Count == 4; if (!IsScannable) { return; } // Now set markers m_topLeft = controlPoints[0]; //new AForge.Point(this.m_bitmap.Width + 10, this.m_bitmap.Height + 10); m_topRight = controlPoints[1]; m_bottomLeft = controlPoints[2]; m_bottomRight = controlPoints[3]; // Find the right most bubble float rightMost = controlPoints.Select(o => o.X).Max(), leftMost = controlPoints.Select(o => o.X).Min(); // Organize those that are left/right Point[] lefties = controlPoints.Where(o => o.X < leftMost + (rightMost - leftMost) / 2).ToArray(), righties = controlPoints.Where(o => o.X > leftMost + (rightMost - leftMost) / 2).ToArray(); // HACK: if (lefties[0].Y < lefties[1].Y) { m_topLeft = lefties[0]; m_bottomLeft = lefties[1]; } else { m_topLeft = lefties[1]; m_bottomLeft = lefties[0]; } // HACK: if (righties[0].Y < righties[1].Y) { m_topRight = righties[0]; m_bottomRight = righties[1]; } else { m_topRight = righties[1]; m_bottomRight = righties[0]; } } if (!IsScannable) { return; } // Get the template data if ((MarkerCodes != null) && (markerCode != null)) { var templateData = markerCode.Text.Split(':'); if (templateData.Length > 2) { TemplateName = templateData[2]; if (templateData.Length > 3) { Parameters = templateData.Skip(3).ToArray(); } } } }
public void PostProcessStep2(ScannedImage image, Bitmap bitmap, ScanProfile profile, ScanParams scanParams, int pageNumber) { if (!profile.UseNativeUI && profile.BrightnessContrastAfterScan) { if (profile.Brightness != 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new BrightnessTransform { Brightness = profile.Brightness }); } if (profile.Contrast != 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new TrueContrastTransform { Contrast = profile.Contrast }); } } if (profile.FlipDuplexedPages && pageNumber % 2 == 0) { AddTransformAndUpdateThumbnail(image, ref bitmap, new RotationTransform(RotateFlipType.Rotate180FlipNone)); } if (profile.AutoDeskew) { var op = operationFactory.Create <DeskewOperation>(); if (op.Start(new[] { image })) { operationProgress.ShowProgress(op); } } if (scanParams.DetectPatchCodes && image.PatchCode == PatchCode.None) { IBarcodeReader reader = new BarcodeReader(); var barcodeResult = reader.Decode(bitmap); if (barcodeResult != null) { switch (barcodeResult.Text) { case "PATCH1": image.PatchCode = PatchCode.Patch1; break; case "PATCH2": image.PatchCode = PatchCode.Patch2; break; case "PATCH3": image.PatchCode = PatchCode.Patch3; break; case "PATCH4": image.PatchCode = PatchCode.Patch4; break; case "PATCH6": image.PatchCode = PatchCode.Patch6; break; case "PATCHT": image.PatchCode = PatchCode.PatchT; break; } } } else if (scanParams.DetectBarcodes) { IMultipleBarcodeReader multiReader = new BarcodeReader(); multiReader.Options.TryHarder = true; // profile.AutoSaveSettings.Separator == ImportExport.SaveSeparator.Barcode if (profile.AutoSaveSettings != null) { if (profile.AutoSaveSettings.BarcodeType != null && profile.AutoSaveSettings.BarcodeType != "") { switch (profile.AutoSaveSettings.BarcodeType) { case "2of5 interleaved": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.ITF); break; case "Code 39": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_39); break; case "Code 93": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_93); break; case "Code 128": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.CODE_128); break; case "EAN 8": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.EAN_8); break; case "EAN13": multiReader.Options.PossibleFormats = new List <BarcodeFormat>(); multiReader.Options.PossibleFormats.Add(BarcodeFormat.EAN_13); break; } } } var barcodeResult = multiReader.DecodeMultiple(bitmap); if (barcodeResult != null) { foreach (var barcode in barcodeResult) { image.Barcode = barcode.Text; System.Diagnostics.Debug.WriteLine(barcode.BarcodeFormat + " = " + barcode.Text); } } } }
private Result[] decodeMulti(Uri uri, string originalInput, IDictionary <DecodeHintType, object> hints) { Bitmap image; try { image = (Bitmap)Bitmap.FromFile(uri.LocalPath); } catch (Exception) { throw new FileNotFoundException("Resource not found: " + uri); } using (image) { LuminanceSource source; if (config.Crop == null) { source = new BitmapLuminanceSource(image); } else { int[] crop = config.Crop; source = new BitmapLuminanceSource(image).crop(crop[0], crop[1], crop[2], crop[3]); } if (config.DumpBlackPoint) { var bitmap = new BinaryBitmap(new HybridBinarizer(source)); dumpBlackPoint(uri, image, bitmap, source); } var reader = new BarcodeReader { AutoRotate = config.AutoRotate }; foreach (var entry in hints) { reader.Options.Hints.Add(entry.Key, entry.Value); } Result[] results = reader.DecodeMultiple(source); if (results != null && results.Length > 0) { if (config.Brief) { Console.Out.WriteLine(uri + ": Success"); } else { foreach (var result in results) { ParsedResult parsedResult = ResultParser.parseResult(result); var resultString = originalInput + " (format: " + result.BarcodeFormat + ", type: " + parsedResult.Type + "):" + Environment.NewLine; for (int i = 0; i < result.ResultPoints.Length; i++) { ResultPoint rp = result.ResultPoints[i]; Console.Out.WriteLine(" Point " + i + ": (" + rp.X + ',' + rp.Y + ')'); } resultString += "Raw result:" + Environment.NewLine + result.Text + Environment.NewLine; resultString += "Parsed result:" + Environment.NewLine + parsedResult.DisplayResult + Environment.NewLine; Console.Out.WriteLine(resultString); ResultString = resultString; } } return(results); } else { var resultString = originalInput + ": No barcode found"; Console.Out.WriteLine(resultString); ResultString = resultString; } return(null); } }