Java Code Examples for com.google.zxing.NotFoundException#getNotFoundInstance()

The following examples show how to use com.google.zxing.NotFoundException#getNotFoundInstance() . 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 RipplePower 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 2
Source File: AI01392xDecoder.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException, FormatException {
  if (this.getInformation().getSize() < HEADER_SIZE + GTIN_SIZE) {
    throw NotFoundException.getNotFoundInstance();
  }

  StringBuilder buf = new StringBuilder();

  encodeCompressedGtin(buf, HEADER_SIZE);

  int lastAIdigit =
      this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE);
  buf.append("(392");
  buf.append(lastAIdigit);
  buf.append(')');

  DecodedInformation decodedInformation =
      this.getGeneralDecoder().decodeGeneralPurposeField(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, null);
  buf.append(decodedInformation.getNewString());

  return buf.toString();
}
 
Example 3
Source File: AI01392xDecoder.java    From ScreenCapture with MIT License 6 votes vote down vote up
@Override
public String parseInformation() throws NotFoundException, FormatException {
  if (this.getInformation().getSize() < HEADER_SIZE + GTIN_SIZE) {
    throw NotFoundException.getNotFoundInstance();
  }

  StringBuilder buf = new StringBuilder();

  encodeCompressedGtin(buf, HEADER_SIZE);

  int lastAIdigit =
      this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE + GTIN_SIZE, LAST_DIGIT_SIZE);
  buf.append("(392");
  buf.append(lastAIdigit);
  buf.append(')');

  DecodedInformation decodedInformation =
      this.getGeneralDecoder().decodeGeneralPurposeField(HEADER_SIZE + GTIN_SIZE + LAST_DIGIT_SIZE, null);
  buf.append(decodedInformation.getNewString());

  return buf.toString();
}
 
Example 4
Source File: Detector.java    From barcodescanner-lib-aar with MIT License 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 5
Source File: RSSExpandedReader.java    From ScreenCapture with MIT License 5 votes vote down vote up
ExpandedPair retrieveNextPair(BitArray row, List<ExpandedPair> previousPairs, int rowNumber)
    throws NotFoundException {
  boolean isOddPattern  = previousPairs.size() % 2 == 0;
  if (startFromEven) {
    isOddPattern = !isOddPattern;
  }

  FinderPattern pattern;

  boolean keepFinding = true;
  int forcedOffset = -1;
  do {
    this.findNextPair(row, previousPairs, forcedOffset);
    pattern = parseFoundFinderPattern(row, rowNumber, isOddPattern);
    if (pattern == null) {
      forcedOffset = getNextSecondBar(row, this.startEnd[0]);
    } else {
      keepFinding = false;
    }
  } while (keepFinding);

  // When stacked symbol is split over multiple rows, there's no way to guess if this pair can be last or not.
  // boolean mayBeLast = checkPairSequence(previousPairs, pattern);

  DataCharacter leftChar  = this.decodeDataCharacter(row, pattern, isOddPattern, true);

  if (!previousPairs.isEmpty() && previousPairs.get(previousPairs.size() - 1).mustBeLast()) {
    throw NotFoundException.getNotFoundInstance();
  }

  DataCharacter rightChar;
  try {
    rightChar = this.decodeDataCharacter(row, pattern, isOddPattern, false);
  } catch (NotFoundException ignored) {
    rightChar = null;
  }
  return new ExpandedPair(leftChar, rightChar, pattern, true);
}
 
