com.google.zxing.NotFoundException Java Examples

The following examples show how to use com.google.zxing.NotFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UPCEANReader.java    From reacteu-app with MIT License 6 votes vote down vote up
static int[] findStartGuardPattern(BitArray row) throws NotFoundException {
  boolean foundStart = false;
  int[] startRange = null;
  int nextStart = 0;
  int[] counters = new int[START_END_PATTERN.length];
  while (!foundStart) {
    Arrays.fill(counters, 0, START_END_PATTERN.length, 0);
    startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN, counters);
    int start = startRange[0];
    nextStart = startRange[1];
    // Make sure there is a quiet zone at least as big as the start pattern before the barcode.
    // If this check would run off the left edge of the image, do not accept this barcode,
    // as it is very likely to be a false positive.
    int quietStart = start - (nextStart - start);
    if (quietStart >= 0) {
      foundStart = row.isRange(quietStart, start, false);
    }
  }
  return startRange;
}
 
Example #2
Source File: MaxiCodeReader.java    From reacteu-app with MIT License 6 votes vote down vote up
@Override
public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
    throws NotFoundException, ChecksumException, FormatException {
  DecoderResult decoderResult;
  if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
    BitMatrix bits = extractPureBits(image.getBlackMatrix());
    decoderResult = decoder.decode(bits, hints);
  } else {
    throw NotFoundException.getNotFoundInstance();
  }

  ResultPoint[] points = NO_POINTS;
  Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.MAXICODE);

  String ecLevel = decoderResult.getECLevel();
  if (ecLevel != null) {
    result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
  }
  return result;
}
 
Example #3
Source File: Detector.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
/**
 * <p>Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.</p>
 *
 * @param image barcode image to decode
 * @param hints optional hints to detector
 * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will
 * be found and returned
 * @return {@link PDF417DetectorResult} encapsulating results of detecting a PDF417 code
 * @throws NotFoundException if no PDF417 Code can be found
 */
public static PDF417DetectorResult detect(BinaryBitmap image, Map<DecodeHintType,?> hints, boolean multiple)
    throws NotFoundException {
  // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even 
  // different binarizers
  //boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);

  BitMatrix bitMatrix = image.getBlackMatrix();

  List<ResultPoint[]> barcodeCoordinates = detect(multiple, bitMatrix);
  if (barcodeCoordinates.isEmpty()) {
    bitMatrix = bitMatrix.clone();
    bitMatrix.rotate180();
    barcodeCoordinates = detect(multiple, bitMatrix);
  }
  return new PDF417DetectorResult(bitMatrix, barcodeCoordinates);
}
 
Example #4
Source File: CodaBarReader.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
/**
 * Records the size of all runs of white and black pixels, starting with white.
 * This is just like recordPattern, except it records all the counters, and
 * uses our builtin "counters" member for storage.
 * @param row row to count from
 */
private void setCounters(BitArray row) throws NotFoundException {
  counterLength = 0;
  // Start from the first white bit.
  int i = row.getNextUnset(0);
  int end = row.getSize();
  if (i >= end) {
    throw NotFoundException.getNotFoundInstance();
  }
  boolean isWhite = true;
  int count = 0;
  while (i < end) {
    if (row.get(i) ^ isWhite) { // that is, exactly one is true
      count++;
    } else {
      counterAppend(count);
      count = 1;
      isWhite = !isWhite;
    }
    i++;
  }
  counterAppend(count);
}
 
Example #5
Source File: Detector.java    From QrCodeScanner with GNU General Public License v3.0 6 votes vote down vote up
/**
 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
 * of the finder patterns and estimated module size.</p>
 */
private static int computeDimension(ResultPoint topLeft,
                                    ResultPoint topRight,
                                    ResultPoint bottomLeft,
                                    float moduleSize) throws NotFoundException {
  int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
  int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
  int dimension = ((tltrCentersDimension + tlblCentersDimension) / 2) + 7;
  switch (dimension & 0x03) { // mod 4
    case 0:
      dimension++;
      break;
      // 1? do nothing
    case 2:
      dimension--;
      break;
    case 3:
      throw NotFoundException.getNotFoundInstance();
  }
  return dimension;
}
 
