Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce scanning area #791

Open
gsharmaappcore opened this issue Dec 19, 2018 · 23 comments
Open

Reduce scanning area #791

gsharmaappcore opened this issue Dec 19, 2018 · 23 comments

Comments

@gsharmaappcore
Copy link

I need to reduce the scanning area so that the barcode when placed in the center of the red scan line then only it should be scanned.Please provide the way out for this

@paulc8712
Copy link

This would be great as the user expects that the scan will occur when in the 'target area', and it can get confusing when a scan is triggered outside of that.

@kiwicodemonkey
Copy link

Can this please be looked at? As paulc8712 said, it is very confusing for users when the scan does not occur where they expect.

For our case, we are only interested in this for 1D barcodes. Looking through the source, there a method:

MultiFormatOneDReader.decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints)
Attempts to decode a one-dimensional barcode format given a single row of an image.

Could we have an option to call this against the center line of the image?

@huytran291195
Copy link

I need to reduce the scanning area so that the barcode when placed in the center of the red scan line then only it should be scanned.Please provide the way out for this

Can you solve it yet? .. Help me. I same you

@priyanka4m
Copy link

We are using Zxing in Xamarin Forms for an iOS app. We are facing the same issue - Unable to reduce the scanning Area.
We use our iOS App to scan products stacked one over the other. Ability to reduce the scanning area will help us to scan only the required products. Right now, the app scans even those that are not intended to.
Is there any resolution/workaround yet on this?

@nitewulf
Copy link

I'm working on putting together a PR that addresses this. My solution allows a View (some sort of framing square/rectangle on the custom overlay) to be provided to the CameraAnalyzer class. Whatever the screen rotation/screen resolution/location of the scan area only what is inside that view will be looked at for scanning. There's also an option to autofocus that scan area. It achieves focus noticeably faster than the ContinuousPicture/Video modes.

@nitewulf
Copy link

pull request completed: #889

@MisterAcoustic
Copy link

MisterAcoustic commented May 11, 2020

Hello - is there any word on whether this pull request will be brought in? If so, any time frame or release planned? We really need this feature - so much so that we've already hacked our own version of ZXing.Net.Mobile - but the way we did it may have led to a decrease in the ability to scan long/complex bar codes. I'd really like to upgrade to a 3.x version that includes this feature right away.

Thanks for listening :)

EDIT: I finally saw that this was added to the '3.1 milestone' - any idea whether nitewulf's pull request is a proper fix for this issue?

@nitewulf
Copy link

MisterAcoustic,

I needed the feature for our inventory app and had to hack my own version as well. I've been working on it and other improvements for a couple of months. My PR is an upgraded 3.0 version. I took the latest master branch from Redeth's repo and modified that. If you want to pull my dev branch I'd love to hear some confirmation that it works as well as I believe.

https://github.com/nitewulf/ZXing.Net.Mobile/tree/dev-scanarea

@MisterAcoustic
Copy link

Thanks nitewulf - I'm in the process of trying to build the latest code from here. My plan was to pull your fix into that version and see how well it works :). I have a few hurdles to cross because the solution doesn't compile out of the box for me - I think I'm missing necessary installs of various things - but when I get it going, I will let you know what I find. Thanks!

@MisterAcoustic
Copy link

MisterAcoustic commented May 14, 2020

LargeCode
Hey nitewulf - First, I'd like to say that it seems you've done a lot of nice work on this. However, for my purposes, there is a problem. We have some overly complicated bar codes - really long text encoded. For these kinds of codes, your changes seem to suffer from the same problems our hacky changes did. When scanning with the full camera area, the library will recognize these codes quite well currently - even slightly better than our handheld laser scanners. However, using the restricted area to scan, the codes are not recognized.

I believe that something else needs to be done to maintain the ability to scan these longer codes. Our hack involved changing the values sent in to the constructor of the FastJavaByteArrayYUVLuminanceSource. We effectively reduced the size of the image the analyzer had to look at. I'm guessing that this approach actually won't work. I haven't tracked down whether your changes have a similar effect, but I'm guessing they do. I'm thinking that perhaps instead of changing the area scanned, we may have to fill the parts of the buffer we're not interested in with a constant value like white or gray.

One last thing - in the FragmentActivityCustomScanArea, you have CameraResolutionSelector code - but it doesn't actually select a resolution. Here's what I did:

                CameraResolutionSelector = availableResolutions => {

                    int bestFound = 0;
                    int foundIndex = 0;
                    int index = 0;
                    foreach (ZXing.Mobile.CameraResolution res in availableResolutions)
                    {
                        int currentSize = res.Height * res.Width;
                        System.Diagnostics.Trace.WriteLine("index: " + index.ToString() + " Height: " + res.Height.ToString() + " Width: " + res.Width.ToString());
                        System.Diagnostics.Trace.WriteLine("currentSize: " + currentSize.ToString() + " bestFound: " + bestFound.ToString());
                        if (currentSize >= bestFound)
                        {
                            bestFound = currentSize;
                            foundIndex = index;
                        }

                        index += 1;
                    }

                    System.Diagnostics.Trace.WriteLine("Selected Index: " + foundIndex.ToString() + " Height: " + availableResolutions[foundIndex].Height.ToString() + " Width: " + availableResolutions[foundIndex].Width.ToString());

                    return availableResolutions[foundIndex];

                }
            };