Example 6
Source File: AI013x0x1xDecoder.java    From reacteu-app with MIT License 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 7
Source File: UPCEANExtension5Support.java    From reacteu-app with MIT License 5 votes vote down vote up
int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException {
  int[] counters = decodeMiddleCounters;
  counters[0] = 0;
  counters[1] = 0;
  counters[2] = 0;
  counters[3] = 0;
  int end = row.getSize();
  int rowOffset = startRange[1];

  int lgPatternFound = 0;

  for (int x = 0; x < 5 && rowOffset < end; x++) {
    int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS);
    resultString.append((char) ('0' + bestMatch % 10));
    for (int counter : counters) {
      rowOffset += counter;
    }
    if (bestMatch >= 10) {
      lgPatternFound |= 1 << (4 - x);
    }
    if (x != 4) {
      // Read off separator if not last
      rowOffset = row.getNextSet(rowOffset);
      rowOffset = row.getNextUnset(rowOffset);
    }
  }

  if (resultString.length() != 5) {
    throw NotFoundException.getNotFoundInstance();
  }

  int checkDigit = determineCheckDigit(lgPatternFound);
  if (extensionChecksum(resultString.toString()) != checkDigit) {
    throw NotFoundException.getNotFoundInstance();
  }
  
  return rowOffset;
}
 
Example 8
Source File: UPCEANReader.java    From QrCodeScanner with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param row row of black/white values to search
 * @param rowOffset position to start search
 * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...
 * pixel counts, otherwise, it is interpreted as black/white/black/...
 * @param pattern pattern of counts of number of black and white pixels that are being
 * searched for as a pattern
 * @param counters array of counters, as long as pattern, to re-use
 * @return start/end horizontal offset of guard pattern, as an array of two ints
 * @throws NotFoundException if pattern is not found
 */
private static int[] findGuardPattern(BitArray row,
                                      int rowOffset,
                                      boolean whiteFirst,
                                      int[] pattern,
                                      int[] counters) throws NotFoundException {
  int width = row.getSize();
  rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset);
  int counterPosition = 0;
  int patternStart = rowOffset;
  int patternLength = pattern.length;
  boolean isWhite = whiteFirst;
  for (int x = rowOffset; x < width; x++) {
    if (row.get(x) != isWhite) {
      counters[counterPosition]++;
    } else {
      if (counterPosition == patternLength - 1) {
        if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
          return new int[]{patternStart, x};
        }
        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 9
Source File: Code39Reader.java    From Tesseract-OCR-Scanner with Apache License 2.0 5 votes vote down vote up
private static char patternToChar(int pattern) throws NotFoundException {
  for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
    if (CHARACTER_ENCODINGS[i] == pattern) {
      return ALPHABET_STRING.charAt(i);
    }
  }
  throw NotFoundException.getNotFoundInstance();
}
 
Example 10
Source File: MultiFormatUPCEANReader.java    From barcodescanner-lib-aar with MIT License 4 votes vote down vote up
@Override
public Result decodeRow(int rowNumber,
                        BitArray row,
                        Map<DecodeHintType,?> hints) throws NotFoundException {
  // Compute this location once and reuse it on multiple implementations
  int[] startGuardPattern = UPCEANReader.findStartGuardPattern(row);
  for (UPCEANReader reader : readers) {
    Result result;
    try {
      result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);
    } catch (ReaderException ignored) {
      continue;
    }
    // Special case: a 12-digit code encoded in UPC-A is identical to a "0"
    // followed by those 12 digits encoded as EAN-13. Each will recognize such a code,
    // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0".
    // Individually these are correct and their readers will both read such a code
    // and correctly call it EAN-13, or UPC-A, respectively.
    //
    // In this case, if we've been looking for both types, we'd like to call it
    // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read
    // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A
    // result if appropriate.
    //
    // But, don't return UPC-A if UPC-A was not a requested format!
    boolean ean13MayBeUPCA =
        result.getBarcodeFormat() == BarcodeFormat.EAN_13 &&
            result.getText().charAt(0) == '0';
    @SuppressWarnings("unchecked")      
    Collection<BarcodeFormat> possibleFormats =
        hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS);
    boolean canReturnUPCA = possibleFormats == null || possibleFormats.contains(BarcodeFormat.UPC_A);

    if (ean13MayBeUPCA && canReturnUPCA) {
      // Transfer the metdata across
      Result resultUPCA = new Result(result.getText().substring(1),
                                     result.getRawBytes(),
                                     result.getResultPoints(),
                                     BarcodeFormat.UPC_A);
      resultUPCA.putAllMetadata(result.getResultMetadata());
      return resultUPCA;
    }
    return result;
  }

  throw NotFoundException.getNotFoundInstance();
}
 