Example #6
Source File: Detector.java    From android-quick-response-code with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Computes the dimension (number of modules on a size) of the QR Code based
 * on the position of the finder patterns and estimated module size.
 * </p>
 */
protected static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize) throws NotFoundException {
    int tltrCentersDimension = round(ResultPoint.distance(topLeft, topRight) / moduleSize);
    int tlblCentersDimension = round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
    int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7;
    switch (dimension & 0x03) { // mod 4
    case 0:
        dimension++;
        break;
    // 1? do nothing
    case 2:
        dimension--;
        break;
    case 3:
        throw NotFoundException.getNotFoundInstance();
    }
    return dimension;
}
 
Example #7
Source File: PDF417ScanningDecoder.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
private static void adjustCodewordCount(DetectionResult detectionResult, BarcodeValue[][] barcodeMatrix)
    throws NotFoundException {
  int[] numberOfCodewords = barcodeMatrix[0][1].getValue();
  int calculatedNumberOfCodewords = detectionResult.getBarcodeColumnCount() *
      detectionResult.getBarcodeRowCount() -
      getNumberOfECCodeWords(detectionResult.getBarcodeECLevel());
  if (numberOfCodewords.length == 0) {
    if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE) {
      throw NotFoundException.getNotFoundInstance();
    }
    barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords);
  } else if (numberOfCodewords[0] != calculatedNumberOfCodewords) {
    // The calculated one is more reliable as it is derived from the row indicator columns
    barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords);
  }
}
 
Example #8
Source File: Detector.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
 * of the finder patterns and estimated module size.</p>
 */
private static int computeDimension(ResultPoint topLeft,
                                    ResultPoint topRight,
                                    ResultPoint bottomLeft,
                                    float moduleSize) throws NotFoundException {
  int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
  int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
  int dimension = ((tltrCentersDimension + tlblCentersDimension) / 2) + 7;
  switch (dimension & 0x03) { // mod 4
    case 0:
      dimension++;
      break;
      // 1? do nothing
    case 2:
      dimension--;
      break;
    case 3:
      throw NotFoundException.getNotFoundInstance();
  }
  return dimension;
}
 
Example #9
Source File: RSS14Reader.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
private FinderPattern parseFoundFinderPattern(BitArray row, int rowNumber, boolean right, int[] startEnd)
    throws NotFoundException {
  // Actually we found elements 2-5
  boolean firstIsBlack = row.get(startEnd[0]);
  int firstElementStart = startEnd[0] - 1;
  // Locate element 1
  while (firstElementStart >= 0 && firstIsBlack ^ row.get(firstElementStart)) {
    firstElementStart--;
  }
  firstElementStart++;
  int firstCounter = startEnd[0] - firstElementStart;
  // Make 'counters' hold 1-4
  int[] counters = getDecodeFinderCounters();
  System.arraycopy(counters, 0, counters, 1, counters.length - 1);
  counters[0] = firstCounter;
  int value = parseFinderValue(counters, FINDER_PATTERNS);
  int start = firstElementStart;
  int end = startEnd[1];
  if (right) {
    // row is actually reversed
    start = row.getSize() - 1 - start;
    end = row.getSize() - 1 - end;
  }
  return new FinderPattern(value, new int[] {firstElementStart, startEnd[1]}, start, end, rowNumber);
}
 
Example #10
Source File: MaxiCodeReader.java    From ZXing-Orient with Apache License 2.0 6 votes vote down vote up
/**
 * This method detects a code in a "pure" image -- that is, pure monochrome image
 * which contains only an unrotated, unskewed, image of a code, with some white border
 * around it. This is a specialized method that works exceptionally fast in this special
 * case.
 *
 * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)
 * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix)
 */
