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, BitMatrix, DefaultGridSampler, GridSampler,
}, },
exceptions::Exceptions, exceptions::Exceptions,
RXingResultPoint, RXingResultPoint, ResultPoint,
}; };
use super::AztecDetectorResult::AztecDetectorRXingResult; use super::AztecDetectorResult::AztecDetectorRXingResult;

View File

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

View File

@@ -1,8 +1,8 @@
pub mod aztec; pub mod aztec;
pub mod qrcode;
pub mod client; pub mod client;
pub mod common; pub mod common;
mod exceptions; mod exceptions;
pub mod qrcode;
pub use exceptions::Exceptions; pub use exceptions::Exceptions;
@@ -26,7 +26,6 @@ mod PlanarYUVLuminanceSourceTestCase;
#[cfg(test)] #[cfg(test)]
mod RGBLuminanceSourceTestCase; mod RGBLuminanceSourceTestCase;
pub type EncodingHintDictionary = HashMap<EncodeHintType, EncodeHintValue>; pub type EncodingHintDictionary = HashMap<EncodeHintType, EncodeHintValue>;
pub type DecodingHintDictionary = HashMap<DecodeHintType, DecodeHintValue>; pub type DecodingHintDictionary = HashMap<DecodeHintType, DecodeHintValue>;
pub type MetadataDictionary = HashMap<RXingResultMetadataType, RXingResultMetadataValue>; pub type MetadataDictionary = HashMap<RXingResultMetadataType, RXingResultMetadataValue>;
@@ -566,7 +565,7 @@ pub enum DecodeHintType {
* *
* @see DecodeHintType#NEED_RESULT_POINT_CALLBACK * @see DecodeHintType#NEED_RESULT_POINT_CALLBACK
*/ */
pub type RXingResultPointCallback = fn(&RXingResultPoint); pub type RXingResultPointCallback = fn(&dyn ResultPoint);
#[derive(Clone)] #[derive(Clone)]
pub enum DecodeHintValue { pub enum DecodeHintValue {
/** /**
@@ -1174,6 +1173,107 @@ impl fmt::Display for RXingResult {
//package com.google.zxing; //package com.google.zxing;
use crate::common::detector::MathUtils; 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 * <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> * 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 { pub const fn new(x: f32, y: f32) -> Self {
Self { x, y } Self { x, y }
} }
}
pub fn getX(&self) -> f32 { impl ResultPoint for RXingResultPoint {
fn getX(&self) -> f32 {
return self.x; return self.x;
} }
pub fn getY(&self) -> f32 { fn getY(&self) -> f32 {
return self.y; 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 { impl fmt::Display for RXingResultPoint {

View File

@@ -16,7 +16,7 @@
//RXingResultPoint //RXingResultPoint
use crate::RXingResultPoint; use crate::{RXingResultPoint, ResultPoint};
/** /**
* <p>Encapsulates an alignment pattern, which are the smaller square patterns found in * <p>Encapsulates an alignment pattern, which are the smaller square patterns found in
@@ -24,17 +24,27 @@ use crate::RXingResultPoint;
* *
* @author Sean Owen * @author Sean Owen
*/ */
#[derive(Clone)] #[derive(Debug,Clone, Copy,PartialEq)]
pub struct AlignmentPattern { pub struct AlignmentPattern {
estimatedModuleSize: f32, 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 { impl AlignmentPattern {
pub fn new(posX: f32, posY: f32, estimatedModuleSize: f32) -> Self { pub fn new(posX: f32, posY: f32, estimatedModuleSize: f32) -> Self {
Self { Self {
estimatedModuleSize, 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> * 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 { pub fn aboutEquals(&self, moduleSize: f32, i: f32, j: f32) -> bool {
if (i - self.internal_result_point.getY()).abs() <= moduleSize if (i - self.getY()).abs() <= moduleSize && (j - self.getX()).abs() <= moduleSize {
&& (j - self.internal_result_point.getX()).abs() <= moduleSize
{
let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs(); let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs();
return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize; 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. * 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 { pub fn combineEstimate(&self, i: f32, j: f32, newModuleSize: f32) -> AlignmentPattern {
let combinedX = (self.internal_result_point.getX() + j) / 2.0; let combinedX = (self.getX() + j) / 2.0;
let combinedY = (self.internal_result_point.getY() + i) / 2.0; let combinedY = (self.getY() + i) / 2.0;
let combinedModuleSize = (self.estimatedModuleSize + newModuleSize) / 2.0; let combinedModuleSize = (self.estimatedModuleSize + newModuleSize) / 2.0;
AlignmentPattern::new(combinedX, combinedY, combinedModuleSize) 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 // Hadn't found this before; save it
let point = AlignmentPattern::new(centerJ, centerI, estimatedModuleSize); let point = AlignmentPattern::new(centerJ, centerI, estimatedModuleSize);
if self.resultPointCallback.is_some() { if self.resultPointCallback.is_some() {
self.resultPointCallback.as_ref().unwrap()(point.as_RXingResultPoint()); self.resultPointCallback.as_ref().unwrap()(&point);
} }
self.possibleCenters.push(point); self.possibleCenters.push(point);
// if self.resultPointCallback.is_some() { // if self.resultPointCallback.is_some() {

View File

@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::RXingResultPoint; use crate::{RXingResultPoint, ResultPoint};
/** /**
* <p>Encapsulates a finder pattern, which are the three square patterns found in * <p>Encapsulates a finder pattern, which are the three square patterns found in
@@ -23,10 +23,21 @@ use crate::RXingResultPoint;
* *
* @author Sean Owen * @author Sean Owen
*/ */
#[derive(Debug,Clone, Copy,PartialEq)]
pub struct FinderPattern { pub struct FinderPattern {
estimatedModuleSize: f32, estimatedModuleSize: f32,
count: usize, 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 { impl FinderPattern {
@@ -38,7 +49,7 @@ impl FinderPattern {
Self { Self {
estimatedModuleSize, estimatedModuleSize,
count, 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> * 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 { pub fn aboutEquals(&self, moduleSize: f32, i: f32, j: f32) -> bool {
if (i - self.internal_result_point.getY()).abs() <= moduleSize if (i - self.getY()).abs() <= moduleSize && (j - self.getX()).abs() <= moduleSize {
&& (j - self.internal_result_point.getX()).abs() <= moduleSize
{
let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs(); let moduleSizeDiff = (moduleSize - self.estimatedModuleSize).abs();
return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize; return moduleSizeDiff <= 1.0 || moduleSizeDiff <= self.estimatedModuleSize;
} }
@@ -71,8 +80,8 @@ impl FinderPattern {
*/ */
pub fn combineEstimate(&self, i: f32, j: f32, newModuleSize: f32) -> FinderPattern { pub fn combineEstimate(&self, i: f32, j: f32, newModuleSize: f32) -> FinderPattern {
let combinedCount = self.count as f32 + 1.0; let combinedCount = self.count as f32 + 1.0;
let combinedX = (self.count as f32 * self.internal_result_point.getX() + j) / combinedCount; let combinedX = (self.count as f32 * self.getX() + j) / combinedCount;
let combinedY = (self.count as f32 * self.internal_result_point.getY() + i) / combinedCount; let combinedY = (self.count as f32 * self.getY() + i) / combinedCount;
let combinedModuleSize = let combinedModuleSize =
(self.count as f32 * self.estimatedModuleSize + newModuleSize) / combinedCount; (self.count as f32 * self.estimatedModuleSize + newModuleSize) / combinedCount;
FinderPattern::private_new( FinderPattern::private_new(

View File

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