Example 11
Source File: Code128Reader.java    From ScreenCapture with MIT License 4 votes vote down vote up
private static int[] findStartPattern(BitArray row) throws NotFoundException {
  int width = row.getSize();
  int rowOffset = row.getNextSet(0);

  int counterPosition = 0;
  int[] counters = new int[6];
  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) {
        float bestVariance = MAX_AVG_VARIANCE;
        int bestMatch = -1;
        for (int startCode = CODE_START_A; startCode <= CODE_START_C; startCode++) {
          float variance = patternMatchVariance(counters, CODE_PATTERNS[startCode],
              MAX_INDIVIDUAL_VARIANCE);
          if (variance < bestVariance) {
            bestVariance = variance;
            bestMatch = startCode;
          }
        }
        // Look for whitespace before start pattern, >= 50% of width of start pattern
        if (bestMatch >= 0 &&
            row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
          return new int[]{patternStart, i, bestMatch};
        }
        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 12
Source File: RSSExpandedReader.java    From ZXing-Orient with Apache License 2.0 4 votes vote down vote up
private void adjustOddEvenCounts(int numModules) throws NotFoundException {

    int oddSum = count(this.getOddCounts());
    int evenSum = count(this.getEvenCounts());
    int mismatch = oddSum + evenSum - numModules;
    boolean oddParityBad = (oddSum & 0x01) == 1;
    boolean evenParityBad = (evenSum & 0x01) == 0;

    boolean incrementOdd = false;
    boolean decrementOdd = false;

    if (oddSum > 13) {
      decrementOdd = true;
    } else if (oddSum < 4) {
      incrementOdd = true;
    }
    boolean incrementEven = false;
    boolean decrementEven = false;
    if (evenSum > 13) {
      decrementEven = true;
    } else if (evenSum < 4) {
      incrementEven = true;
    }

    if (mismatch == 1) {
      if (oddParityBad) {
        if (evenParityBad) {
          throw NotFoundException.getNotFoundInstance();
        }
        decrementOdd = true;
      } else {
        if (!evenParityBad) {
          throw NotFoundException.getNotFoundInstance();
        }
        decrementEven = true;
      }
    } else if (mismatch == -1) {
      if (oddParityBad) {
        if (evenParityBad) {
          throw NotFoundException.getNotFoundInstance();
        }
        incrementOdd = true;
      } else {
        if (!evenParityBad) {
          throw NotFoundException.getNotFoundInstance();
        }
        incrementEven = true;
      }
    } else if (mismatch == 0) {
      if (oddParityBad) {
        if (!evenParityBad) {
          throw NotFoundException.getNotFoundInstance();
        }
        // Both bad
        if (oddSum < evenSum) {
          incrementOdd = true;
          decrementEven = true;
        } else {
          decrementOdd = true;
          incrementEven = true;
        }
      } else {
        if (evenParityBad) {
          throw NotFoundException.getNotFoundInstance();
        }
        // Nothing to do!
      }
    } else {
      throw NotFoundException.getNotFoundInstance();
    }

    if (incrementOdd) {
      if (decrementOdd) {
        throw NotFoundException.getNotFoundInstance();
      }
      increment(this.getOddCounts(), this.getOddRoundingErrors());
    }
    if (decrementOdd) {
      decrement(this.getOddCounts(), this.getOddRoundingErrors());
    }
    if (incrementEven) {
      if (decrementEven) {
        throw NotFoundException.getNotFoundInstance();
      }
      increment(this.getEvenCounts(), this.getOddRoundingErrors());
    }
    if (decrementEven) {
      decrement(this.getEvenCounts(), this.getEvenRoundingErrors());
    }
  }
 
Example 13
Source File: Detector.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
private void a(b ab[])
{
    int i = 0;
    boolean aflag[] = a(ab[0], ab[1], 1 + 2 * e);
    boolean aflag1[] = a(ab[1], ab[2], 1 + 2 * e);
    boolean aflag2[] = a(ab[2], ab[3], 1 + 2 * e);
    boolean aflag3[] = a(ab[3], ab[0], 1 + 2 * e);
    if (aflag[0] && aflag[2 * e])
    {
        f = 0;
    } else
    if (aflag1[0] && aflag1[2 * e])
    {
        f = 1;
    } else
    if (aflag2[0] && aflag2[2 * e])
    {
        f = 2;
    } else
    if (aflag3[0] && aflag3[2 * e])
    {
        f = 3;
    } else
    {
        throw NotFoundException.getNotFoundInstance();
    }
    boolean aflag5[];
    if (b)
    {
        boolean aflag6[] = new boolean[28];
        for (int k = 0; k < 7; k++)
        {
            aflag6[k] = aflag[k + 2];
            aflag6[k + 7] = aflag1[k + 2];
            aflag6[k + 14] = aflag2[k + 2];
            aflag6[k + 21] = aflag3[k + 2];
        }

        aflag5 = new boolean[28];
        for (; i < 28; i++)
        {
            aflag5[i] = aflag6[(i + 7 * f) % 28];
        }

    } else
    {
        boolean aflag4[] = new boolean[40];
        for (int j = 0; j < 11; j++)
        {
            if (j < 5)
            {
                aflag4[j] = aflag[j + 2];
                aflag4[j + 10] = aflag1[j + 2];
                aflag4[j + 20] = aflag2[j + 2];
                aflag4[j + 30] = aflag3[j + 2];
            }
            if (j > 5)
            {
                aflag4[j - 1] = aflag[j + 2];
                aflag4[-1 + (j + 10)] = aflag1[j + 2];
                aflag4[-1 + (j + 20)] = aflag2[j + 2];
                aflag4[-1 + (j + 30)] = aflag3[j + 2];
            }
        }

        aflag5 = new boolean[40];
        for (; i < 40; i++)
        {
            aflag5[i] = aflag4[(i + 10 * f) % 40];
        }

    }
    a(aflag5, b);
    a(aflag5);
}
 
Example 14
Source File: Detector.java    From ScreenCapture with MIT License 4 votes vote down vote up
protected final DetectorResult processFinderPatternInfo(FinderPatternInfo info)
    throws NotFoundException, FormatException {

  FinderPattern topLeft = info.getTopLeft();
  FinderPattern topRight = info.getTopRight();
  FinderPattern bottomLeft = info.getBottomLeft();

  float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
  if (moduleSize < 1.0f) {
    throw NotFoundException.getNotFoundInstance();
  }
  int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
  Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
  int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;

  AlignmentPattern alignmentPattern = null;
  // Anything above version 1 has an alignment pattern
  if (provisionalVersion.getAlignmentPatternCenters().length > 0) {

    // Guess where a "bottom right" finder pattern would have been
    float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
    float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();

    // Estimate that alignment pattern is closer by 3 modules
    // from "bottom right" to known top left location
    float correctionToTopLeft = 1.0f - 3.0f / modulesBetweenFPCenters;
    int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
    int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));

    // Kind of arbitrary -- expand search radius before giving up
    for (int i = 4; i <= 16; i <<= 1) {
      try {
        alignmentPattern = findAlignmentInRegion(moduleSize,
            estAlignmentX,
            estAlignmentY,
            i);
        break;
      } catch (NotFoundException re) {
        // try next round
      }
    }
    // If we didn't find alignment pattern... well try anyway without it
  }

  PerspectiveTransform transform =
      createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);

  BitMatrix bits = sampleGrid(image, transform, dimension);

  ResultPoint[] points;
  if (alignmentPattern == null) {
    points = new ResultPoint[]{bottomLeft, topLeft, topRight};
  } else {
    points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern};
  }
  return new DetectorResult(bits, points);
}
 
