[scanner setSymbology: 0可以大大提高性能。
config: ZBAR_CFG_ENABLE
to: 0];
[scanner setSymbology: ZBAR_QRCODE
config: ZBAR_CFG_ENABLE
to: 1];
As good as the iPhone performance is for a mobile device, the reality from animage processing perspective is that it represents a lower performance target.While the default configuration of the iPhone reader has been carefully tunedfor the general case, you can often obtain much better results if you optimizefor your specific application.
Note
Performance is a complex topic. The only way to tune performance is bychanging settings and comparing measured results. If you are notcomfortable with the concepts presented here, it is recommended that youleave the settings at the defaults and avoid compromising reliability.
Performance of the barcode reader is generally evaluated by two factors:
Basically our goal is to optimize the latency without sacrificing reliability.There are several factors that contribue to latency:
Most of these factors are interrelated. We will discuss those we can controlin detail, as well the settings you use to affect them. Then we will providea few specific case examples.
Subjective response times are a good place to start (does it “feel” responsiveto you?), and possibly the only way to evaluate the overall experience, but tocompare incremental changes to interrelated settings and have meaningfulperformance discussions with others, we need a more quantitative approach.
The mach_absolute_time() function is a good tool for accuratelymeasuring small delays. Research this function and learn how to apply it. Aswhen measuring any real-world value, keep in mind that some variance is to beexpected - even if you perform exactly the same operation multiple times, youwill not see exactly the same measurement. You should collect severalsamples, discard any obvious outliers, and average the remaining measurements.
One way that the overall reader latency may be evaluated is by manuallymarking the time when the barcode is presented to the reader. Add a controlto your overlay that captures the start time when tapped and compare this tothe end time, just before your delegate returns.
The reader continually monitors the frame rate at which it is running. Themeasured value may be displayed for debugging purposes by enabling theshowsFPS property. The readertest example doesthis and also provides control over many of the available settings, so you canquickly test how each setting affects the frame rate. You should target youroptimization efforts to achieve a frame rate of at least 8-10fps, although12-15fps is preferable.
You can measure the latency of your delegate using mach_absolute_time().The measured value should be less than about 100ms, the smaller the better, toavoid noticeable lag.
The readertest is a good tool for testing the performance of the reader. Youcan tune the settings appropriately for your application and evaluate theeffect each change has on the performance.
This latency contributor is the easiest for you to effect (and sometimes theeasiest to overlook). You delegate method should update the interface -dismiss the controller or update your overlay to indicate success - andnothing else. All other processing should be deferred until after theanimations have started.
One might think that “more is better” in terms of resolution, but this is notnecessarily the case. Given average image quality, the ideal resolution forscanning is right around three pixels per barcode “module” (the width of thesmallest bar or space). Note that this measure is not an absolute image sizeor even a measure of the physical dimensions represented by a pixel sample, itonly describes the sampled size of the barcode in the image.
As the resolution decreases below about two pixels per module, edge fidelityis lost and the bars and spaces start to merge together, making it impossible(for this library) to scan. This affects the density (feature size) andmaximum size (data capacity) of the barcodes that can be detected.Conversely, as the resolution increases above about 4 pixels per module, noisecan interfere with the edge detection and images will take longer to process.
Other quality factors, such as poor focus, bad lighting or even excessivenoise, can increase (or decrease) the resolution requirement.
When scanning from the camera, the reader defaults to 640x480, which is goodfor most applications. On the iPhone 4, you can increase this using a capturesession preset. The iPhone 3GS does not have ahigher resolution option available.
For scanning images, you can usemaxScanDimension to control the scaled sizeof the converted image, or resort to converting them yourself.
If you want to read long linear barcodes or dense 2-D symbols, you willprobably want to increase the resolution by adjusting these settings.
Keep in mind that more pixels will take longer to scan, refer to the framerate discussion for ways to compensate.
Ideally we would fix the focus at a calculated optimum distance and optimizethe aperture selection to maximize the depth of field. Unfortunately the APIsdo not currently give us control over any of these settings, the best we cando (as of iOS 4) is continuous auto-focus mode - this mode is configured bythe reader automatically. It can still take the device as long as 1-2 secondsto find the appropriate macro focus setting, but there just isn’t much we cando about that.
An image that is too bright or overexposed can completely wash out anybarcodes. An image that is too dark or underexposed will not providesufficient contrast for the scanner. Low light levels also tend to producenoisier images, possibly because the driver uses a faster “ISO” setting tocompensate for the lighting.
The camera defaults to continuous automatic exposure and white balance. Sincethere are no other useful values, the reader leaves these unchanged from theirdefault setting.
For the iPhone 4 device, the “torch” can be enabled to provide additionalillumination for the camera in low-light conditions. The reader sets thetorch to automatic by default, so it should turn on only when needeed...There have been some reports that the torch turns on inappropriately, washingout the image. If you find that this occurs, you should instead set thetorchMode property of the ZBarReaderViewto Off.
For scanning images from another source, you are again stuck with theavailable image quality. If you have any control over the image source, youshould do what you can to fix quality problems there.
Some level of noise is filtered by the reader, but excessive noise levelscreate additional edges in the image which corrupt barcodes and increasescanning time (decreasing the frame rate).
As mentioned with lighting and exposure, noise mostly becomes a problemwhen the light-level is too low, but high-resolution images may also increaseexposure to sensor noise.
We compensate for noise by reducing the resolution from the sensormaximum. Scaling the image down has the effect of averaging several pixelsinto one value, filtering out the high-frequency noise component.
The time it takes to scan and decode an image/frame is roughly proportional tothe number of pixels that are processed. The number and type of enabledsymbologies and image noise can also affect the processing time.
We have several knobs available that affect the frame rate. Most of these aregeared toward reducing the number of image pixels that are scanned.
Adjusting the resolution of the image is an easy way to quickly reduce thenumber of pixels. Smaller images also mean there is less data to carryaround, which helps performance in other ways. For example, reducing eachimage dimension by 30% (eg, from 640x480 to 448x336) will about double thespeed of the reader (to a point). [FIXME verify!]
Adjusting the resolution is described above. As mentionedthere, reducing the resolution will negatively impact the minimum feature sizeand maximum barcode size that can be scanned, but it will help filter noise.
It may not always be necessary for an application to scan all the way to theedges of the image. By cropping the scan area, you can get most of thebenefits of reduced resolution without sacrificing the minimum feature size.Cropping will also not affect image noise, but similar to decreasing theresolution, it does affect the maximum size barcode that can be scanned.
For all cases you set the crop rectanglescanCrop property. Note that therectangle provided to the controller is normalized across image size androtation. This means that the coordinates range from 0 to 1 and the axes willbe arranged such that the x-axis of the crop rectangle corresponds to themajor (longer) image axis.
Your interface will typically need to indicate the cropped scan area to theuser with visual queues. Use thecameraOverlayView to provide this.
By default, the ZBarReaderView recognizes a pinch gesture todigitally zoom the preview around the center of the image. This zoom does notaffect the resolution of the image, but it does crop the scan region to thevisible area. You can also disable the pinch gesture and set thezoom programmatically.
The scanner works by making scan passes across the pixel rows and colums ofthe image. The density of the passes is configured at the scanner as a pixelstride for each axis. ZBAR_CFG_Y_DENSITY (ZBAR_CFG_X_DENSITY)controls the number of pixel rows (columns) that are skipped betweensuccessive horizontal (vertical) scan passes. (Note that “density” is reallynot a good name for the configuation settings... “stride” might be moreappropriate.)
Decreasing the scan density (by increasing the stride setting) is a great wayto limit the processing (increasing the frame rate) without sacrificing scanresolution - each scan pass is still made at full image resolution, there arejust fewer passes (less redundancy).
Setting the stride value to 0 completely disables scanning in that direction.This is very useful when reading linear codes with a visual alignment guide -scanning parallel to the bars is a waste of cycles which may be better appliedto support higher resolution or increased density of scans across the symbol.Note that some 2-D symbologies (QR Code) require scans in both directions.
Setting the stride to a very large value will generate a single scan passthrough the center of the image. Note that some symbologies will not bedetected without multiple successful passes; it is usually better to combinethis setting with cropping to generate a number of closely clustered scanpasses in the target area.
Note that the density also affects the aspect ratio and rotation that can betolerated. If you set it too large, some barcodes will become more difficultto read.
In general, 2 to 4 is a good target for the stride setting, unless you havevery high or low resolution images.
Limiting the symbologies to the set of interest should provide a smallperformance boost. It also improves decode reliability - it is impossible toreceive an incorrect or unexpected decode result from a symbology that isdisabled.
The reader does support full auto-discrimination among the supportedsymbologies, but with all of them enabled you may need to compensate elsewhereto get a good frame rate.
For example, if you are only interested in QR codes, disable the others. Therobust way to do this is by disabling all symbologies and then reenablingonly those you want. This helps isolate you from encountering new symbologiesthat may be added in future versions of the library until you are ready tohandle them:
[scanner setSymbology: 0 config: ZBAR_CFG_ENABLE to: 0];[scanner setSymbology: ZBAR_QRCODE config: ZBAR_CFG_ENABLE to: 1];
Even if you would like your application to support multiple symbologies, youmay consider if there is a way to limit the enabled subset based on thescanning context, etc...
These examples demonstrate several scenarios for scanning from the camera withautomatic capture using iOS 4. You can try them yourself using thereadertest. For each example, start with the default settings (by tapping theZBarReaderViewController class), then enable continuous mode and thecustom overlay (by disablingshowsZBarControls). You should also usea release build and avoid running in the debugger.
Frame rates are approximate, measured on an iPhone 3GS running iOS 4.0.1 in awell lit room. Two measurements are taken for each sample: the rate with thecamera pointed at a blank white page such that it fills the frame, and therate while continuously decoding the provided example. For best results, itis recommended that you print the examples rather than scanning them from thescreen.
For reference, the base frame rates with default settings are 12fps for ablank white page, 7.5fps for this basic EAN symbol and 2.2fps for thisbasic QR symbol.
For this example, we will use a relatively long Code 128 barcode.
While it should be possible to read this symbol with the default settings, youmay notice that it is not very reliable. You will have to stretch the symbolacross the entire screen, and even then the default settings will only giveyou about 1.6 pixels per module, well below the ideal target of 3. To improvethese results, we want to maximize scanning resolution for the long imageaxis.
We should compensate for this reduction in the frame rate:
Since we have plenty of margin with the frame rate, we can minimize the totaldecode latency by performing more scan passes through the symbol:
You should now be able to quickly and reliably decode long linear symbols.
If have an iPhone 4, you may also try increasing the resolution to supporteven longer symbols (NB there is no readertest setting for resolution). Youmay have to compensate elsewhere to bring the frame rate back to a reasonablelevel.
For this example we will use a version 29 QR Code symbol.
In this case we still want to maximize the resolution, but we also need toincrease the scan density to reliably pick up the small finder patterns:
We can compensate somewhat for the reduced frame rate:
Even though the frame rate is still pretty bad, the QR recognition latencyshould be acceptable.
If have an iPhone 4, you may also try increasing the resolution to supporteven denser QR symbols (NB there is no readertest setting for resolution).You may have to compensate elsewhere to bring the frame rate back to areasonable level.
For this example we will use a DataBar symbol printed with a small featuresize, typical of the stickers used to tag produce. Scale it when printingsuch that the printed dimensions are about 1cm square. This symbol shouldscan with the default settings, but we will attempt to optimize the scanlatency for this case.
As well as high barcode resolution, we also want high density passes in bothdirections to minimize sensitivity to rotation:
Compensate for the reduction in frame rate by zooming in on the small symbol,which crops the scanned image. Zooming also helps the user see the smallbarcode:
The reader should now be very sensitive to DataBar, even when scanned at anangle.
联系客服