Search in sources :

Example 26 with ReaderException

use of com.google.zxing.ReaderException in project zxing by zxing.

the class GUIRunner method getDecodeText.

private static String getDecodeText(Path file) {
    BufferedImage image;
    try {
        image = ImageReader.readImage(file.toUri());
    } catch (IOException ioe) {
        return ioe.toString();
    }
    LuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    Result result;
    try {
        result = new MultiFormatReader().decode(bitmap);
    } catch (ReaderException re) {
        return re.toString();
    }
    return String.valueOf(result.getText());
}
Also used : MultiFormatReader(com.google.zxing.MultiFormatReader) LuminanceSource(com.google.zxing.LuminanceSource) IOException(java.io.IOException) BinaryBitmap(com.google.zxing.BinaryBitmap) HybridBinarizer(com.google.zxing.common.HybridBinarizer) BufferedImage(java.awt.image.BufferedImage) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 27 with ReaderException

use of com.google.zxing.ReaderException in project zxing by zxing.

the class AbstractBlackBoxTestCase method testBlackBoxCountingResults.

private void testBlackBoxCountingResults(boolean assertOnFailure) throws IOException {
    assertFalse(testResults.isEmpty());
    List<Path> imageFiles = getImageFiles();
    int testCount = testResults.size();
    int[] passedCounts = new int[testCount];
    int[] misreadCounts = new int[testCount];
    int[] tryHarderCounts = new int[testCount];
    int[] tryHarderMisreadCounts = new int[testCount];
    for (Path testImage : imageFiles) {
        log.info(String.format("Starting %s", testImage));
        BufferedImage image = ImageIO.read(testImage.toFile());
        String testImageFileName = testImage.getFileName().toString();
        String fileBaseName = testImageFileName.substring(0, testImageFileName.indexOf('.'));
        Path expectedTextFile = testBase.resolve(fileBaseName + ".txt");
        String expectedText;
        if (Files.exists(expectedTextFile)) {
            expectedText = readFileAsString(expectedTextFile, StandardCharsets.UTF_8);
        } else {
            expectedTextFile = testBase.resolve(fileBaseName + ".bin");
            assertTrue(Files.exists(expectedTextFile));
            expectedText = readFileAsString(expectedTextFile, StandardCharsets.ISO_8859_1);
        }
        Path expectedMetadataFile = testBase.resolve(fileBaseName + ".metadata.txt");
        Properties expectedMetadata = new Properties();
        if (Files.exists(expectedMetadataFile)) {
            try (BufferedReader reader = Files.newBufferedReader(expectedMetadataFile, StandardCharsets.UTF_8)) {
                expectedMetadata.load(reader);
            }
        }
        for (int x = 0; x < testCount; x++) {
            float rotation = testResults.get(x).getRotation();
            BufferedImage rotatedImage = rotateImage(image, rotation);
            LuminanceSource source = new BufferedImageLuminanceSource(rotatedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            try {
                if (decode(bitmap, rotation, expectedText, expectedMetadata, false)) {
                    passedCounts[x]++;
                } else {
                    misreadCounts[x]++;
                }
            } catch (ReaderException ignored) {
                log.fine(String.format("could not read at rotation %f", rotation));
            }
            try {
                if (decode(bitmap, rotation, expectedText, expectedMetadata, true)) {
                    tryHarderCounts[x]++;
                } else {
                    tryHarderMisreadCounts[x]++;
                }
            } catch (ReaderException ignored) {
                log.fine(String.format("could not read at rotation %f w/TH", rotation));
            }
        }
    }
    // Print the results of all tests first
    int totalFound = 0;
    int totalMustPass = 0;
    int totalMisread = 0;
    int totalMaxMisread = 0;
    for (int x = 0; x < testResults.size(); x++) {
        TestResult testResult = testResults.get(x);
        log.info(String.format("Rotation %d degrees:", (int) testResult.getRotation()));
        log.info(String.format(" %d of %d images passed (%d required)", passedCounts[x], imageFiles.size(), testResult.getMustPassCount()));
        int failed = imageFiles.size() - passedCounts[x];
        log.info(String.format(" %d failed due to misreads, %d not detected", misreadCounts[x], failed - misreadCounts[x]));
        log.info(String.format(" %d of %d images passed with try harder (%d required)", tryHarderCounts[x], imageFiles.size(), testResult.getTryHarderCount()));
        failed = imageFiles.size() - tryHarderCounts[x];
        log.info(String.format(" %d failed due to misreads, %d not detected", tryHarderMisreadCounts[x], failed - tryHarderMisreadCounts[x]));
        totalFound += passedCounts[x] + tryHarderCounts[x];
        totalMustPass += testResult.getMustPassCount() + testResult.getTryHarderCount();
        totalMisread += misreadCounts[x] + tryHarderMisreadCounts[x];
        totalMaxMisread += testResult.getMaxMisreads() + testResult.getMaxTryHarderMisreads();
    }
    int totalTests = imageFiles.size() * testCount * 2;
    log.info(String.format("Decoded %d images out of %d (%d%%, %d required)", totalFound, totalTests, totalFound * 100 / totalTests, totalMustPass));
    if (totalFound > totalMustPass) {
        log.warning(String.format("+++ Test too lax by %d images", totalFound - totalMustPass));
    } else if (totalFound < totalMustPass) {
        log.warning(String.format("--- Test failed by %d images", totalMustPass - totalFound));
    }
    if (totalMisread < totalMaxMisread) {
        log.warning(String.format("+++ Test expects too many misreads by %d images", totalMaxMisread - totalMisread));
    } else if (totalMisread > totalMaxMisread) {
        log.warning(String.format("--- Test had too many misreads by %d images", totalMisread - totalMaxMisread));
    }
    // Then run through again and assert if any failed
    if (assertOnFailure) {
        for (int x = 0; x < testCount; x++) {
            TestResult testResult = testResults.get(x);
            String label = "Rotation " + testResult.getRotation() + " degrees: Too many images failed";
            assertTrue(label, passedCounts[x] >= testResult.getMustPassCount());
            assertTrue("Try harder, " + label, tryHarderCounts[x] >= testResult.getTryHarderCount());
            label = "Rotation " + testResult.getRotation() + " degrees: Too many images misread";
            assertTrue(label, misreadCounts[x] <= testResult.getMaxMisreads());
            assertTrue("Try harder, " + label, tryHarderMisreadCounts[x] <= testResult.getMaxTryHarderMisreads());
        }
    }
}
Also used : Path(java.nio.file.Path) Properties(java.util.Properties) BufferedImage(java.awt.image.BufferedImage) ReaderException(com.google.zxing.ReaderException) LuminanceSource(com.google.zxing.LuminanceSource) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) BufferedReader(java.io.BufferedReader) BinaryBitmap(com.google.zxing.BinaryBitmap)