private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {
  
  int[] enclosingRectangle = image.getEnclosingRectangle();
  if (enclosingRectangle == null) {
    throw NotFoundException.getNotFoundInstance();
  }
  
  int left = enclosingRectangle[0];
  int top = enclosingRectangle[1];
  int width = enclosingRectangle[2];
  int height = enclosingRectangle[3];

  // Now just read off the bits
  BitMatrix bits = new BitMatrix(MATRIX_WIDTH, MATRIX_HEIGHT);
  for (int y = 0; y < MATRIX_HEIGHT; y++) {
    int iy = top + (y * height + height / 2) / MATRIX_HEIGHT;
    for (int x = 0; x < MATRIX_WIDTH; x++) {
      int ix = left + (x * width + width / 2 + (y & 0x01) *  width / 2) / MATRIX_WIDTH;
      if (image.get(ix, iy)) {
        bits.set(x, y);
      }
    }
  }
  return bits;
}
 
Example #11
Source File: Detector.java    From ScreenCapture with MIT License 6 votes vote down vote up
/**
 * <p>Computes the dimension (number of modules on a size) of the QR Code based on the position
 * of the finder patterns and estimated module size.</p>
 */
private static int computeDimension(ResultPoint topLeft,
                                    ResultPoint topRight,
                                    ResultPoint bottomLeft,
                                    float moduleSize) throws NotFoundException {
  int tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);
  int tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);
  int dimension = ((tltrCentersDimension + tlblCentersDimension) / 2) + 7;
  switch (dimension & 0x03) { // mod 4
    case 0:
      dimension++;
      break;
      // 1? do nothing
    case 2:
      dimension--;
      break;
    case 3:
      throw NotFoundException.getNotFoundInstance();
  }
  return dimension;
}
 
Example #12
Source File: QRCodeReader.java    From ScreenCapture with MIT License 6 votes vote down vote up
private static float moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException {
  int height = image.getHeight();
  int width = image.getWidth();
  int x = leftTopBlack[0];
  int y = leftTopBlack[1];
  boolean inBlack = true;
  int transitions = 0;
  while (x < width && y < height) {
    if (inBlack != image.get(x, y)) {
      if (++transitions == 5) {
        break;
      }
      inBlack = !inBlack;
    }
    x++;
    y++;
  }
  if (x == width || y == height) {
    throw NotFoundException.getNotFoundInstance();
  }
  return (x - leftTopBlack[0]) / 7.0f;
}
 
Example #13
Source File: GeneralAppIdDecoder.java    From weex with Apache License 2.0 6 votes vote down vote up
String decodeAllCodes(StringBuilder buff, int initialPosition) throws NotFoundException, FormatException {
  int currentPosition = initialPosition;
  String remaining = null;
  do{
    DecodedInformation info = this.decodeGeneralPurposeField(currentPosition, remaining);
    String parsedFields = FieldParser.parseFieldsInGeneralPurpose(info.getNewString());
    if (parsedFields != null) {
      buff.append(parsedFields);
    }
    if(info.isRemaining()) {
      remaining = String.valueOf(info.getRemainingValue());
    } else {
      remaining = null;
    }

    if(currentPosition == info.getNewPosition()) {// No step forward!
      break;
    }
    currentPosition = info.getNewPosition();
  }while(true);

  return buff.toString();
}
 
Example #14
Source File: RSSExpandedReader.java    From Tesseract-OCR-Scanner with Apache License 2.0 6 votes vote down vote up
static Result constructResult(List<ExpandedPair> pairs) throws NotFoundException, FormatException {
  BitArray binary = BitArrayBuilder.buildBitArray(pairs);

  AbstractExpandedDecoder decoder = AbstractExpandedDecoder.createDecoder(binary);
  String resultingString = decoder.parseInformation();

  ResultPoint[] firstPoints = pairs.get(0).getFinderPattern().getResultPoints();
  ResultPoint[] lastPoints  = pairs.get(pairs.size() - 1).getFinderPattern().getResultPoints();

  return new Result(
        resultingString,
        null,
        new ResultPoint[]{firstPoints[0], firstPoints[1], lastPoints[0], lastPoints[1]},
        BarcodeFormat.RSS_EXPANDED
    );
}
 
