/// <summary> /// </summary> /// <returns>the 3 best <see cref="FinderPattern" />s from our list of candidates. The "best" are /// those that have been detected at least CENTER_QUORUM times, and whose module /// size differs from the average among those patterns the least /// </returns> private FinderPattern[][] selectMultipleBestPatterns() { List <FinderPattern> possibleCenters = PossibleCenters; int size = possibleCenters.Count; if (size < 3) { // Couldn't find enough finder patterns return(null); } /* * Begin HE modifications to safely detect multiple codes of equal size */ if (size == 3) { return(new FinderPattern[][] { new FinderPattern[] { possibleCenters[0], possibleCenters[1], possibleCenters[2] } }); } // Sort by estimated module size to speed up the upcoming checks possibleCenters.Sort(new ModuleSizeComparator()); /* * Now lets start: build a list of tuples of three finder locations that * - feature similar module sizes * - are placed in a distance so the estimated module count is within the QR specification * - have similar distance between upper left/right and left top/bottom finder patterns * - form a triangle with 90° angle (checked by comparing top right/bottom left distance * with pythagoras) * * Note: we allow each point to be used for more than one code region: this might seem * counterintuitive at first, but the performance penalty is not that big. At this point, * we cannot make a good quality decision whether the three finders actually represent * a QR code, or are just by chance layouted so it looks like there might be a QR code there. * So, if the layout seems right, lets have the decoder try to decode. */ List <FinderPattern[]> results = new List <FinderPattern[]>(); // holder for the results for (int i1 = 0; i1 < (size - 2); i1++) { FinderPattern p1 = possibleCenters[i1]; if (p1 == null) { continue; } for (int i2 = i1 + 1; i2 < (size - 1); i2++) { FinderPattern p2 = possibleCenters[i2]; if (p2 == null) { continue; } // Compare the expected module sizes; if they are really off, skip float vModSize12 = (p1.EstimatedModuleSize - p2.EstimatedModuleSize) / Math.Min(p1.EstimatedModuleSize, p2.EstimatedModuleSize); float vModSize12A = Math.Abs(p1.EstimatedModuleSize - p2.EstimatedModuleSize); if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) { // break, since elements are ordered by the module size deviation there cannot be // any more interesting elements for the given p1. break; } for (int i3 = i2 + 1; i3 < size; i3++) { FinderPattern p3 = possibleCenters[i3]; if (p3 == null) { continue; } // Compare the expected module sizes; if they are really off, skip float vModSize23 = (p2.EstimatedModuleSize - p3.EstimatedModuleSize) / Math.Min(p2.EstimatedModuleSize, p3.EstimatedModuleSize); float vModSize23A = Math.Abs(p2.EstimatedModuleSize - p3.EstimatedModuleSize); if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) { // break, since elements are ordered by the module size deviation there cannot be // any more interesting elements for the given p1. break; } FinderPattern[] test = { p1, p2, p3 }; ResultPoint.orderBestPatterns(test); // Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal FinderPatternInfo info = new FinderPatternInfo(test); float dA = ResultPoint.distance(info.TopLeft, info.BottomLeft); float dC = ResultPoint.distance(info.TopRight, info.BottomLeft); float dB = ResultPoint.distance(info.TopLeft, info.TopRight); // Check the sizes float estimatedModuleCount = (dA + dB) / (p1.EstimatedModuleSize * 2.0f); if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) { continue; } // Calculate the difference of the edge lengths in percent float vABBC = Math.Abs((dA - dB) / Math.Min(dA, dB)); if (vABBC >= 0.1f) { continue; } // Calculate the diagonal length by assuming a 90° angle at topleft float dCpy = (float)Math.Sqrt((double)dA * dA + (double)dB * dB); // Compare to the real distance in % float vPyC = Math.Abs((dC - dCpy) / Math.Min(dC, dCpy)); if (vPyC >= 0.1f) { continue; } // All tests passed! results.Add(test); } // end iterate p3 } // end iterate p2 } // end iterate p1 if (results.Count != 0) { return(results.ToArray()); } // Nothing found! return(null); }
public FinderPatternInfo[] findMulti(IDictionary <DecodeHintType, object> hints) { bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); BitMatrix image = Image; int maxI = image.Height; int maxJ = image.Width; // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI; i += iSkip) { // Get a row of black/white values clearCounts(stateCount); int currentState = 0; for (int j = 0; j < maxJ; j++) { if (image[j, i]) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount) && handlePossibleCenter(stateCount, i, j)) { // Yes // Clear state to start looking again currentState = 0; clearCounts(stateCount); } else { // No, shift counts back by two shiftCounts2(stateCount); currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } // for j=... if (foundPatternCross(stateCount)) { handlePossibleCenter(stateCount, i, maxJ); } // end if foundPatternCross } // for i=iSkip-1 ... FinderPattern[][] patternInfo = selectMultipleBestPatterns(); if (patternInfo == null) { return(EMPTY_RESULT_ARRAY); } List <FinderPatternInfo> result = new List <FinderPatternInfo>(); foreach (FinderPattern[] pattern in patternInfo) { ResultPoint.orderBestPatterns(pattern); result.Add(new FinderPatternInfo(pattern)); } if (result.Count == 0) { return(EMPTY_RESULT_ARRAY); } else { return(result.ToArray()); } }
internal virtual FinderPatternInfo find(IDictionary <DecodeHintType, object> hints) { bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); int maxI = image.Height; int maxJ = image.Width; // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } bool done = false; int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values clearCounts(stateCount); int currentState = 0; for (int j = 0; j < maxJ; j++) { if (image[j, i]) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes bool confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (hasSkipped) { done = haveMultiplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { shiftCounts2(stateCount); currentState = 3; continue; } // Clear state to start looking again currentState = 0; clearCounts(stateCount); } else { // No, shift counts back by two shiftCounts2(stateCount); currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { bool confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one done = haveMultiplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = selectBestPatterns(); if (patternInfo == null) { return(null); } ResultPoint.orderBestPatterns(patternInfo); return(new FinderPatternInfo(patternInfo)); }
/// <summary> /// <p>Detects a Data Matrix Code in an image.</p> /// </summary> /// <returns><see cref="DetectorResult" />encapsulating results of detecting a Data Matrix Code or null</returns> public DetectorResult detect() { if (rectangleDetector == null) { // can be null, if the image is to small return(null); } ResultPoint[] cornerPoints = rectangleDetector.detect(); if (cornerPoints == null) { return(null); } var pointA = cornerPoints[0]; var pointB = cornerPoints[1]; var pointC = cornerPoints[2]; var pointD = cornerPoints[3]; // Point A and D are across the diagonal from one another, // as are B and C. Figure out which are the solid black lines // by counting transitions var transitions = new List <ResultPointsAndTransitions>(4); transitions.Add(transitionsBetween(pointA, pointB)); transitions.Add(transitionsBetween(pointA, pointC)); transitions.Add(transitionsBetween(pointB, pointD)); transitions.Add(transitionsBetween(pointC, pointD)); transitions.Sort(new ResultPointsAndTransitionsComparator()); // Sort by number of transitions. First two will be the two solid sides; last two // will be the two alternating black/white sides var lSideOne = transitions[0]; var lSideTwo = transitions[1]; // Figure out which point is their intersection by tallying up the number of times we see the // endpoints in the four endpoints. One will show up twice. var pointCount = new Dictionary <ResultPoint, int>(); increment(pointCount, lSideOne.From); increment(pointCount, lSideOne.To); increment(pointCount, lSideTwo.From); increment(pointCount, lSideTwo.To); ResultPoint maybeTopLeft = null; ResultPoint bottomLeft = null; ResultPoint maybeBottomRight = null; foreach (var entry in pointCount) { ResultPoint point = entry.Key; int value = entry.Value; if (value == 2) { bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides } else { // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now if (maybeTopLeft == null) { maybeTopLeft = point; } else { maybeBottomRight = point; } } } if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { return(null); } // Bottom left is correct but top left and bottom right might be switched ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight }; // Use the dot product trick to sort them out ResultPoint.orderBestPatterns(corners); // Now we know which is which: ResultPoint bottomRight = corners[0]; bottomLeft = corners[1]; ResultPoint topLeft = corners[2]; // Which point didn't we find in relation to the "L" sides? that's the top right corner ResultPoint topRight; if (!pointCount.ContainsKey(pointA)) { topRight = pointA; } else if (!pointCount.ContainsKey(pointB)) { topRight = pointB; } else if (!pointCount.ContainsKey(pointC)) { topRight = pointC; } else { topRight = pointD; } // Next determine the dimension by tracing along the top or right side and counting black/white // transitions. Since we start inside a black module, we should see a number of transitions // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to // end on a black module: // The top right point is actually the corner of a module, which is one of the two black modules // adjacent to the white module at the top right. Tracing to that corner from either the top left // or bottom right should work here. int dimensionTop = transitionsBetween(topLeft, topRight).Transitions; int dimensionRight = transitionsBetween(bottomRight, topRight).Transitions; if ((dimensionTop & 0x01) == 1) { // it can't be odd, so, round... up? dimensionTop++; } dimensionTop += 2; if ((dimensionRight & 0x01) == 1) { // it can't be odd, so, round... up? dimensionRight++; } dimensionRight += 2; BitMatrix bits; ResultPoint correctedTopRight; // Rectangular symbols are 6x16, 6x28, 10x24, 10x32, 14x32, or 14x44. If one dimension is more // than twice the other, it's certainly rectangular, but to cut a bit more slack we accept it as // rectangular if the bigger side is at least 7/4 times the other: if (4 * dimensionTop >= 7 * dimensionRight || 4 * dimensionRight >= 7 * dimensionTop) { // The matrix is rectangular correctedTopRight = correctTopRightRectangular(bottomLeft, bottomRight, topLeft, topRight, dimensionTop, dimensionRight); if (correctedTopRight == null) { correctedTopRight = topRight; } dimensionTop = transitionsBetween(topLeft, correctedTopRight).Transitions; dimensionRight = transitionsBetween(bottomRight, correctedTopRight).Transitions; if ((dimensionTop & 0x01) == 1) { // it can't be odd, so, round... up? dimensionTop++; } if ((dimensionRight & 0x01) == 1) { // it can't be odd, so, round... up? dimensionRight++; } bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionTop, dimensionRight); } else { // The matrix is square int dimension = Math.Min(dimensionRight, dimensionTop); // correct top right point to match the white module correctedTopRight = correctTopRight(bottomLeft, bottomRight, topLeft, topRight, dimension); if (correctedTopRight == null) { correctedTopRight = topRight; } // Redetermine the dimension using the corrected top right point int dimensionCorrected = Math.Max(transitionsBetween(topLeft, correctedTopRight).Transitions, transitionsBetween(bottomRight, correctedTopRight).Transitions); dimensionCorrected++; if ((dimensionCorrected & 0x01) == 1) { dimensionCorrected++; } bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionCorrected, dimensionCorrected); } if (bits == null) { return(null); } return(new DetectorResult(bits, new ResultPoint[] { topLeft, bottomLeft, bottomRight, correctedTopRight })); }
public FinderPatternInfo[] findMulti(Hashtable hints) { bool tryHarder = hints != null && hints.Contains(DecodeHintType.TRY_HARDER); BitMatrix image = Image; int maxI = image.Height; int maxJ = image.Width; // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (int)(maxI / (MAX_MODULES * 4.0f) * 3); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI; i += iSkip) { // Get a row of black/white values stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (image[j, i]) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes bool confirmed = handlePossibleCenter(stateCount, i, j); if (!confirmed) { do { // Advance to next black pixel j++; } while (j < maxJ && !image[j, i]); j--; // back up to that last white pixel } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } // for j=... if (foundPatternCross(stateCount)) { handlePossibleCenter(stateCount, i, maxJ); } // end if foundPatternCross } // for i=iSkip-1 ... FinderPattern[][] patternInfo = selectMutipleBestPatterns(); var result = new ArrayList(); foreach (FinderPattern[] pattern in patternInfo) { ResultPoint.orderBestPatterns(pattern); result.Add(new FinderPatternInfo(pattern)); } if (result.Count == 0) { return(EMPTY_RESULT_ARRAY); } else { return((FinderPatternInfo[])result.ToArray()); } }
/// <summary> <p>Detects a Data Matrix Code in an image.</p> /// /// </summary> /// <returns> {@link DetectorResult} encapsulating results of detecting a QR Code /// </returns> /// <throws> ReaderException if no Data Matrix Code can be found </throws> public DetectorResult detect() { ResultPoint[] cornerPoints = rectangleDetector.detect(); ResultPoint pointA = cornerPoints[0]; ResultPoint pointB = cornerPoints[1]; ResultPoint pointC = cornerPoints[2]; ResultPoint pointD = cornerPoints[3]; // Point A and D are across the diagonal from one another, // as are B and C. Figure out which are the solid black lines // by counting transitions System.Collections.ArrayList transitions = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(4)); transitions.Add(transitionsBetween(pointA, pointB)); transitions.Add(transitionsBetween(pointA, pointC)); transitions.Add(transitionsBetween(pointB, pointD)); transitions.Add(transitionsBetween(pointC, pointD)); Collections.insertionSort(transitions, new ResultPointsAndTransitionsComparator()); // Sort by number of transitions. First two will be the two solid sides; last two // will be the two alternating black/white sides ResultPointsAndTransitions lSideOne = (ResultPointsAndTransitions)transitions[0]; ResultPointsAndTransitions lSideTwo = (ResultPointsAndTransitions)transitions[1]; // Figure out which point is their intersection by tallying up the number of times we see the // endpoints in the four endpoints. One will show up twice. System.Collections.Hashtable pointCount = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); increment(pointCount, lSideOne.From); increment(pointCount, lSideOne.To); increment(pointCount, lSideTwo.From); increment(pointCount, lSideTwo.To); ResultPoint maybeTopLeft = null; ResultPoint bottomLeft = null; ResultPoint maybeBottomRight = null; System.Collections.IEnumerator points = pointCount.Keys.GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" while (points.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" ResultPoint point = (ResultPoint)points.Current; System.Int32 value_Renamed = (System.Int32)pointCount[point]; if (value_Renamed == 2) { bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides } else { // Otherwise it's either top left or bottom right -- just assign the two arbitrarily now if (maybeTopLeft == null) { maybeTopLeft = point; } else { maybeBottomRight = point; } } } if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null) { throw ReaderException.Instance; } // Bottom left is correct but top left and bottom right might be switched ResultPoint[] corners = new ResultPoint[] { maybeTopLeft, bottomLeft, maybeBottomRight }; // Use the dot product trick to sort them out ResultPoint.orderBestPatterns(corners); // Now we know which is which: ResultPoint bottomRight = corners[0]; bottomLeft = corners[1]; ResultPoint topLeft = corners[2]; // Which point didn't we find in relation to the "L" sides? that's the top right corner ResultPoint topRight; if (!pointCount.ContainsKey(pointA)) { topRight = pointA; } else if (!pointCount.ContainsKey(pointB)) { topRight = pointB; } else if (!pointCount.ContainsKey(pointC)) { topRight = pointC; } else { topRight = pointD; } // Next determine the dimension by tracing along the top or right side and counting black/white // transitions. Since we start inside a black module, we should see a number of transitions // equal to 1 less than the code dimension. Well, actually 2 less, because we are going to // end on a black module: // The top right point is actually the corner of a module, which is one of the two black modules // adjacent to the white module at the top right. Tracing to that corner from either the top left // or bottom right should work here. The number of transitions could be higher than it should be // due to noise. So we try both and take the min. int dimension = System.Math.Min(transitionsBetween(topLeft, topRight).Transitions, transitionsBetween(bottomRight, topRight).Transitions); if ((dimension & 0x01) == 1) { // it can't be odd, so, round... up? dimension++; } dimension += 2; BitMatrix bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, dimension); return(new DetectorResult(bits, new ResultPoint[] { pointA, pointB, pointC, pointD })); }