Example 28 with ReaderException

use of com.google.zxing.ReaderException in project zxing by zxing.

the class PDF417BlackBox4TestCase method testPDF417BlackBoxCountingResults.

private void testPDF417BlackBoxCountingResults(boolean assertOnFailure) throws IOException {
    assertFalse(testResults.isEmpty());
    Map<String, List<Path>> imageFiles = getImageFileLists();
    int testCount = testResults.size();
    int[] passedCounts = new int[testCount];
    int[] tryHarderCounts = new int[testCount];
    Path testBase = getTestBase();
    for (Entry<String, List<Path>> testImageGroup : imageFiles.entrySet()) {
        log.fine(String.format("Starting Image Group %s", testImageGroup.getKey()));
        String fileBaseName = testImageGroup.getKey();
        String expectedText;
        Path expectedTextFile = testBase.resolve(fileBaseName + ".txt");
        if (Files.exists(expectedTextFile)) {
            expectedText = readFileAsString(expectedTextFile, StandardCharsets.UTF_8);
        } else {
            expectedTextFile = testBase.resolve(fileBaseName + ".bin");
            assertTrue(Files.exists(expectedTextFile));
            expectedText = readFileAsString(expectedTextFile, StandardCharsets.ISO_8859_1);
        }
        for (int x = 0; x < testCount; x++) {
            List<Result> results = new ArrayList<>();
            for (Path imageFile : testImageGroup.getValue()) {
                BufferedImage image = ImageIO.read(imageFile.toFile());
                float rotation = testResults.get(x).getRotation();
                BufferedImage rotatedImage = rotateImage(image, rotation);
                LuminanceSource source = new BufferedImageLuminanceSource(rotatedImage);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                try {
                    results.addAll(Arrays.asList(decode(bitmap, false)));
                } catch (ReaderException ignored) {
                // ignore
                }
            }
            Collections.sort(results, new Comparator<Result>() {

                @Override
                public int compare(Result arg0, Result arg1) {
                    PDF417ResultMetadata resultMetadata = getMeta(arg0);
                    PDF417ResultMetadata otherResultMetadata = getMeta(arg1);
                    return resultMetadata.getSegmentIndex() - otherResultMetadata.getSegmentIndex();
                }
            });
            StringBuilder resultText = new StringBuilder();
            String fileId = null;
            for (Result result : results) {
                PDF417ResultMetadata resultMetadata = getMeta(result);
                assertNotNull("resultMetadata", resultMetadata);
                if (fileId == null) {
                    fileId = resultMetadata.getFileId();
                }
                assertEquals("FileId", fileId, resultMetadata.getFileId());
                resultText.append(result.getText());
            }
            assertEquals("ExpectedText", expectedText, resultText.toString());
            passedCounts[x]++;
            tryHarderCounts[x]++;
        }
    }
    // Print the results of all tests first
    int totalFound = 0;
    int totalMustPass = 0;
    int numberOfTests = imageFiles.keySet().size();
    for (int x = 0; x < testResults.size(); x++) {
        TestResult testResult = testResults.get(x);
        log.info(String.format("Rotation %d degrees:", (int) testResult.getRotation()));
        log.info(String.format(" %d of %d images passed (%d required)", passedCounts[x], numberOfTests, testResult.getMustPassCount()));
        log.info(String.format(" %d of %d images passed with try harder (%d required)", tryHarderCounts[x], numberOfTests, testResult.getTryHarderCount()));
        totalFound += passedCounts[x] + tryHarderCounts[x];
        totalMustPass += testResult.getMustPassCount() + testResult.getTryHarderCount();
    }
    int totalTests = numberOfTests * testCount * 2;
    log.info(String.format("Decoded %d images out of %d (%d%%, %d required)", totalFound, totalTests, totalFound * 100 / totalTests, totalMustPass));
    if (totalFound > totalMustPass) {
        log.warning(String.format("+++ Test too lax by %d images", totalFound - totalMustPass));
    } else if (totalFound < totalMustPass) {
        log.warning(String.format("--- Test failed by %d images", totalMustPass - totalFound));
    }
    // Then run through again and assert if any failed
    if (assertOnFailure) {
        for (int x = 0; x < testCount; x++) {
            TestResult testResult = testResults.get(x);
            String label = "Rotation " + testResult.getRotation() + " degrees: Too many images failed";
            assertTrue(label, passedCounts[x] >= testResult.getMustPassCount());
            assertTrue("Try harder, " + label, tryHarderCounts[x] >= testResult.getTryHarderCount());
        }
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) TestResult(com.google.zxing.common.TestResult) HybridBinarizer(com.google.zxing.common.HybridBinarizer) BufferedImage(java.awt.image.BufferedImage) Result(com.google.zxing.Result) TestResult(com.google.zxing.common.TestResult) ReaderException(com.google.zxing.ReaderException) LuminanceSource(com.google.zxing.LuminanceSource) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) BufferedImageLuminanceSource(com.google.zxing.BufferedImageLuminanceSource) ArrayList(java.util.ArrayList) List(java.util.List) BinaryBitmap(com.google.zxing.BinaryBitmap)

Example 29 with ReaderException

use of com.google.zxing.ReaderException in project zxing by zxing.

the class OneDReader method doDecode.

/**
   * We're going to examine rows from the middle outward, searching alternately above and below the
   * middle, and farther out each time. rowStep is the number of rows between each successive
   * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
   * middle + rowStep, then middle - (2 * rowStep), etc.
   * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
   * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
   * image if "trying harder".
   *
   * @param image The image to decode
   * @param hints Any hints that were requested
   * @return The contents of the decoded barcode
   * @throws NotFoundException Any spontaneous errors which occur
   */
private Result doDecode(BinaryBitmap image, Map<DecodeHintType, ?> hints) throws NotFoundException {
    int width = image.getWidth();
    int height = image.getHeight();
    BitArray row = new BitArray(width);
    boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
    int rowStep = Math.max(1, height >> (tryHarder ? 8 : 5));
    int maxLines;
    if (tryHarder) {
        // Look at the whole image, not just the center
        maxLines = height;
    } else {
        // 15 rows spaced 1/32 apart is roughly the middle half of the image
        maxLines = 15;
    }
    int middle = height / 2;
    for (int x = 0; x < maxLines; x++) {
        // Scanning from the middle out. Determine which row we're looking at next:
        int rowStepsAboveOrBelow = (x + 1) / 2;
        // i.e. is x even?
        boolean isAbove = (x & 0x01) == 0;
        int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
        if (rowNumber < 0 || rowNumber >= height) {
            // Oops, if we run off the top or bottom, stop
            break;
        }
        // Estimate black point for this row and load it:
        try {
            row = image.getBlackRow(rowNumber, row);
        } catch (NotFoundException ignored) {
            continue;
        }
        // handle decoding upside down barcodes.
        for (int attempt = 0; attempt < 2; attempt++) {
            if (attempt == 1) {
                // trying again?
                // reverse the row and continue
                row.reverse();
                // that start on the center line.
                if (hints != null && hints.containsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) {
                    Map<DecodeHintType, Object> newHints = new EnumMap<>(DecodeHintType.class);
                    newHints.putAll(hints);
                    newHints.remove(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
                    hints = newHints;
                }
            }
            try {
                // Look for a barcode
                Result result = decodeRow(rowNumber, row, hints);
                // We found our barcode
                if (attempt == 1) {
                    // But it was upside down, so note that
                    result.putMetadata(ResultMetadataType.ORIENTATION, 180);
                    // And remember to flip the result points horizontally.
                    ResultPoint[] points = result.getResultPoints();
                    if (points != null) {
                        points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());
                        points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());
                    }
                }
                return result;
            } catch (ReaderException re) {
            // continue -- just couldn't decode this row
            }
        }
    }
    throw NotFoundException.getNotFoundInstance();
}
Also used : ResultPoint(com.google.zxing.ResultPoint) DecodeHintType(com.google.zxing.DecodeHintType) NotFoundException(com.google.zxing.NotFoundException) BitArray(com.google.zxing.common.BitArray) EnumMap(java.util.EnumMap) ResultPoint(com.google.zxing.ResultPoint) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Example 30 with ReaderException