Example #15
Source File: CodaBarReader.java    From ScreenCapture with MIT License 6 votes vote down vote up
private int findStartPattern() throws NotFoundException {
  for (int i = 1; i < counterLength; i += 2) {
    int charOffset = toNarrowWidePattern(i);
    if (charOffset != -1 && arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) {
      // Look for whitespace before start pattern, >= 50% of width of start pattern
      // We make an exception if the whitespace is the first element.
      int patternSize = 0;
      for (int j = i; j < i + 7; j++) {
        patternSize += counters[j];
      }
      if (i == 1 || counters[i - 1] >= patternSize / 2) {
        return i;
      }
    }
  }
  throw NotFoundException.getNotFoundInstance();
}
 
Example #16
Source File: ITFReader.java    From QrCodeScanner with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Attempts to decode a sequence of ITF black/white lines into single
 * digit.
 *
 * @param counters the counts of runs of observed black/white/black/... values
 * @return The decoded digit
 * @throws NotFoundException if digit cannot be decoded
 */
private static int decodeDigit(int[] counters) throws NotFoundException {
  float bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
  int bestMatch = -1;
  int max = PATTERNS.length;
  for (int i = 0; i < max; i++) {
    int[] pattern = PATTERNS[i];
    float variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
    if (variance < bestVariance) {
      bestVariance = variance;
      bestMatch = i;
    }
  }
  if (bestMatch >= 0) {
    return bestMatch;
  } else {
    throw NotFoundException.getNotFoundInstance();
  }
}
 
Example #17
Source File: UPCEANExtension2Support.java    From ZXing-Orient with Apache License 2.0 6 votes vote down vote up
Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException {

    StringBuilder result = decodeRowStringBuffer;
    result.setLength(0);
    int end = decodeMiddle(row, extensionStartRange, result);

    String resultString = result.toString();
    Map<ResultMetadataType,Object> extensionData = parseExtensionString(resultString);

    Result extensionResult =
        new Result(resultString,
                   null,
                   new ResultPoint[] {
                       new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, (float) rowNumber),
                       new ResultPoint((float) end, (float) rowNumber),
                   },
                   BarcodeFormat.UPC_EAN_EXTENSION);
    if (extensionData != null) {
      extensionResult.putAllMetadata(extensionData);
    }
    return extensionResult;
  }
 
Example #18
Source File: UPCEANReader.java    From ZXing-Orient with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to decode a single UPC/EAN-encoded digit.
 *
 * @param row row of black/white values to decode
 * @param counters the counts of runs of observed black/white/black/... values
 * @param rowOffset horizontal offset to start decoding from
 * @param patterns the set of patterns to use to decode -- sometimes different encodings
 * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should
 * be used
 * @return horizontal offset of first pixel beyond the decoded digit
 * @throws NotFoundException if digit cannot be decoded
 */
static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns)
    throws NotFoundException {
  recordPattern(row, rowOffset, counters);
  float bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
  int bestMatch = -1;
  int max = patterns.length;
  for (int i = 0; i < max; i++) {
    int[] pattern = patterns[i];
    float variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
    if (variance < bestVariance) {
      bestVariance = variance;
      bestMatch = i;
    }
  }
  if (bestMatch >= 0) {
    return bestMatch;
  } else {
    throw NotFoundException.getNotFoundInstance();
  }
}
 
Example #19
Source File: CodaBarReader.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
/**
 * Records the size of all runs of white and black pixels, starting with
 * white. This is just like recordPattern, except it records all the
 * counters, and uses our builtin "counters" member for storage.
 * 
 * @param row
 *            row to count from
 */
private void setCounters(BitArray row) throws NotFoundException {
	counterLength = 0;
	// Start from the first white bit.
	int i = row.getNextUnset(0);
	int end = row.getSize();
	if (i >= end) {
		throw NotFoundException.getNotFoundInstance();
	}
	boolean isWhite = true;
	int count = 0;
	while (i < end) {
		if (row.get(i) ^ isWhite) { // that is, exactly one is true
			count++;
		} else {
			counterAppend(count);
			count = 1;
			isWhite = !isWhite;
		}
		i++;
	}
	counterAppend(count);
}
 
Example #20
Source File: CodaBarReader.java    From Tesseract-OCR-Scanner with Apache License 2.0 6 votes vote down vote up
/**
 * Records the size of all runs of white and black pixels, starting with white.
 * This is just like recordPattern, except it records all the counters, and
 * uses our builtin "counters" member for storage.
 * @param row row to count from
 */
private void setCounters(BitArray row) throws NotFoundException {
  counterLength = 0;
  // Start from the first white bit.
  int i = row.getNextUnset(0);
  int end = row.getSize();
  if (i >= end) {
    throw NotFoundException.getNotFoundInstance();
  }
  boolean isWhite = true;
  int count = 0;
  while (i < end) {
    if (row.get(i) != isWhite) {
      count++;
    } else {
      counterAppend(count);
      count = 1;
      isWhite = !isWhite;
    }
    i++;
  }
  counterAppend(count);
}
 
Example #21
Source File: MultiDetector.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
public DetectorResult[] detectMulti(Map<DecodeHintType,?> hints) throws NotFoundException {
  BitMatrix image = getImage();
  ResultPointCallback resultPointCallback =
      hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);
  MultiFinderPatternFinder finder = new MultiFinderPatternFinder(image, resultPointCallback);
  FinderPatternInfo[] infos = finder.findMulti(hints);

  if (infos.length == 0) {
    throw NotFoundException.getNotFoundInstance();
  }

  List<DetectorResult> result = new ArrayList<>();
  for (FinderPatternInfo info : infos) {
    try {
      result.add(processFinderPatternInfo(info));
    } catch (ReaderException e) {
      // ignore
    }
  }
  if (result.isEmpty()) {
    return EMPTY_DETECTOR_RESULTS;
  } else {
    return result.toArray(new DetectorResult[result.size()]);
  }
}
 
Example #22
Source File: QRCodeReader.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Override
public final Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
    throws NotFoundException, ChecksumException, FormatException {
  DecoderResult decoderResult;
  ResultPoint[] points;
  if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) {
    BitMatrix bits = extractPureBits(image.getBlackMatrix());
    decoderResult = decoder.decode(bits, hints);
    points = NO_POINTS;
  } else {
    DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints);
    decoderResult = decoder.decode(detectorResult.getBits(), hints);
    points = detectorResult.getPoints();
  }

  // If the code was mirrored: swap the bottom-left and the top-right points.
  if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {
    ((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points);
  }

  Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE);
  List<byte[]> byteSegments = decoderResult.getByteSegments();
  if (byteSegments != null) {
    result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
  }
  String ecLevel = decoderResult.getECLevel();
  if (ecLevel != null) {
    result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
  }
  if (decoderResult.hasStructuredAppend()) {
    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE,
                       decoderResult.getStructuredAppendSequenceNumber());
    result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY,
                       decoderResult.getStructuredAppendParity());
  }
  return result;
}
 
Example #23
Source File: Detector.java    From barcodescanner-lib-aar with MIT License 5 votes vote down vote up
/**
 * <p>Attempts to locate an alignment pattern in a limited region of the image, which is
 * guessed to contain it. This method uses {@link AlignmentPattern}.</p>
 *
 * @param overallEstModuleSize estimated module size so far
 * @param estAlignmentX x coordinate of center of area probably containing alignment pattern
 * @param estAlignmentY y coordinate of above
 * @param allowanceFactor number of pixels in all directions to search from the center
 * @return {@link AlignmentPattern} if found, or null otherwise
 * @throws NotFoundException if an unexpected error occurs during detection
 */
protected final AlignmentPattern findAlignmentInRegion(float overallEstModuleSize,
                                                       int estAlignmentX,
                                                       int estAlignmentY,
                                                       float allowanceFactor)
    throws NotFoundException {
  // Look for an alignment pattern (3 modules in size) around where it
  // should be
  int allowance = (int) (allowanceFactor * overallEstModuleSize);
  int alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);
  int alignmentAreaRightX = Math.min(image.getWidth() - 1, estAlignmentX + allowance);
  if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {
    throw NotFoundException.getNotFoundInstance();
  }

  int alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);
  int alignmentAreaBottomY = Math.min(image.getHeight() - 1, estAlignmentY + allowance);
  if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {
    throw NotFoundException.getNotFoundInstance();
  }

  AlignmentPatternFinder alignmentFinder =
      new AlignmentPatternFinder(
          image,
          alignmentAreaLeftX,
          alignmentAreaTopY,
          alignmentAreaRightX - alignmentAreaLeftX,
          alignmentAreaBottomY - alignmentAreaTopY,
          overallEstModuleSize,
          resultPointCallback);
  return alignmentFinder.find();
}
 
Example #24
Source File: HybridBinarizer.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the final BitMatrix once for all requests. This could be called once from the
 * constructor instead, but there are some advantages to doing it lazily, such as making
 * profiling easier, and not doing heavy lifting when callers don't expect it.
 */
@Override
public BitMatrix getBlackMatrix() throws NotFoundException {
  if (matrix != null) {
    return matrix;
  }
  LuminanceSource source = getLuminanceSource();
  int width = source.getWidth();
  int height = source.getHeight();
  if (width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION) {
    byte[] luminances = source.getMatrix();
    int subWidth = width >> BLOCK_SIZE_POWER;
    if ((width & BLOCK_SIZE_MASK) != 0) {
      subWidth++;
    }
    int subHeight = height >> BLOCK_SIZE_POWER;
    if ((height & BLOCK_SIZE_MASK) != 0) {
      subHeight++;
    }
    int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height);

    BitMatrix newMatrix = new BitMatrix(width, height);
    calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix);
    matrix = newMatrix;
  } else {
    // If the image is too small, fall back to the global histogram approach.
    matrix = super.getBlackMatrix();
  }
  return matrix;
}
 
Example #25
Source File: Detector.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
private static int getRotation(int[] sides, int length) throws NotFoundException {
  // In a normal pattern, we expect to See
  //   **    .*             D       A
  //   *      *
  //
  //   .      *
  //   ..    ..             C       B
  //
  // Grab the 3 bits from each of the sides the form the locator pattern and concatenate
  // into a 12-bit integer.  Start with the bit at A
  int cornerBits = 0;
  for (int side : sides) {
    // XX......X where X's are orientation marks
    int t = ((side >> (length - 2)) << 1) + (side & 1);
    cornerBits = (cornerBits << 3) + t;
  }
  // Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
  // together.  cornerBits is now:
  //  3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
  cornerBits = ((cornerBits & 1) << 11) + (cornerBits >> 1);
  // The result shift indicates which element of BullsEyeCorners[] goes into the top-left
  // corner. Since the four rotation values have a Hamming distance of 8, we
  // can easily tolerate two errors.
  for (int shift = 0; shift < 4; shift++) {
    if (Integer.bitCount(cornerBits ^ EXPECTED_CORNER_BITS[shift]) <= 2) {
      return shift;
    }
  }
  throw NotFoundException.getNotFoundInstance();
}
 