Please let me know what you think.

EDIT: I may have broken something with the camera selector code - I'm not sure. But still, with a complex bar code example, I can go back and forth in the android sample app between scanning with the default overlay (works), and any of the custom overlay pages (doesn't work). I will attempt to attach a sample bar code as soon as possible.

EDIT2: Added a .png of a complex bar code, easily readable with the default overlay, not working with others. The code is printed quite a bit smaller than the image is rendered here on the web page. The code should read: "SS-2020-1255-04Z10Z1Z1".

EDIT3: Gack - last edit, I promise. I am testing with the android sample app, on a samsung galaxy tab. I have now seen the restricted size areas work. I was able to read the code I posted right off the screen here, and went back to paper and was also successful. I'm wondering if something else is going on - possible auto-focus issues, or camera resolution selection issues. I had spent literally minutes trying to get it to read the code one time previously - and it would just never read. Have you seen any behavior like this?

@nitewulf
Copy link

nitewulf commented May 15, 2020 via email

@MisterAcoustic
Copy link

Hi nitewulf, I added the bar code example to the previous post in one of my many edits. I see it displayed at the top of the post for some reason. The printed version that I'm testing with measures about 4 and 1/4 inches in width.

I am currently confused, since I am seeing behavior all over the map from the library in general. It may be that your modifications are not part of the problem. On occasion, I see fantastic performance from the library - reads the long codes quickly and easily. Much of the time though, it's unlikely to read the code at all. I do not have an idea yet what might be happening, but I am thinking about focus issues, camera resolution, and I'm also noticing some exceptions being thrown from way down in the BarcodeReader.Decode function (no idea if they're important).

Do you (or anyone listening) have an idea why the normal way of selecting a camera resolution doesn't pick the highest available resolution?:

				// Loop through all supported sizes
				foreach (var sps in availableResolutions)
				{
					// Find one that's >= 640x360 but <= 1000x1000
					// This will likely pick the *smallest* size in that range, which should be fine
					if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000)
					{
                                                  ........

I think that every time I attempt to use a CameraResolutionSelector to actually return a result, things are not working. Still confused, any input is appreciated.

@nitewulf
Copy link

nitewulf commented May 22, 2020

That's something I wanted to improve as well. Here's my branch for selecting the best resolution available that is closest to matching the aspect ratio of the surface view:

https://github.com/nitewulf/ZXing.Net.Mobile/tree/dev-resolution-select

I'll also have a branch at some point in the near future with my changes for focus areas. Basically I used my cropped scan area and made it autofocus on that area every (configurable number of milliseconds). I noticed a significant (hard to really quantify that, but it felt much faster) improvement over just letting the camera try to continuously autofocus.

@MisterAcoustic
Copy link

Hi nitewulf - I've been swamped. I was doing some testing, and it doesn't appear that you implemented the reduced scannning area for iOS devices - is that correct? I've also been trying to get AutoFocus to work more consistently, and I've been running into problems. On my samsung galaxy tab, I see autofocus working one time - then all further attempts will get "AutoFocus Failed" in the log. The camera app on the device still does autofocus normally. Any ideas on that?

@nitewulf
Copy link

Yeah, I don't have any iOS devices to develop against.

AutoFocus can be a jerk. I think the best overall solution for it is to continuously (with a configurable number of milliseconds in between) attempt to focus on the reduced scanning area instead of letting the camera try to automatically focus by itself.

That's the last of the changes I've made to the library. I'll organize that into a proper PR in my repo soon.

@universaldata-eu
Copy link

doesn't pullrequest #921 solve this issue?

@paranpiano
Copy link

paranpiano commented Nov 2, 2020

The latest package 3.0.0-beta5 doesn't have this update.
Anybody knows how to apply it before the next version release.

scanPage = new ZXingScannerPage(new MobileBarcodeScanningOptions
{
ScanningArea = ScanningArea.From(0f, 0.49f, 1f, 0.51f),
PossibleFormats = new List { BarcodeFormat.All_1D }
});

public MobileBarcodeScanningOptions()
{
PossibleFormats = new List();
//this.AutoRotate = true;
DelayBetweenAnalyzingFrames = 150;
InitialDelayBeforeAnalyzingFrames = 300;
DelayBetweenContinuousScans = 1000;
UseNativeScanning = false;
ScanningArea = ScanningArea.Default;
}
public class ScanningArea
{
public float StartX { get; }
public float StartY { get; }
public float EndX { get; }
public float EndY { get; }

ScanningArea(float startX, float startY, float endX, float endY)
{
	//if difference between parameters is less than 1% we assume those are equal
	if (Math.Abs(startY - endY) < 0.01f)
	{
		throw new ArgumentException($"Values of {nameof(startY)} and {nameof(endY)} cannot be the same");
	}

	//if difference between parameters is less than 1% we assume those are equal
	if (Math.Abs(startX - endX) < 0.01f)
	{
		throw new ArgumentException($"Values of {nameof(startX)} and {nameof(endX)} cannot be the same");
	}

	//Reverse values instead of throwing argument exception
	if (startY > endY)
	{
		var temp = endY;
		endY = startY;
		startY = temp;
	}

	if (startX > endX)
	{
		var temp = endX;
		endX = startX;
		startX = temp;
	}

	if (startY < 0)
	{
		startY = 0;
	}

	if (endY > 1)
	{
		endY = 1;
	}

	if (startX < 0)
	{
		startX = 0;
	}

	if (endX > 1)
	{
		endX = 1;
	}

	StartY = startY;
	EndY = endY;
	StartX = startX;
	EndX = endX;
}

public ScanningArea RotateCounterClockwise()
{
	var startX = StartY;
	var startY = EndX;
	var endX = EndY;
	var endY = StartX;

	if (startY > endY)
	{
		startY = 1f - startY;
		endY = 1 - endY;
	}

	if (startX > endX)
	{
		startX = 1 - startX;
		endX = 1 - endX;
	}

	return new ScanningArea(startX, startY, endX, endY);
}


static ScanningArea _default = new ScanningArea(0f, 0f, 1f, 1f);

/// <summary>
/// Returns value that represents whole image.
/// </summary>
public static ScanningArea Default => _default;

public static ScanningArea From(float startX, float startY, float endX, float endY) =>
	new ScanningArea(startX, startY, endX, endY);

}

@universaldata-eu
Copy link

i took the branch of #921: https://github.com/michcons/ZXing.Net.Mobile/tree/narrow-scanning-area
but in the 3.0.0 there is still a problem with focus on android devices (#875) . i stepped into it and found a solution.
in ZXing.Net.Mobile\Android\CameraAccess\CameraController.android.cs i removed two lines because after SetupCamera() RefreshCamera() is always called doing these calls twice:
`public void SetupCamera()
{
...
try
{
//Camera.SetPreviewDisplay(holder);

			var previewParameters = Camera.GetParameters();
			var previewSize = previewParameters.PreviewSize;
			var bitsPerPixel = ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat);


			var bufferSize = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8;
			const int NUM_PREVIEW_BUFFERS = 5;
			for (uint i = 0; i < NUM_PREVIEW_BUFFERS; ++i)
			{
				using (var buffer = new FastJavaByteArray(bufferSize))
					Camera.AddCallbackBuffer(buffer);
			}

			//Camera.StartPreview();

			Camera.SetNonMarshalingPreviewCallback(cameraEventListener);
		}
		catch (Exception ex)
		{
			Android.Util.Log.Debug(MobileBarcodeScanner.TAG, ex.ToString());
			return;
		}
		finally
		{
			PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms");
		}

...
`

@paranpiano
Copy link

i took the branch of #921: https://github.com/michcons/ZXing.Net.Mobile/tree/narrow-scanning-area
but in the 3.0.0 there is still a problem with focus on android devices (#875) . i stepped into it and found a solution.
in ZXing.Net.Mobile\Android\CameraAccess\CameraController.android.cs i removed two lines because after SetupCamera() RefreshCamera() is always called doing these calls twice:
`public void SetupCamera()
{
...
try
{
//Camera.SetPreviewDisplay(holder);

			var previewParameters = Camera.GetParameters();
			var previewSize = previewParameters.PreviewSize;
			var bitsPerPixel = ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat);


			var bufferSize = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8;
			const int NUM_PREVIEW_BUFFERS = 5;
			for (uint i = 0; i < NUM_PREVIEW_BUFFERS; ++i)
			{
				using (var buffer = new FastJavaByteArray(bufferSize))
					Camera.AddCallbackBuffer(buffer);
			}

			//Camera.StartPreview();

			Camera.SetNonMarshalingPreviewCallback(cameraEventListener);
		}
		catch (Exception ex)
		{
			Android.Util.Log.Debug(MobileBarcodeScanner.TAG, ex.ToString());
			return;
		}
		finally
		{
			PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms");
		}

...
`
Hello , universaldata-eu
Would you share #921 + what you have done with me ? solution or project
I really appreciate it.

@Hollywood25201
Copy link

any update on this?

@HNordhaus
Copy link

More than a year has passed - please let us know when the PR will be merged.
Thanks :-)

@ABDKBR
Copy link

ABDKBR commented Jun 22, 2022

any update on this?

@Sashi13
Copy link

Sashi13 commented Aug 15, 2023

When the PR will be merged?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests