port finder pattern finder

This commit is contained in:
Henry Schimke
2022-10-07 18:25:46 -05:00
parent 8f831b63e8
commit a205e1e08b
7 changed files with 895 additions and 771 deletions

View File

@@ -23,7 +23,7 @@ use crate::{
BitMatrix, DefaultGridSampler, GridSampler,
},
exceptions::Exceptions,
RXingResultPoint,
RXingResultPoint, ResultPoint,
};
use super::AztecDetectorResult::AztecDetectorRXingResult;

View File

@@ -1,6 +1,6 @@
pub mod MathUtils;
use crate::common::BitMatrix;
use crate::{Exceptions, RXingResultPoint};
use crate::{Exceptions, RXingResultPoint, ResultPoint};
/*
* Copyright 2009 ZXing authors

View File

@@ -1,8 +1,8 @@
pub mod aztec;
pub mod qrcode;
pub mod client;
pub mod common;
mod exceptions;
pub mod qrcode;
pub use exceptions::Exceptions;
@@ -26,7 +26,6 @@ mod PlanarYUVLuminanceSourceTestCase;
#[cfg(test)]
mod RGBLuminanceSourceTestCase;
pub type EncodingHintDictionary = HashMap<EncodeHintType, EncodeHintValue>;
pub type DecodingHintDictionary = HashMap<DecodeHintType, DecodeHintValue>;
pub type MetadataDictionary = HashMap<RXingResultMetadataType, RXingResultMetadataValue>;
@@ -566,7 +565,7 @@ pub enum DecodeHintType {
*
* @see DecodeHintType#NEED_RESULT_POINT_CALLBACK
*/
pub type RXingResultPointCallback = fn(&RXingResultPoint);
pub type RXingResultPointCallback = fn(&dyn ResultPoint);
#[derive(Clone)]
pub enum DecodeHintValue {
/**
@@ -1174,6 +1173,107 @@ impl fmt::Display for RXingResult {
//package com.google.zxing;
use crate::common::detector::MathUtils;
pub trait ResultPoint {
fn getX(&self) -> f32;
fn getY(&self) -> f32;
}
pub mod result_point_utils {
use crate::{common::detector::MathUtils, ResultPoint};
/**
* Orders an array of three RXingResultPoints in an order [A,B,C] such that AB is less than AC
* and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
*
* @param patterns array of three {@code RXingResultPoint} to order
*/
pub fn orderBestPatterns<T: ResultPoint+Copy+Clone>(patterns: &mut [T; 3]) {
// Find distances between pattern centers
let zeroOneDistance = MathUtils::distance_float(
patterns[0].getX(),
patterns[0].getY(),
patterns[1].getX(),
patterns[1].getY(),
);
let oneTwoDistance = MathUtils::distance_float(
patterns[1].getX(),
patterns[1].getY(),
patterns[2].getX(),
patterns[2].getY(),
);
let zeroTwoDistance = MathUtils::distance_float(
patterns[0].getX(),
patterns[0].getY(),
patterns[2].getX(),
patterns[2].getY(),
);
let mut pointA; //: &RXingResultPoint;
let mut pointB; //: &RXingResultPoint;
let mut pointC; //: &RXingResultPoint;
// Assume one closest to other two is B; A and C will just be guesses at first
if oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance {
pointB = patterns[0];
pointA = patterns[1];
pointC = patterns[2];
} else if zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance {
pointB = patterns[1];
pointA = patterns[0];
pointC = patterns[2];
} else {
pointB = patterns[2];
pointA = patterns[0];
pointC = patterns[1];
}
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if crossProductZ(pointA, pointB, pointC) < 0.0f32 {
let temp = pointA;
pointA = pointC;
pointC = temp;
}
let pa = pointA;
let pb = pointB;
let pc = pointC;
patterns[0] = pa;
patterns[1] = pb;
patterns[2] = pc;
}
/**
* @param pattern1 first pattern
* @param pattern2 second pattern
* @return distance between two points
*/
pub fn distance<T:ResultPoint>(pattern1: T, pattern2: T) -> f32 {
return MathUtils::distance_float(
pattern1.getX(),
pattern1.getY(),
pattern2.getX(),
pattern2.getY(),
);
}
/**
* Returns the z component of the cross product between vectors BC and BA.
*/
pub fn crossProductZ<T: ResultPoint>(
pointA: T,
pointB: T,
pointC: T,
) -> f32 {
let bX = pointB.getX();
let bY = pointB.getY();
return ((pointC.getX() - bX) * (pointA.getY() - bY))
- ((pointC.getY() - bY) * (pointA.getX() - bX));
}
}
/**
* <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
* would be the location of a finder pattern or the corner of the barcode, for example.</p>
@@ -1201,100 +1301,16 @@ impl RXingResultPoint {
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
pub fn getX(&self) -> f32 {
impl ResultPoint for RXingResultPoint {
fn getX(&self) -> f32 {
return self.x;
}
pub fn getY(&self) -> f32 {
fn getY(&self) -> f32 {
return self.y;
}
/**
* Orders an array of three RXingResultPoints in an order [A,B,C] such that AB is less than AC
* and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
*
* @param patterns array of three {@code RXingResultPoint} to order
*/
pub fn orderBestPatterns(patterns: &mut Vec<RXingResultPoint>) {
// Find distances between pattern centers
let zeroOneDistance = MathUtils::distance_float(
patterns[0].getX(),
patterns[0].getY(),
patterns[1].getX(),
patterns[1].getY(),
);
let oneTwoDistance = MathUtils::distance_float(
patterns[1].getX(),
patterns[1].getY(),
patterns[2].getX(),
patterns[2].getY(),
);
let zeroTwoDistance = MathUtils::distance_float(
patterns[0].getX(),
patterns[0].getY(),
patterns[2].getX(),
patterns[2].getY(),
);
let mut pointA: &RXingResultPoint;
let mut pointB: &RXingResultPoint;
let mut pointC: &RXingResultPoint;
// Assume one closest to other two is B; A and C will just be guesses at first
if oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance {
pointB = &patterns[0];
pointA = &patterns[1];
pointC = &patterns[2];
} else if zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance {
pointB = &patterns[1];
pointA = &patterns[0];
pointC = &patterns[2];
} else {
pointB = &patterns[2];
pointA = &patterns[0];
pointC = &patterns[1];
}
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if RXingResultPoint::crossProductZ(&pointA, &pointB, &pointC) < 0.0f32 {
let temp = pointA;
pointA = pointC;
pointC = temp;
}
let pa = (*pointA).clone();
let pb = (*pointB).clone();
let pc = (*pointC).clone();
patterns[0] = pa;
patterns[1] = pb;
patterns[2] = pc;
}
/**
* @param pattern1 first pattern
* @param pattern2 second pattern
* @return distance between two points
*/
pub fn distance(pattern1: &RXingResultPoint, pattern2: &RXingResultPoint) -> f32 {
return MathUtils::distance_float(pattern1.x, pattern1.y, pattern2.x, pattern2.y);
}
/**
* Returns the z component of the cross product between vectors BC and BA.
*/
pub fn crossProductZ(
pointA: &RXingResultPoint,
pointB: &RXingResultPoint,
pointC: &RXingResultPoint,
) -> f32 {
let bX = pointB.x;
let bY = pointB.y;
return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
}
}
impl fmt::Display for RXingResultPoint {

View File

@@ -16,7 +16,7 @@
//RXingResultPoint
use crate::RXingResultPoint;
use crate::{RXingResultPoint, ResultPoint};
/**
* <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
@@ -24,17 +24,27 @@ use crate::RXingResultPoint;
*
* @author Sean Owen
*/
#[derive(Clone)]
#[derive(Debug,Clone, Copy,PartialEq)]
pub struct AlignmentPattern {
estimatedModuleSize: f32,
internal_result_point: RXingResultPoint,
point: (f32, f32),
}
impl ResultPoint for AlignmentPattern {
fn getX(&self) -> f32 {
self.point.0
}
fn getY(&self) -> f32 {
self.point.1
}
}
impl AlignmentPattern {
pub fn new(posX: f32, posY: f32, estimatedModuleSize: f32) -> Self {
Self {
estimatedModuleSize,
internal_result_point: RXingResultPoint { x: posX, y: posY },
point: (posX, posY),
}
}
@@ -43,9 +53,7 @@ impl AlignmentPattern {
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/
pub fn aboutEquals(&self, moduleSize: f32, i: f32, j: f32) -> bool {
if (i - self.internal_result_point.getY()).abs() <= moduleSize
&& (j - self.internal_result_point.getX()).abs() <= moduleSize
{
if (i - self.getY()).abs() <= moduleSize && (j - self.getX()).abs() <= moduleSize {
let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs();
return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize;
}
@@ -57,13 +65,9 @@ impl AlignmentPattern {
* with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.
*/
pub fn combineEstimate(&self, i: f32, j: f32, newModuleSize: f32) -> AlignmentPattern {
let combinedX = (self.internal_result_point.getX() + j) / 2.0;
let combinedY = (self.internal_result_point.getY() + i) / 2.0;
let combinedX = (self.getX() + j) / 2.0;
let combinedY = (self.getY() + i) / 2.0;
let combinedModuleSize = (self.estimatedModuleSize + newModuleSize) / 2.0;
AlignmentPattern::new(combinedX, combinedY, combinedModuleSize)
}
pub fn as_RXingResultPoint(&self) -> &RXingResultPoint {
&self.internal_result_point
}
}

View File

@@ -306,7 +306,7 @@ impl AlignmentPatternFinder {
// Hadn't found this before; save it
let point = AlignmentPattern::new(centerJ, centerI, estimatedModuleSize);
if self.resultPointCallback.is_some() {
self.resultPointCallback.as_ref().unwrap()(point.as_RXingResultPoint());
self.resultPointCallback.as_ref().unwrap()(&point);
}
self.possibleCenters.push(point);
// if self.resultPointCallback.is_some() {

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
use crate::RXingResultPoint;
use crate::{RXingResultPoint, ResultPoint};
/**
* <p>Encapsulates a finder pattern, which are the three square patterns found in
@@ -23,10 +23,21 @@ use crate::RXingResultPoint;
*
* @author Sean Owen
*/
#[derive(Debug,Clone, Copy,PartialEq)]
pub struct FinderPattern {
estimatedModuleSize: f32,
count: usize,
internal_result_point: RXingResultPoint,
point: (f32, f32),
}
impl ResultPoint for FinderPattern {
fn getX(&self) -> f32 {
self.point.0
}
fn getY(&self) -> f32 {
self.point.1
}
}
impl FinderPattern {
@@ -38,7 +49,7 @@ impl FinderPattern {
Self {
estimatedModuleSize,
count,
internal_result_point: RXingResultPoint::new(posX, posY),
point: (posX, posY),
}
}
@@ -55,9 +66,7 @@ impl FinderPattern {
* position and size -- meaning, it is at nearly the same center with nearly the same size.</p>
*/
pub fn aboutEquals(&self, moduleSize: f32, i: f32, j: f32) -> bool {
if (i - self.internal_result_point.getY()).abs() <= moduleSize
&& (j - self.internal_result_point.getX()).abs() <= moduleSize
{
if (i - self.getY()).abs() <= moduleSize && (j - self.getX()).abs() <= moduleSize {
let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs();
return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize;
}
@@ -71,8 +80,8 @@ impl FinderPattern {
*/
pub fn combineEstimate(&self, i: f32, j: f32, newModuleSize: f32) -> FinderPattern {
let combinedCount = self.count as f32 + 1.0;
let combinedX = (self.count as f32 * self.internal_result_point.getX() + j) / combinedCount;
let combinedY = (self.count as f32 * self.internal_result_point.getY() + i) / combinedCount;
let combinedX = (self.count as f32 * self.getX() + j) / combinedCount;
let combinedY = (self.count as f32 * self.getY() + i) / combinedCount;
let combinedModuleSize =
(self.count as f32 * self.estimatedModuleSize + newModuleSize) / combinedCount;
FinderPattern::private_new(

View File

@@ -14,11 +14,13 @@
* limitations under the License.
*/
use crate::{common::BitMatrix, RXingResultPointCallback, DecodingHintDictionary};
use crate::{
common::BitMatrix, result_point_utils, DecodeHintType, DecodingHintDictionary, Exceptions,
RXingResultPoint, RXingResultPointCallback, ResultPoint,
};
use super::{FinderPattern, FinderPatternInfo};
/**
* <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
* markers at three corners of a QR Code.</p>
@@ -28,15 +30,14 @@ use super::{FinderPattern, FinderPatternInfo};
* @author Sean Owen
*/
pub struct FinderPatternFinder {
image: BitMatrix,
possibleCenters: Vec<FinderPattern>,
hasSkipped: bool,
crossCheckStateCount:Vec<u32>,
crossCheckStateCount: [u32; 5],
resultPointCallback: Option<RXingResultPointCallback>,
}
impl FinderPatternFinder {
const CENTER_QUORUM :u32= 2;
const CENTER_QUORUM: usize = 2;
// private static final EstimatedModuleComparator moduleComparator = new EstimatedModuleComparator();
const MIN_SKIP: u32 = 3; // 1 pixel/module times 3 modules/center
const MAX_MODULES: u32 = 97; // support up to version 20 for mobile clients
@@ -50,7 +51,10 @@ impl FinderPatternFinder{
Self::with_callback(image, None)
}
pub fn with_callback( image:BitMatrix, resultPointCallback:Option<RXingResultPointCallback>) -> Self{
pub fn with_callback(
image: BitMatrix,
resultPointCallback: Option<RXingResultPointCallback>,
) -> Self {
Self {
image,
possibleCenters: Vec::new(),
@@ -68,10 +72,13 @@ impl FinderPatternFinder{
&self.possibleCenters
}
pub fn find(&self, hints:&DecodingHintDictionary) -> Result<FinderPatternInfo,Exceptions> {
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);
int maxI = image.getHeight();
int maxJ = image.getWidth();
pub fn find(
&mut self,
hints: &DecodingHintDictionary,
) -> Result<FinderPatternInfo, Exceptions> {
let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER);
let maxI = self.image.getHeight();
let maxJ = self.image.getWidth();
// 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
@@ -79,38 +86,47 @@ impl FinderPatternFinder{
// 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;
let mut iSkip = (3 * maxI) / (4 * Self::MAX_MODULES);
if iSkip < Self::MIN_SKIP || tryHarder {
iSkip = Self::MIN_SKIP;
}
boolean done = false;
int[] stateCount = new int[5];
for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {
let mut done = false;
let mut stateCount = [0u32; 5];
let mut i = iSkip - 1;
while i < maxI && !done {
// for (int i = iSkip - 1; i < maxI && !done; i += iSkip) {
// Get a row of black/white values
doClearCounts(stateCount);
int currentState = 0;
for (int j = 0; j < maxJ; j++) {
if (image.get(j, i)) {
FinderPatternFinder::doClearCounts(&mut stateCount);
let mut currentState = 0;
let mut j = 0;
while j < maxJ {
// for (int j = 0; j < maxJ; j++) {
if self.image.get(j, i) {
// Black pixel
if ((currentState & 1) == 1) { // Counting white pixels
currentState++;
if (currentState & 1) == 1 {
// Counting white pixels
currentState += 1;
}
stateCount[currentState]++;
} else { // White pixel
if ((currentState & 1) == 0) { // Counting black pixels
if (currentState == 4) { // A winner?
if (foundPatternCross(stateCount)) { // Yes
boolean confirmed = handlePossibleCenter(stateCount, i, j);
if (confirmed) {
stateCount[currentState] += 1;
} else {
// White pixel
if (currentState & 1) == 0 {
// Counting black pixels
if currentState == 4 {
// A winner?
if FinderPatternFinder::foundPatternCross(&stateCount) {
// Yes
let confirmed = self.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();
if self.hasSkipped {
done = self.haveMultiplyConfirmedCenters();
} else {
int rowSkip = findRowSkip();
if (rowSkip > stateCount[2]) {
let rowSkip = self.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
@@ -124,41 +140,46 @@ impl FinderPatternFinder{
}
}
} else {
doShiftCounts2(stateCount);
FinderPatternFinder::doShiftCounts2(&mut stateCount);
currentState = 3;
continue;
}
// Clear state to start looking again
currentState = 0;
doClearCounts(stateCount);
} else { // No, shift counts back by two
doShiftCounts2(stateCount);
FinderPatternFinder::doClearCounts(&mut stateCount);
} else {
// No, shift counts back by two
FinderPatternFinder::doShiftCounts2(&mut stateCount);
currentState = 3;
}
} else {
stateCount[++currentState]++;
currentState += 1;
stateCount[currentState] += 1;
}
} else { // Counting white pixels
stateCount[currentState]++;
} else {
// Counting white pixels
stateCount[currentState] += 1;
}
}
}
if (foundPatternCross(stateCount)) {
boolean confirmed = handlePossibleCenter(stateCount, i, maxJ);
if (confirmed) {
if FinderPatternFinder::foundPatternCross(&stateCount) {
let confirmed = self.handlePossibleCenter(&stateCount, i, maxJ);
if confirmed {
iSkip = stateCount[0];
if (hasSkipped) {
if self.hasSkipped {
// Found a third one
done = haveMultiplyConfirmedCenters();
}
done = self.haveMultiplyConfirmedCenters();
}
}
}
FinderPattern[] patternInfo = selectBestPatterns();
RXingResultPoint.orderBestPatterns(patternInfo);
i += iSkip;
}
return new FinderPatternInfo(patternInfo);
let mut patternInfo = self.selectBestPatterns()?;
result_point_utils::orderBestPatterns(&mut patternInfo);
Ok(FinderPatternInfo::new(patternInfo))
}
/**
@@ -166,7 +187,7 @@ impl FinderPatternFinder{
* figures the location of the center of this run.
*/
fn centerFromEnd(stateCount: &[u32], end: u32) -> f32 {
return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f;
((end - stateCount[4] - stateCount[3]) - stateCount[2]) as f32 / 2.0
}
/**
@@ -175,26 +196,26 @@ impl FinderPatternFinder{
* used by finder patterns to be considered a match
*/
pub fn foundPatternCross(stateCount: &[u32]) -> bool {
int totalModuleSize = 0;
for (int i = 0; i < 5; i++) {
int count = stateCount[i];
if (count == 0) {
let mut totalModuleSize = 0;
for i in 0..5 {
// for (int i = 0; i < 5; i++) {
let count = stateCount[i];
if count == 0 {
return false;
}
totalModuleSize += count;
}
if (totalModuleSize < 7) {
if totalModuleSize < 7 {
return false;
}
float moduleSize = totalModuleSize / 7.0f;
float maxVariance = moduleSize / 2.0f;
let moduleSize = totalModuleSize as f32 / 7.0;
let maxVariance = moduleSize as f32 / 2.0;
// Allow less than 50% variance from 1-1-3-1-1 proportions
return
Math.abs(moduleSize - stateCount[0]) < maxVariance &&
Math.abs(moduleSize - stateCount[1]) < maxVariance &&
Math.abs(3.0f * moduleSize - stateCount[2]) < 3 * maxVariance &&
Math.abs(moduleSize - stateCount[3]) < maxVariance &&
Math.abs(moduleSize - stateCount[4]) < maxVariance;
return ((moduleSize - stateCount[0] as f32).abs()) < maxVariance
&& ((moduleSize - stateCount[1] as f32).abs()) < maxVariance
&& ((3.0 * moduleSize - stateCount[2] as f32).abs()) < 3.0 * maxVariance
&& (moduleSize - stateCount[3] as f32).abs() < maxVariance
&& (moduleSize - stateCount[4] as f32).abs() < maxVariance;
}
/**
@@ -203,10 +224,11 @@ impl FinderPatternFinder{
* used by finder patterns to be considered a match
*/
pub fn foundPatternDiagonal(stateCount: &[u32]) -> bool {
int totalModuleSize = 0;
for (int i = 0; i < 5; i++) {
int count = stateCount[i];
if (count == 0) {
let mut totalModuleSize = 0;
for i in 0..5 {
// for (int i = 0; i < 5; i++) {
let count = stateCount[i];
if count == 0 {
return false;
}
totalModuleSize += count;
@@ -214,37 +236,36 @@ impl FinderPatternFinder{
if (totalModuleSize < 7) {
return false;
}
float moduleSize = totalModuleSize / 7.0f;
float maxVariance = moduleSize / 1.333f;
let moduleSize = totalModuleSize as f32 / 7.0;
let maxVariance = moduleSize / 1.333;
// Allow less than 75% variance from 1-1-3-1-1 proportions
return
Math.abs(moduleSize - stateCount[0]) < maxVariance &&
Math.abs(moduleSize - stateCount[1]) < maxVariance &&
Math.abs(3.0f * moduleSize - stateCount[2]) < 3 * maxVariance &&
Math.abs(moduleSize - stateCount[3]) < maxVariance &&
Math.abs(moduleSize - stateCount[4]) < maxVariance;
return (moduleSize - stateCount[0] as f32).abs() < maxVariance
&& (moduleSize - stateCount[1] as f32).abs() < maxVariance
&& (3.0 * moduleSize - stateCount[2] as f32).abs() < 3.0 * maxVariance
&& (moduleSize - stateCount[3] as f32).abs() < maxVariance
&& (moduleSize - stateCount[4] as f32).abs() < maxVariance;
}
fn getCrossCheckStateCount(&self) -> &[u32] {
doClearCounts(crossCheckStateCount);
return crossCheckStateCount;
fn getCrossCheckStateCount(&mut self) -> &[u32; 5] {
FinderPatternFinder::doClearCounts(&mut self.crossCheckStateCount);
&self.crossCheckStateCount
}
#[deprecated]
pub fn clearCounts(&self, counts:&[u32]) {
doClearCounts(counts);
pub fn clearCounts(&self, counts: &mut [u32; 5]) {
Self::doClearCounts(counts);
}
#[deprecated]
pub fn shiftCounts2(&self, stateCount:&[u32]) {
doShiftCounts2(stateCount);
pub fn shiftCounts2(&self, stateCount: &mut [u32; 5]) {
Self::doShiftCounts2(stateCount);
}
pub fn doClearCounts(icounts:&[u32]) {
Arrays.fill(counts, 0);
pub fn doClearCounts(counts: &mut [u32; 5]) {
counts.fill(0)
}
pub fn doShiftCounts2( stateCount:&[u32]) {
pub fn doShiftCounts2(stateCount: &mut [u32]) {
stateCount[0] = stateCount[2];
stateCount[1] = stateCount[3];
stateCount[2] = stateCount[4];
@@ -261,64 +282,65 @@ impl FinderPatternFinder{
* @param centerJ center of the section that appears to cross a finder pattern
* @return true if proportions are withing expected limits
*/
fn crossCheckDiagonal(&self, centerI:u32, centerJ:u32) -> bool{
int[] stateCount = getCrossCheckStateCount();
fn crossCheckDiagonal(&mut self, centerI: u32, centerJ: u32) -> bool {
let _state_count = self.getCrossCheckStateCount();
// Start counting up, left from center finding black center mass
int i = 0;
while (centerI >= i && centerJ >= i && image.get(centerJ - i, centerI - i)) {
stateCount[2]++;
i++;
let mut i = 0;
while centerI >= i && centerJ >= i && self.image.get(centerJ - i, centerI - i) {
self.crossCheckStateCount[2] += 1;
i += 1;
}
if (stateCount[2] == 0) {
if self.crossCheckStateCount[2] == 0 {
return false;
}
// Continue up, left finding white space
while (centerI >= i && centerJ >= i && !image.get(centerJ - i, centerI - i)) {
stateCount[1]++;
i++;
while centerI >= i && centerJ >= i && !self.image.get(centerJ - i, centerI - i) {
self.crossCheckStateCount[1] += 1;
i += 1;
}
if (stateCount[1] == 0) {
if self.crossCheckStateCount[1] == 0 {
return false;
}
// Continue up, left finding black border
while (centerI >= i && centerJ >= i && image.get(centerJ - i, centerI - i)) {
stateCount[0]++;
i++;
while centerI >= i && centerJ >= i && self.image.get(centerJ - i, centerI - i) {
self.crossCheckStateCount[0] += 1;
i += 1;
}
if (stateCount[0] == 0) {
if self.crossCheckStateCount[0] == 0 {
return false;
}
int maxI = image.getHeight();
int maxJ = image.getWidth();
let maxI = self.image.getHeight();
let maxJ = self.image.getWidth();
// Now also count down, right from center
i = 1;
while (centerI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, centerI + i)) {
stateCount[2]++;
i++;
while centerI + i < maxI && centerJ + i < maxJ && self.image.get(centerJ + i, centerI + i) {
self.crossCheckStateCount[2] += 1;
i += 1;
}
while (centerI + i < maxI && centerJ + i < maxJ && !image.get(centerJ + i, centerI + i)) {
stateCount[3]++;
i++;
while centerI + i < maxI && centerJ + i < maxJ && !self.image.get(centerJ + i, centerI + i)
{
self.crossCheckStateCount[3] += 1;
i += 1;
}
if (stateCount[3] == 0) {
if self.crossCheckStateCount[3] == 0 {
return false;
}
while (centerI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, centerI + i)) {
stateCount[4]++;
i++;
while centerI + i < maxI && centerJ + i < maxJ && self.image.get(centerJ + i, centerI + i) {
self.crossCheckStateCount[4] += 1;
i += 1;
}
if (stateCount[4] == 0) {
if self.crossCheckStateCount[4] == 0 {
return false;
}
return foundPatternDiagonal(stateCount);
Self::foundPatternDiagonal(&self.crossCheckStateCount)
}
/**
@@ -332,71 +354,83 @@ impl FinderPatternFinder{
* observed in any reading state, based on the results of the horizontal scan
* @return vertical center of finder pattern, or {@link Float#NaN} if not found
*/
fn crossCheckVertical( &self, startI:u32, centerJ:u32, maxCount:u32,
originalStateCountTotal:u32) -> f32{
BitMatrix image = this.image;
fn crossCheckVertical(
&mut self,
startI: u32,
centerJ: u32,
maxCount: u32,
originalStateCountTotal: u32,
) -> f32 {
// let image = &self.image;
int maxI = image.getHeight();
int[] stateCount = getCrossCheckStateCount();
let maxI = self.image.getHeight();
let _stateCount = self.getCrossCheckStateCount();
// Start counting up from center
int i = startI;
while (i >= 0 && image.get(centerJ, i)) {
stateCount[2]++;
i--;
let mut i = startI;
while i >= 0 && self.image.get(centerJ, i) {
self.crossCheckStateCount[2] += 1;
i -= 1;
}
if (i < 0) {
return Float.NaN;
if i < 0 {
return f32::NAN;
}
while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {
stateCount[1]++;
i--;
while i >= 0 && !self.image.get(centerJ, i) && self.crossCheckStateCount[1] <= maxCount {
self.crossCheckStateCount[1] += 1;
i -= 1;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount) {
return Float.NaN;
if i < 0 || self.crossCheckStateCount[1] > maxCount {
return f32::NAN;
}
while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {
stateCount[0]++;
i--;
while i >= 0 && self.image.get(centerJ, i) && self.crossCheckStateCount[0] <= maxCount {
self.crossCheckStateCount[0] += 1;
i -= 1;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
if self.crossCheckStateCount[0] > maxCount {
return f32::NAN;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image.get(centerJ, i)) {
stateCount[2]++;
i++;
while i < maxI && self.image.get(centerJ, i) {
self.crossCheckStateCount[2] += 1;
i += 1;
}
if (i == maxI) {
return Float.NaN;
if i == maxI {
return f32::NAN;
}
while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {
stateCount[3]++;
i++;
while i < maxI && !self.image.get(centerJ, i) && self.crossCheckStateCount[3] < maxCount {
self.crossCheckStateCount[3] += 1;
i += 1;
}
if (i == maxI || stateCount[3] >= maxCount) {
return Float.NaN;
if i == maxI || self.crossCheckStateCount[3] >= maxCount {
return f32::NAN;
}
while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {
stateCount[4]++;
i++;
while i < maxI && self.image.get(centerJ, i) && self.crossCheckStateCount[4] < maxCount {
self.crossCheckStateCount[4] += 1;
i += 1;
}
if (stateCount[4] >= maxCount) {
return Float.NaN;
if self.crossCheckStateCount[4] >= maxCount {
return f32::NAN;
}
// If we found a finder-pattern-like section, but its size is more than 40% different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {
return Float.NaN;
let stateCountTotal = self.crossCheckStateCount[0]
+ self.crossCheckStateCount[1]
+ self.crossCheckStateCount[2]
+ self.crossCheckStateCount[3]
+ self.crossCheckStateCount[4];
if 5 * (stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal {
return f32::NAN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : Float.NaN;
if Self::foundPatternCross(&self.crossCheckStateCount) {
Self::centerFromEnd(&self.crossCheckStateCount, i)
} else {
f32::NAN
}
}
/**
@@ -404,68 +438,80 @@ impl FinderPatternFinder{
* except it reads horizontally instead of vertically. This is used to cross-cross
* check a vertical cross check and locate the real center of the alignment pattern.</p>
*/
fn crossCheckHorizontal(&self, startJ:u32, centerI:u32, maxCount:u32,
originalStateCountTotal:u32) -> f32{
BitMatrix image = this.image;
fn crossCheckHorizontal(
&mut self,
startJ: u32,
centerI: u32,
maxCount: u32,
originalStateCountTotal: u32,
) -> f32 {
// let image = &self.image;
int maxJ = image.getWidth();
int[] stateCount = getCrossCheckStateCount();
let maxJ = self.image.getWidth();
let _stateCount = self.getCrossCheckStateCount();
int j = startJ;
while (j >= 0 && image.get(j, centerI)) {
stateCount[2]++;
j--;
let mut j = startJ;
while j >= 0 && self.image.get(j, centerI) {
self.crossCheckStateCount[2] += 1;
j -= 1;
}
if (j < 0) {
return Float.NaN;
if j < 0 {
return f32::NAN;
}
while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {
stateCount[1]++;
j--;
while j >= 0 && !self.image.get(j, centerI) && self.crossCheckStateCount[1] <= maxCount {
self.crossCheckStateCount[1] += 1;
j -= 1;
}
if (j < 0 || stateCount[1] > maxCount) {
return Float.NaN;
if j < 0 || self.crossCheckStateCount[1] > maxCount {
return f32::NAN;
}
while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {
stateCount[0]++;
j--;
while j >= 0 && self.image.get(j, centerI) && self.crossCheckStateCount[0] <= maxCount {
self.crossCheckStateCount[0] += 1;
j -= 1;
}
if (stateCount[0] > maxCount) {
return Float.NaN;
if self.crossCheckStateCount[0] > maxCount {
return f32::NAN;
}
j = startJ + 1;
while (j < maxJ && image.get(j, centerI)) {
stateCount[2]++;
j++;
while j < maxJ && self.image.get(j, centerI) {
self.crossCheckStateCount[2] += 1;
j += 1;
}
if (j == maxJ) {
return Float.NaN;
if j == maxJ {
return f32::NAN;
}
while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {
stateCount[3]++;
j++;
while j < maxJ && !self.image.get(j, centerI) && self.crossCheckStateCount[3] < maxCount {
self.crossCheckStateCount[3] += 1;
j += 1;
}
if (j == maxJ || stateCount[3] >= maxCount) {
return Float.NaN;
if j == maxJ || self.crossCheckStateCount[3] >= maxCount {
return f32::NAN;
}
while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {
stateCount[4]++;
j++;
while j < maxJ && self.image.get(j, centerI) && self.crossCheckStateCount[4] < maxCount {
self.crossCheckStateCount[4] += 1;
j += 1;
}
if (stateCount[4] >= maxCount) {
return Float.NaN;
if self.crossCheckStateCount[4] >= maxCount {
return f32::NAN;
}
// If we found a finder-pattern-like section, but its size is significantly different than
// the original, assume it's a false positive
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {
return Float.NaN;
let stateCountTotal = self.crossCheckStateCount[0]
+ self.crossCheckStateCount[1]
+ self.crossCheckStateCount[2]
+ self.crossCheckStateCount[3]
+ self.crossCheckStateCount[4];
if 5 * (stateCountTotal - originalStateCountTotal) >= originalStateCountTotal {
return f32::NAN;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : Float.NaN;
if Self::foundPatternCross(&self.crossCheckStateCount) {
Self::centerFromEnd(&self.crossCheckStateCount, j)
} else {
f32::NAN
}
}
/**
@@ -478,8 +524,14 @@ impl FinderPatternFinder{
* @see #handlePossibleCenter(int[], int, int)
*/
#[deprecated]
pub fn handlePossibleCenter(&self, stateCount:&[u32], i:u32, j:u32, pureBarcode:bool) -> bool{
return handlePossibleCenter(stateCount, i, j);
pub fn handlePossibleCenterWithPureBarcodeFlag(
&mut self,
stateCount: &[u32],
i: u32,
j: u32,
_pureBarcode: bool,
) -> bool {
self.handlePossibleCenter(stateCount, i, j)
}
/**
@@ -499,31 +551,38 @@ impl FinderPatternFinder{
* @param j end of possible finder pattern in row
* @return true if a finder pattern candidate was found this time
*/
pub fn handlePossibleCenter(&self, stateCount:&[u32], i:u32, j:u32) -> bool{
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +
stateCount[4];
float centerJ = centerFromEnd(stateCount, j);
float centerI = crossCheckVertical(i, (int) centerJ, stateCount[2], stateCountTotal);
if (!Float.isNaN(centerI)) {
pub fn handlePossibleCenter(&mut self, stateCount: &[u32], i: u32, j: u32) -> bool {
let stateCountTotal =
stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];
let mut centerJ = Self::centerFromEnd(stateCount, j);
let centerI = self.crossCheckVertical(i, centerJ as u32, stateCount[2], stateCountTotal);
if !centerI.is_nan() {
// Re-cross check
centerJ = crossCheckHorizontal((int) centerJ, (int) centerI, stateCount[2], stateCountTotal);
if (!Float.isNaN(centerJ) && crossCheckDiagonal((int) centerI, (int) centerJ)) {
float estimatedModuleSize = stateCountTotal / 7.0f;
boolean found = false;
for (int index = 0; index < possibleCenters.size(); index++) {
FinderPattern center = possibleCenters.get(index);
centerJ = self.crossCheckHorizontal(
centerJ as u32,
centerI as u32,
stateCount[2],
stateCountTotal,
);
if !centerJ.is_nan() && self.crossCheckDiagonal(centerI as u32, centerJ as u32) {
let estimatedModuleSize = stateCountTotal as f32 / 7.0;
let mut found = false;
for index in 0..self.possibleCenters.len() {
// for (int index = 0; index < possibleCenters.size(); index++) {
let center = self.possibleCenters.get(index).unwrap();
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {
possibleCenters.set(index, center.combineEstimate(centerI, centerJ, estimatedModuleSize));
if center.aboutEquals(estimatedModuleSize, centerI, centerJ) {
self.possibleCenters[index] =
center.combineEstimate(centerI, centerJ, estimatedModuleSize);
found = true;
break;
}
}
if (!found) {
FinderPattern point = new FinderPattern(centerJ, centerI, estimatedModuleSize);
possibleCenters.add(point);
if (resultPointCallback != null) {
resultPointCallback.foundPossibleRXingResultPoint(point);
if !found {
let point = FinderPattern::new(centerJ, centerI, estimatedModuleSize);
self.possibleCenters.push(point);
if self.resultPointCallback.is_some() {
self.resultPointCallback.as_ref().unwrap()(&point);
}
}
return true;
@@ -538,25 +597,29 @@ impl FinderPatternFinder{
* allow us to infer that the third pattern must lie below a certain point farther
* down in the image.
*/
fn findRowSkip(&self) -> u32{
int max = possibleCenters.size();
if (max <= 1) {
fn findRowSkip(&mut self) -> u32 {
let max = self.possibleCenters.len();
if max <= 1 {
return 0;
}
RXingResultPoint firstConfirmedCenter = null;
for (FinderPattern center : possibleCenters) {
if (center.getCount() >= CENTER_QUORUM) {
if (firstConfirmedCenter == null) {
firstConfirmedCenter = center;
let mut firstConfirmedCenter = None;
for center in &self.possibleCenters {
// for (FinderPattern center : possibleCenters) {
if center.getCount() >= Self::CENTER_QUORUM {
if firstConfirmedCenter.is_none() {
firstConfirmedCenter = Some(center);
} else {
// We have two confirmed centers
// How far down can we skip before resuming looking for the next
// pattern? In the worst case, only the difference between the
// difference in the x / y coordinates of the two centers.
// This is the case where you find top left last.
hasSkipped = true;
return (int) (Math.abs(firstConfirmedCenter.getX() - center.getX()) -
Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2;
self.hasSkipped = true;
let fnp = firstConfirmedCenter.unwrap();
return (((fnp.getX() - center.getX().abs())
- (fnp.getY() - center.getY()).abs())
/ 2.0)
.floor() as u32;
}
}
}
@@ -569,37 +632,40 @@ impl FinderPatternFinder{
* candidates is "pretty similar"
*/
fn haveMultiplyConfirmedCenters(&self) -> bool {
int confirmedCount = 0;
float totalModuleSize = 0.0f;
int max = possibleCenters.size();
for (FinderPattern pattern : possibleCenters) {
if (pattern.getCount() >= CENTER_QUORUM) {
confirmedCount++;
let mut confirmedCount = 0;
let mut totalModuleSize = 0.0;
let max = self.possibleCenters.len();
for pattern in &self.possibleCenters {
// for (FinderPattern pattern : possibleCenters) {
if pattern.getCount() >= Self::CENTER_QUORUM {
confirmedCount += 1;
totalModuleSize += pattern.getEstimatedModuleSize();
}
}
if (confirmedCount < 3) {
if confirmedCount < 3 {
return false;
}
// OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive"
// and that we need to keep looking. We detect this by asking if the estimated module sizes
// vary too much. We arbitrarily say that when the total deviation from average exceeds
// 5% of the total module size estimates, it's too much.
float average = totalModuleSize / max;
float totalDeviation = 0.0f;
for (FinderPattern pattern : possibleCenters) {
totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);
let average = totalModuleSize / max as f32;
let mut totalDeviation = 0.0;
for pattern in &self.possibleCenters {
// for (FinderPattern pattern : possibleCenters) {
totalDeviation += (pattern.getEstimatedModuleSize() - average).abs();
}
return totalDeviation <= 0.05f * totalModuleSize;
return totalDeviation <= 0.05 * totalModuleSize;
}
/**
* Get square of distance between a and b.
*/
fn squaredDistance(a: &FinderPattern, b: &FinderPattern) -> f64 {
double x = a.getX() - b.getX();
double y = a.getY() - b.getY();
return x * x + y * y;
let x = a.getX() as f64 - b.getX() as f64;
let y = a.getY() as f64 - b.getY() as f64;
x * x + y * y
}
/**
@@ -607,67 +673,88 @@ impl FinderPatternFinder{
* those have similar module size and form a shape closer to a isosceles right triangle.
* @throws NotFoundException if 3 such finder patterns do not exist
*/
fn selectBestPatterns(&self) -> Result<Vec<FinderPattern>,Exceptions> {
int startSize = possibleCenters.size();
if (startSize < 3) {
fn selectBestPatterns(&mut self) -> Result<[FinderPattern; 3], Exceptions> {
let startSize = self.possibleCenters.len();
if startSize < 3 {
// Couldn't find enough finder patterns
throw NotFoundException.getNotFoundInstance();
return Err(Exceptions::NotFoundException("".to_owned()));
}
possibleCenters.sort(moduleComparator);
self.possibleCenters.sort_by(|x, y| {
x.getEstimatedModuleSize()
.partial_cmp(&y.getEstimatedModuleSize())
.unwrap()
// Float.compare(center1.getEstimatedModuleSize(), center2.getEstimatedModuleSize());
});
double distortion = Double.MAX_VALUE;
FinderPattern[] bestPatterns = new FinderPattern[3];
// self.possibleCenters.sort(self.moduleComparator);
for (int i = 0; i < possibleCenters.size() - 2; i++) {
FinderPattern fpi = possibleCenters.get(i);
float minModuleSize = fpi.getEstimatedModuleSize();
let mut distortion = f64::MAX;
let mut bestPatterns = [None; 3];
for (int j = i + 1; j < possibleCenters.size() - 1; j++) {
FinderPattern fpj = possibleCenters.get(j);
double squares0 = squaredDistance(fpi, fpj);
for i in 0..self.possibleCenters.len() {
// for (int i = 0; i < possibleCenters.size() - 2; i++) {
let fpi = if let Some(f) = self.possibleCenters.get(i) {
f
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
};
let minModuleSize = fpi.getEstimatedModuleSize();
for (int k = j + 1; k < possibleCenters.size(); k++) {
FinderPattern fpk = possibleCenters.get(k);
float maxModuleSize = fpk.getEstimatedModuleSize();
if (maxModuleSize > minModuleSize * 1.4f) {
for j in (i + 1)..(self.possibleCenters.len() - 1) {
// for (int j = i + 1; j < possibleCenters.size() - 1; j++) {
let fpj = if let Some(f) = self.possibleCenters.get(j) {
f
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
};
let squares0 = Self::squaredDistance(fpi, fpj);
for k in (j + 1)..(self.possibleCenters.len()) {
// for (int k = j + 1; k < possibleCenters.size(); k++) {
let fpk = if let Some(f) = self.possibleCenters.get(k) {
f
} else {
return Err(Exceptions::NotFoundException("".to_owned()));
};
let maxModuleSize = fpk.getEstimatedModuleSize();
if maxModuleSize > minModuleSize * 1.4 {
// module size is not similar
continue;
}
double a = squares0;
double b = squaredDistance(fpj, fpk);
double c = squaredDistance(fpi, fpk);
let mut a = squares0;
let mut b = Self::squaredDistance(fpj, fpk);
let mut c = Self::squaredDistance(fpi, fpk);
// sorts ascending - inlined
if (a < b) {
if (b > c) {
if (a < c) {
double temp = b;
if a < b {
if b > c {
if a < c {
let temp = b;
b = c;
c = temp;
} else {
double temp = a;
let temp = a;
a = c;
c = b;
b = temp;
}
}
} else {
if (b < c) {
if (a < c) {
double temp = a;
if b < c {
if a < c {
let temp = a;
a = b;
b = temp;
} else {
double temp = a;
let temp = a;
a = b;
b = c;
c = temp;
}
} else {
double temp = a;
let temp = a;
a = c;
c = temp;
}
@@ -678,24 +765,32 @@ impl FinderPatternFinder{
// we need to check both two equal sides separately.
// The value of |c^2 - 2 * b^2| + |c^2 - 2 * a^2| increases as dissimilarity
// from isosceles right triangle.
double d = Math.abs(c - 2 * b) + Math.abs(c - 2 * a);
if (d < distortion) {
let d = (c - 2.0 * b).abs() + (c - 2.0 * a).abs();
if d < distortion {
distortion = d;
bestPatterns[0] = fpi;
bestPatterns[1] = fpj;
bestPatterns[2] = fpk;
bestPatterns = [Some(*fpi), Some(*fpj), Some(*fpk)];
// bestPatterns[0] = *fpi;
// bestPatterns[1] = *fpj;
// bestPatterns[2] = *fpk;
}
}
}
}
if (distortion == Double.MAX_VALUE) {
throw NotFoundException.getNotFoundInstance();
if distortion == f64::MAX {
return Err(Exceptions::NotFoundException("".to_owned()));
}
return bestPatterns;
if bestPatterns[0].is_none() {
return Err(Exceptions::NotFoundException("".to_owned()));
}
let p1 = bestPatterns[0].unwrap();
let p2 = bestPatterns[1].unwrap();
let p3 = bestPatterns[2].unwrap();
Ok([p1, p2, p3])
}
}
// /**