Example #26
Source File: GlobalHistogramBinarizer.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public BitArray getBlackRow(int y, BitArray row) throws NotFoundException {
  LuminanceSource source = getLuminanceSource();
  int width = source.getWidth();
  if (row == null || row.getSize() < width) {
    row = new BitArray(width);
  } else {
    row.clear();
  }

  initArrays(width);
  byte[] localLuminances = source.getRow(y, luminances);
  int[] localBuckets = buckets;
  for (int x = 0; x < width; x++) {
    localBuckets[(localLuminances[x] & 0xff) >> LUMINANCE_SHIFT]++;
  }
  int blackPoint = estimateBlackPoint(localBuckets);

  if (width < 3) {
    // Special case for very small images
    for (int x = 0; x < width; x++) {
      if ((localLuminances[x] & 0xff) < blackPoint) {
        row.set(x);
      }
    }
  } else {
    int left = localLuminances[0] & 0xff;
    int center = localLuminances[1] & 0xff;
    for (int x = 1; x < width - 1; x++) {
      int right = localLuminances[x + 1] & 0xff;
      // A simple -1 4 -1 box filter with a weight of 2.
      if (((center * 4) - left - right) / 2 < blackPoint) {
        row.set(x);
      }
      left = center;
      center = right;
    }
  }
  return row;
}
 
Example #27
Source File: Code39Reader.java    From ScreenCapture with MIT License 5 votes vote down vote up
private static int[] findAsteriskPattern(BitArray row, int[] counters) throws NotFoundException {
  int width = row.getSize();
  int rowOffset = row.getNextSet(0);

  int counterPosition = 0;
  int patternStart = rowOffset;
  boolean isWhite = false;
  int patternLength = counters.length;

  for (int i = rowOffset; i < width; i++) {
    if (row.get(i) != isWhite) {
      counters[counterPosition]++;
    } else {
      if (counterPosition == patternLength - 1) {
        // Look for whitespace before start pattern, >= 50% of width of start pattern
        if (toNarrowWidePattern(counters) == ASTERISK_ENCODING &&
            row.isRange(Math.max(0, patternStart - ((i - patternStart) / 2)), patternStart, false)) {
          return new int[]{patternStart, i};
        }
        patternStart += counters[0] + counters[1];
        System.arraycopy(counters, 2, counters, 0, counterPosition - 1);
        counters[counterPosition - 1] = 0;
        counters[counterPosition] = 0;
        counterPosition--;
      } else {
        counterPosition++;
      }
      counters[counterPosition] = 1;
      isWhite = !isWhite;
    }
  }
  throw NotFoundException.getNotFoundInstance();
}
 
Example #28
Source File: Detector.java    From reacteu-app with MIT License 5 votes vote down vote up
private static BitMatrix sampleGrid(BitMatrix image,
                                    PerspectiveTransform transform,
                                    int dimension) throws NotFoundException {

  GridSampler sampler = GridSampler.getInstance();
  return sampler.sampleGrid(image, dimension, dimension, transform);
}
 
Example #29
Source File: AI013x0x1xDecoder.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException {
  if (this.getInformation().getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE + DATE_SIZE) {
    throw NotFoundException.getNotFoundInstance();
  }

  StringBuilder buf = new StringBuilder();

  encodeCompressedGtin(buf, HEADER_SIZE);
  encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE);
  encodeCompressedDate(buf, HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE);

  return buf.toString();
}
 
Example #30
Source File: AI013x0xDecoder.java    From QrCodeScanner with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException {
  if (this.getInformation().getSize() != HEADER_SIZE + GTIN_SIZE + WEIGHT_SIZE) {
    throw NotFoundException.getNotFoundInstance();
  }

  StringBuilder buf = new StringBuilder();

  encodeCompressedGtin(buf, HEADER_SIZE);
  encodeCompressedWeight(buf, HEADER_SIZE + GTIN_SIZE, WEIGHT_SIZE);

  return buf.toString();
}