Example 15
Source File: DefaultGridSampler.java    From ZXing-Orient with Apache License 2.0 4 votes vote down vote up
@Override
public BitMatrix sampleGrid(BitMatrix image,
                            int dimensionX,
                            int dimensionY,
                            PerspectiveTransform transform) throws NotFoundException {
  if (dimensionX <= 0 || dimensionY <= 0) {
    throw NotFoundException.getNotFoundInstance();      
  }
  BitMatrix bits = new BitMatrix(dimensionX, dimensionY);
  float[] points = new float[2 * dimensionX];
  for (int y = 0; y < dimensionY; y++) {
    int max = points.length;
    float iValue = (float) y + 0.5f;
    for (int x = 0; x < max; x += 2) {
      points[x] = (float) (x / 2) + 0.5f;
      points[x + 1] = iValue;
    }
    transform.transformPoints(points);
    // Quick check to see if points transformed to something inside the image;
    // sufficient to check the endpoints
    checkAndNudgePoints(image, points);
    try {
      for (int x = 0; x < max; x += 2) {
        if (image.get((int) points[x], (int) points[x + 1])) {
          // Black(-ish) pixel
          bits.set(x / 2, y);
        }
      }
    } catch (ArrayIndexOutOfBoundsException aioobe) {
      // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
      // transform gets "twisted" such that it maps a straight line of points to a set of points
      // whose endpoints are in bounds, but others are not. There is probably some mathematical
      // way to detect this about the transformation that I don't know yet.
      // This results in an ugly runtime exception despite our clever checks above -- can't have
      // that. We could check each point's coordinates but that feels duplicative. We settle for
      // catching and wrapping ArrayIndexOutOfBoundsException.
      throw NotFoundException.getNotFoundInstance();
    }
  }
  return bits;
}
 
Example 16
Source File: Detector.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
protected final DetectorResult processFinderPatternInfo(FinderPatternInfo info)
		throws NotFoundException, FormatException {

	FinderPattern topLeft = info.getTopLeft();
	FinderPattern topRight = info.getTopRight();
	FinderPattern bottomLeft = info.getBottomLeft();

	float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft);
	if (moduleSize < 1.0f) {
		throw NotFoundException.getNotFoundInstance();
	}
	int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize);
	Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension);
	int modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;

	AlignmentPattern alignmentPattern = null;
	// Anything above version 1 has an alignment pattern
	if (provisionalVersion.getAlignmentPatternCenters().length > 0) {

		// Guess where a "bottom right" finder pattern would have been
		float bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();
		float bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();

		// Estimate that alignment pattern is closer by 3 modules
		// from "bottom right" to known top left location
		float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters;
		int estAlignmentX = (int) (topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));
		int estAlignmentY = (int) (topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));

		// Kind of arbitrary -- expand search radius before giving up
		for (int i = 4; i <= 16; i <<= 1) {
			try {
				alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float) i);
				break;
			} catch (NotFoundException re) {
				// try next round
			}
		}
		// If we didn't find alignment pattern... well try anyway without it
	}

	PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);

	BitMatrix bits = sampleGrid(image, transform, dimension);

	ResultPoint[] points;
	if (alignmentPattern == null) {
		points = new ResultPoint[] { bottomLeft, topLeft, topRight };
	} else {
		points = new ResultPoint[] { bottomLeft, topLeft, topRight, alignmentPattern };
	}
	return new DetectorResult(bits, points);
}
 