use of com.google.zxing.ReaderException in project QRCode by 5peak2me.

the class DecodeHandler method decode.

/**
	 * Decode the data within the viewfinder rectangle, and time how long it
	 * took. For efficiency, reuse the same reader objects from one decode to
	 * the next.
	 * 
	 * @param data
	 *            The YUV preview frame.
	 * @param width
	 *            The width of the preview frame.
	 * @param height
	 *            The height of the preview frame.
	 */
private void decode(byte[] data, int width, int height) {
    long start = System.currentTimeMillis();
    Result rawResult = null;
    // modify here
    byte[] rotatedData = new byte[data.length];
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) rotatedData[x * height + height - y - 1] = data[x + y * width];
    }
    // Here we are swapping, that's the difference to #11
    int tmp = width;
    width = height;
    height = tmp;
    PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(rotatedData, width, height);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    try {
        rawResult = multiFormatReader.decodeWithState(bitmap);
    } catch (ReaderException re) {
    // continue
    } finally {
        multiFormatReader.reset();
    }
    if (rawResult != null) {
        long end = System.currentTimeMillis();
        Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n" + rawResult.toString());
        Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, rawResult);
        Bundle bundle = new Bundle();
        bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap());
        message.setData(bundle);
        // Log.d(TAG, "Sending decode succeeded message...");
        message.sendToTarget();
    } else {
        Message message = Message.obtain(activity.getHandler(), R.id.decode_failed);
        message.sendToTarget();
    }
}
Also used : Message(android.os.Message) PlanarYUVLuminanceSource(com.google.zxing.zxing.camera.PlanarYUVLuminanceSource) Bundle(android.os.Bundle) BinaryBitmap(com.google.zxing.BinaryBitmap) HybridBinarizer(com.google.zxing.common.HybridBinarizer) Result(com.google.zxing.Result) ReaderException(com.google.zxing.ReaderException)

Aggregations

ReaderException (com.google.zxing.ReaderException)39 Result (com.google.zxing.Result)35 BinaryBitmap (com.google.zxing.BinaryBitmap)26 HybridBinarizer (com.google.zxing.common.HybridBinarizer)21 Bundle (android.os.Bundle)13 Message (android.os.Message)13 PlanarYUVLuminanceSource (com.google.zxing.PlanarYUVLuminanceSource)9 Handler (android.os.Handler)8 ResultPoint (com.google.zxing.ResultPoint)8 BufferedImage (java.awt.image.BufferedImage)7 BufferedImageLuminanceSource (com.google.zxing.BufferedImageLuminanceSource)6 ArrayList (java.util.ArrayList)6 LuminanceSource (com.google.zxing.LuminanceSource)5 MultiFormatReader (com.google.zxing.MultiFormatReader)5 BitArray (com.google.zxing.common.BitArray)5 Path (java.nio.file.Path)5 BarcodeFormat (com.google.zxing.BarcodeFormat)4 DecodeHintType (com.google.zxing.DecodeHintType)4 ResultPointCallback (com.google.zxing.ResultPointCallback)4 DetectorResult (com.google.zxing.common.DetectorResult)4