Example 17
Source File: CodaBarReader.java    From weex with Apache License 2.0 4 votes vote down vote up
@Override
public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException {

  Arrays.fill(counters, 0);
  setCounters(row);
  int startOffset = findStartPattern();
  int nextStart = startOffset;

  decodeRowResult.setLength(0);
  do {
    int charOffset = toNarrowWidePattern(nextStart);
    if (charOffset == -1) {
      throw NotFoundException.getNotFoundInstance();
    }
    // Hack: We store the position in the alphabet table into a
    // StringBuilder, so that we can access the decoded patterns in
    // validatePattern. We'll translate to the actual characters later.
    decodeRowResult.append((char)charOffset);
    nextStart += 8;
    // Stop as soon as we see the end character.
    if (decodeRowResult.length() > 1 &&
        arrayContains(STARTEND_ENCODING, ALPHABET[charOffset])) {
      break;
    }
  } while (nextStart < counterLength); // no fixed end pattern so keep on reading while data is available

  // Look for whitespace after pattern:
  int trailingWhitespace = counters[nextStart - 1];
  int lastPatternSize = 0;
  for (int i = -8; i < -1; i++) {
    lastPatternSize += counters[nextStart + i];
  }

  // We need to see whitespace equal to 50% of the last pattern size,
  // otherwise this is probably a false positive. The exception is if we are
  // at the end of the row. (I.e. the barcode barely fits.)
  if (nextStart < counterLength && trailingWhitespace < lastPatternSize / 2) {
    throw NotFoundException.getNotFoundInstance();
  }

  validatePattern(startOffset);

  // Translate character table offsets to actual characters.
  for (int i = 0; i < decodeRowResult.length(); i++) {
    decodeRowResult.setCharAt(i, ALPHABET[decodeRowResult.charAt(i)]);
  }
  // Ensure a valid start and end character
  char startchar = decodeRowResult.charAt(0);
  if (!arrayContains(STARTEND_ENCODING, startchar)) {
    throw NotFoundException.getNotFoundInstance();
  }
  char endchar = decodeRowResult.charAt(decodeRowResult.length() - 1);
  if (!arrayContains(STARTEND_ENCODING, endchar)) {
    throw NotFoundException.getNotFoundInstance();
  }

  // remove stop/start characters character and check if a long enough string is contained
  if (decodeRowResult.length() <= MIN_CHARACTER_LENGTH) {
    // Almost surely a false positive ( start + stop + at least 1 character)
    throw NotFoundException.getNotFoundInstance();
  }

  if (hints == null || !hints.containsKey(DecodeHintType.RETURN_CODABAR_START_END)) {
    decodeRowResult.deleteCharAt(decodeRowResult.length() - 1);
    decodeRowResult.deleteCharAt(0);
  }

  int runningCount = 0;
  for (int i = 0; i < startOffset; i++) {
    runningCount += counters[i];
  }
  float left = (float) runningCount;
  for (int i = startOffset; i < nextStart - 1; i++) {
    runningCount += counters[i];
  }
  float right = (float) runningCount;
  return new Result(
      decodeRowResult.toString(),
      null,
      new ResultPoint[]{
          new ResultPoint(left, (float) rowNumber),
          new ResultPoint(right, (float) rowNumber)},
      BarcodeFormat.CODABAR);
}
 
Example 18
Source File: Code93Reader.java    From reacteu-app with MIT License 4 votes vote down vote up
@Override
public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints)
    throws NotFoundException, ChecksumException, FormatException {

  int[] start = findAsteriskPattern(row);
  // Read off white space    
  int nextStart = row.getNextSet(start[1]);
  int end = row.getSize();

  StringBuilder result = new StringBuilder(20);
  int[] counters = new int[6];
  char decodedChar;
  int lastStart;
  do {
    recordPattern(row, nextStart, counters);
    int pattern = toPattern(counters);
    if (pattern < 0) {
      throw NotFoundException.getNotFoundInstance();
    }
    decodedChar = patternToChar(pattern);
    result.append(decodedChar);
    lastStart = nextStart;
    for (int counter : counters) {
      nextStart += counter;
    }
    // Read off white space
    nextStart = row.getNextSet(nextStart);
  } while (decodedChar != '*');
  result.deleteCharAt(result.length() - 1); // remove asterisk

  // Should be at least one more black module
  if (nextStart == end || !row.get(nextStart)) {
    throw NotFoundException.getNotFoundInstance();
  }

  if (result.length() < 2) {
    // false positive -- need at least 2 checksum digits
    throw NotFoundException.getNotFoundInstance();
  }

  checkChecksums(result);
  // Remove checksum digits
  result.setLength(result.length() - 2);

  String resultString = decodeExtended(result);

  float left = (float) (start[1] + start[0]) / 2.0f;
  float right = (float) (nextStart + lastStart) / 2.0f;
  return new Result(
      resultString,
      null,
      new ResultPoint[]{
          new ResultPoint(left, (float) rowNumber),
          new ResultPoint(right, (float) rowNumber)},
      BarcodeFormat.CODE_93);

}
 
Example 19
Source File: Code39Reader.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
private static int[] a(BitArray bitarray, int ai[])
{
    int i = bitarray.getSize();
    int j = bitarray.getNextSet(0);
    int k = ai.length;
    int l = j;
    boolean flag = false;
    int i1 = 0;
    while (l < i) 
    {
        if (flag ^ bitarray.get(l))
        {
            ai[i1] = 1 + ai[i1];
        } else
        {
            if (i1 == k - 1)
            {
                if (a(ai) == d && bitarray.isRange(Math.max(0, j - (l - j >> 1)), j, false))
                {
                    return (new int[] {
                        j, l
                    });
                }
                j += ai[0] + ai[1];
                System.arraycopy(ai, 2, ai, 0, k - 2);
                ai[k - 2] = 0;
                ai[k - 1] = 0;
                i1--;
            } else
            {
                i1++;
            }
            ai[i1] = 1;
            if (!flag)
            {
                flag = true;
            } else
            {
                flag = false;
            }
        }
        l++;
    }
    throw NotFoundException.getNotFoundInstance();
}
 
Example 20
Source File: DefaultGridSampler.java    From barcodescanner-lib-aar with MIT License 4 votes vote down vote up
@Override
public BitMatrix sampleGrid(BitMatrix image,
                            int dimensionX,
                            int dimensionY,
                            PerspectiveTransform transform) throws NotFoundException {
  if (dimensionX <= 0 || dimensionY <= 0) {
    throw NotFoundException.getNotFoundInstance();      
  }
  BitMatrix bits = new BitMatrix(dimensionX, dimensionY);
  float[] points = new float[2 * dimensionX];
  for (int y = 0; y < dimensionY; y++) {
    int max = points.length;
    float iValue = y + 0.5f;
    for (int x = 0; x < max; x += 2) {
      points[x] = (float) (x / 2) + 0.5f;
      points[x + 1] = iValue;
    }
    transform.transformPoints(points);
    // Quick check to see if points transformed to something inside the image;
    // sufficient to check the endpoints
    checkAndNudgePoints(image, points);
    try {
      for (int x = 0; x < max; x += 2) {
        if (image.get((int) points[x], (int) points[x + 1])) {
          // Black(-ish) pixel
          bits.set(x / 2, y);
        }
      }
    } catch (ArrayIndexOutOfBoundsException aioobe) {
      // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
      // transform gets "twisted" such that it maps a straight line of points to a set of points
      // whose endpoints are in bounds, but others are not. There is probably some mathematical
      // way to detect this about the transformation that I don't know yet.
      // This results in an ugly runtime exception despite our clever checks above -- can't have
      // that. We could check each point's coordinates but that feels duplicative. We settle for
      // catching and wrapping ArrayIndexOutOfBoundsException.
      throw NotFoundException.getNotFoundInstance();
    }
  }
  return bits;
}