qrcode multi detector port

This commit is contained in:
Henry Schimke
2022-11-28 17:50:58 -06:00
parent baa8406855
commit 5273136c96
4 changed files with 314 additions and 261 deletions

View File

@@ -14,7 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{qrcode::detector::{Detector, QRCodeDetectorResult}, common::{BitMatrix, DetectorRXingResult}, DecodingHintDictionary, Exceptions, DecodeHintType}; use crate::{
common::{BitMatrix, DetectorRXingResult},
qrcode::detector::{Detector, QRCodeDetectorResult},
DecodeHintType, DecodeHintValue, DecodingHintDictionary, Exceptions,
};
use super::MultiFinderPatternFinder; use super::MultiFinderPatternFinder;
@@ -33,18 +37,26 @@ impl MultiDetector {
// private static final DetectorRXingResult[] EMPTY_DETECTOR_RESULTS = new DetectorRXingResult[0]; // private static final DetectorRXingResult[] EMPTY_DETECTOR_RESULTS = new DetectorRXingResult[0];
pub fn detectMulti(&self, hints:&DecodingHintDictionary) -> Result<Vec<QRCodeDetectorResult>,Exceptions> { pub fn detectMulti(
&self,
hints: &DecodingHintDictionary,
) -> Result<Vec<QRCodeDetectorResult>, Exceptions> {
let image = self.0.getImage(); let image = self.0.getImage();
let resultPointCallback = let resultPointCallback = if let Some(DecodeHintValue::NeedResultPointCallback(cb)) =
hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK); hints.get(&DecodeHintType::NEED_RESULT_POINT_CALLBACK)
let finder = MultiFinderPatternFinder::new(image, resultPointCallback); {
Some(*cb)
} else {
None
};
let mut finder = MultiFinderPatternFinder::new(image, resultPointCallback);
let infos = finder.findMulti(hints)?; let infos = finder.findMulti(hints)?;
if infos.len() == 0 { if infos.len() == 0 {
return Err(Exceptions::NotFoundException("".to_owned())) return Err(Exceptions::NotFoundException("".to_owned()));
} }
let result = Vec::new(); let mut result = Vec::new();
for info in infos { for info in infos {
if let Ok(potential) = self.0.processFinderPatternInfo(info) { if let Ok(potential) = self.0.processFinderPatternInfo(info) {
result.push(potential); result.push(potential);
@@ -58,5 +70,4 @@ impl MultiDetector {
Ok(result) Ok(result)
} }
} }

View File

@@ -14,14 +14,20 @@
* limitations under the License. * limitations under the License.
*/ */
use crate::{qrcode::detector::{FinderPatternFinder, FinderPattern, FinderPatternInfo}, common::BitMatrix, RXingResultPointCallback, Exceptions, DecodingHintDictionary}; use std::cmp::Ordering;
use crate::{
common::BitMatrix,
qrcode::detector::{FinderPattern, FinderPatternFinder, FinderPatternInfo},
result_point_utils, DecodeHintType, DecodingHintDictionary, Exceptions, RXingResultPoint,
RXingResultPointCallback,
};
// max. legal count of modules per QR code edge (177) // max. legal count of modules per QR code edge (177)
const MAX_MODULE_COUNT_PER_EDGE: f32 = 180_f32; const MAX_MODULE_COUNT_PER_EDGE: f32 = 180_f32;
// min. legal count per modules per QR code edge (11) // min. legal count per modules per QR code edge (11)
const MIN_MODULE_COUNT_PER_EDGE: f32 = 9_f32; const MIN_MODULE_COUNT_PER_EDGE: f32 = 9_f32;
/** /**
* More or less arbitrary cutoff point for determining if two finder patterns might belong * More or less arbitrary cutoff point for determining if two finder patterns might belong
* to the same code if they differ less than DIFF_MODSIZE_CUTOFF_PERCENT percent in their * to the same code if they differ less than DIFF_MODSIZE_CUTOFF_PERCENT percent in their
@@ -53,7 +59,6 @@ const MIN_MODULE_COUNT_PER_EDGE : f32= 9_f32;
pub struct MultiFinderPatternFinder(FinderPatternFinder); pub struct MultiFinderPatternFinder(FinderPatternFinder);
impl MultiFinderPatternFinder { impl MultiFinderPatternFinder {
// private static final FinderPatternInfo[] EMPTY_RESULT_ARRAY = new FinderPatternInfo[0]; // private static final FinderPatternInfo[] EMPTY_RESULT_ARRAY = new FinderPatternInfo[0];
// private static final FinderPattern[] EMPTY_FP_ARRAY = new FinderPattern[0]; // private static final FinderPattern[] EMPTY_FP_ARRAY = new FinderPattern[0];
// private static final FinderPattern[][] EMPTY_FP_2D_ARRAY = new FinderPattern[0][]; // private static final FinderPattern[][] EMPTY_FP_2D_ARRAY = new FinderPattern[0][];
@@ -61,21 +66,11 @@ impl MultiFinderPatternFinder {
// TODO MIN_MODULE_COUNT and MAX_MODULE_COUNT would be great hints to ask the user for // TODO MIN_MODULE_COUNT and MAX_MODULE_COUNT would be great hints to ask the user for
// since it limits the number of regions to decode // since it limits the number of regions to decode
pub fn new(image: &BitMatrix, resultPointCallback: Option<RXingResultPointCallback>) -> Self {
Self(FinderPatternFinder::with_callback(
// /** image.clone(),
// * A comparator that orders FinderPatterns by their estimated module size. resultPointCallback,
// */ ))
// private static final class ModuleSizeComparator implements Comparator<FinderPattern>, Serializable {
// @Override
// public int compare(FinderPattern center1, FinderPattern center2) {
// float value = center2.getEstimatedModuleSize() - center1.getEstimatedModuleSize();
// return value < 0.0 ? -1 : value > 0.0 ? 1 : 0;
// }
// }
pub fn new( image:&BitMatrix, resultPointCallback:&RXingResultPointCallback) -> Self {
Self(FinderPatternFinder::with_callback(image, resultPointCallback))
} }
/** /**
@@ -84,29 +79,36 @@ impl MultiFinderPatternFinder {
* size differs from the average among those patterns the least * size differs from the average among those patterns the least
* @throws NotFoundException if 3 such finder patterns do not exist * @throws NotFoundException if 3 such finder patterns do not exist
*/ */
fn selectMultipleBestPatterns(&self) -> Result<Vec<Vec<FinderPattern>>,Exceptions> { fn selectMultipleBestPatterns(&self) -> Result<Vec<[FinderPattern; 3]>, Exceptions> {
List<FinderPattern> possibleCenters = new ArrayList<>(); let mut possibleCenters = Vec::new(); //new ArrayList<>();
for (FinderPattern fp : getPossibleCenters()) { for fp in self.0.getPossibleCenters() {
if (fp.getCount() >= 2) { if fp.getCount() >= 2 {
possibleCenters.add(fp); possibleCenters.push(*fp);
} }
} }
int size = possibleCenters.size(); let size = possibleCenters.len();
if (size < 3) { if size < 3 {
// Couldn't find enough finder patterns // Couldn't find enough finder patterns
throw NotFoundException.getNotFoundInstance(); return Err(Exceptions::NotFoundException(
"Couldn't find enough finder patterns".to_owned(),
));
} }
/* /*
* Begin HE modifications to safely detect multiple codes of equal size * Begin HE modifications to safely detect multiple codes of equal size
*/ */
if (size == 3) { if size == 3 {
return new FinderPattern[][] { possibleCenters.toArray(EMPTY_FP_ARRAY) }; return Ok(vec![[
possibleCenters[0],
possibleCenters[1],
possibleCenters[2],
]]);
} }
// Sort by estimated module size to speed up the upcoming checks // Sort by estimated module size to speed up the upcoming checks
Collections.sort(possibleCenters, new ModuleSizeComparator()); possibleCenters.sort_by(compare_finder_patterns);
// Collections.sort(possibleCenters, new ModuleSizeComparator());
/* /*
* Now lets start: build a list of tuples of three finder locations that * Now lets start: build a list of tuples of three finder locations that
@@ -123,96 +125,103 @@ impl MultiFinderPatternFinder {
* So, if the layout seems right, lets have the decoder try to decode. * So, if the layout seems right, lets have the decoder try to decode.
*/ */
List<FinderPattern[]> results = new ArrayList<>(); // holder for the results let mut results = Vec::new(); //new ArrayList<>(); // holder for the results
for (int i1 = 0; i1 < (size - 2); i1++) { for i1 in 0..(size - 2) {
FinderPattern p1 = possibleCenters.get(i1); // for (int i1 = 0; i1 < (size - 2); i1++) {
if (p1 == null) { let Some(p1) = possibleCenters.get(i1)else {
continue; continue;
} };
for (int i2 = i1 + 1; i2 < (size - 1); i2++) { for i2 in (i1 + 1)..(size - 1) {
FinderPattern p2 = possibleCenters.get(i2); // for (int i2 = i1 + 1; i2 < (size - 1); i2++) {
if (p2 == null) { let Some(p2) = possibleCenters.get(i2) else {
continue; continue;
} };
// Compare the expected module sizes; if they are really off, skip // Compare the expected module sizes; if they are really off, skip
float vModSize12 = (p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()) / let vModSize12 = (p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize())
Math.min(p1.getEstimatedModuleSize(), p2.getEstimatedModuleSize()); / p1.getEstimatedModuleSize().min(p2.getEstimatedModuleSize());
float vModSize12A = Math.abs(p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()); let vModSize12A = (p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()).abs();
if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) { if vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT {
// break, since elements are ordered by the module size deviation there cannot be // break, since elements are ordered by the module size deviation there cannot be
// any more interesting elements for the given p1. // any more interesting elements for the given p1.
break; break;
} }
for (int i3 = i2 + 1; i3 < size; i3++) { for i3 in (i2 + 1)..size {
FinderPattern p3 = possibleCenters.get(i3); // for (int i3 = i2 + 1; i3 < size; i3++) {
if (p3 == null) { let Some( p3) = possibleCenters.get(i3)else {
continue; continue;
} };
// Compare the expected module sizes; if they are really off, skip // Compare the expected module sizes; if they are really off, skip
float vModSize23 = (p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()) / let vModSize23 = (p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize())
Math.min(p2.getEstimatedModuleSize(), p3.getEstimatedModuleSize()); / p2.getEstimatedModuleSize().min(p3.getEstimatedModuleSize());
float vModSize23A = Math.abs(p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()); let vModSize23A =
if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) { (p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()).abs();
if vModSize23A > DIFF_MODSIZE_CUTOFF
&& vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT
{
// break, since elements are ordered by the module size deviation there cannot be // break, since elements are ordered by the module size deviation there cannot be
// any more interesting elements for the given p1. // any more interesting elements for the given p1.
break; break;
} }
FinderPattern[] test = {p1, p2, p3}; let mut test = [*p1, *p2, *p3];
RXingResultPoint.orderBestPatterns(test); result_point_utils::orderBestPatterns(&mut test);
// Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal // Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal
FinderPatternInfo info = new FinderPatternInfo(test); let info = FinderPatternInfo::new(test);
float dA = RXingResultPoint.distance(info.getTopLeft(), info.getBottomLeft()); let dA = result_point_utils::distance(info.getTopLeft(), info.getBottomLeft());
float dC = RXingResultPoint.distance(info.getTopRight(), info.getBottomLeft()); let dC = result_point_utils::distance(info.getTopRight(), info.getBottomLeft());
float dB = RXingResultPoint.distance(info.getTopLeft(), info.getTopRight()); let dB = result_point_utils::distance(info.getTopLeft(), info.getTopRight());
// Check the sizes // Check the sizes
float estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0f); let estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0);
if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || if estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE
estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) { || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE
{
continue; continue;
} }
// Calculate the difference of the edge lengths in percent // Calculate the difference of the edge lengths in percent
float vABBC = Math.abs((dA - dB) / Math.min(dA, dB)); let vABBC = ((dA - dB) / dA.min(dB)).abs();
if (vABBC >= 0.1f) { if vABBC >= 0.1 {
continue; continue;
} }
// Calculate the diagonal length by assuming a 90° angle at topleft // Calculate the diagonal length by assuming a 90° angle at topleft
float dCpy = (float) Math.sqrt((double) dA * dA + (double) dB * dB); let dCpy =
((dA as f64) * (dA as f64) + (dB as f64) * (dB as f64)).sqrt() as f32;
// Compare to the real distance in % // Compare to the real distance in %
float vPyC = Math.abs((dC - dCpy) / Math.min(dC, dCpy)); let vPyC = ((dC - dCpy) / dC.min(dCpy)).abs();
if (vPyC >= 0.1f) { if vPyC >= 0.1 {
continue; continue;
} }
// All tests passed! // All tests passed!
results.add(test); results.push(test);
} }
} }
} }
if (!results.isEmpty()) { if !results.is_empty() {
return results.toArray(EMPTY_FP_2D_ARRAY); Ok(results)
} else {
Err(Exceptions::NotFoundException("no result".to_owned()))
}
} }
// Nothing found! pub fn findMulti(
throw NotFoundException.getNotFoundInstance(); &mut self,
} hints: &DecodingHintDictionary,
) -> Result<Vec<FinderPatternInfo>, Exceptions> {
pub fn findMulti(&self, hints:&DecodingHintDictionary) -> Result<Vec<FinderPatternInfo>,Exceptions> { let tryHarder = hints.contains_key(&DecodeHintType::TRY_HARDER);
boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); let image = self.0.getImage().clone();
BitMatrix image = getImage(); let maxI = image.getHeight();
int maxI = image.getHeight(); let maxJ = image.getWidth();
int maxJ = 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
@@ -220,59 +229,92 @@ impl MultiFinderPatternFinder {
// 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 * FinderPatternFinder::MAX_MODULES);
if (iSkip < MIN_SKIP || tryHarder) { if iSkip < FinderPatternFinder::MIN_SKIP || tryHarder {
iSkip = MIN_SKIP; iSkip = FinderPatternFinder::MIN_SKIP;
} }
int[] stateCount = new int[5]; let mut stateCount = [0_u32; 5]; //new int[5];
for (int i = iSkip - 1; i < maxI; i += iSkip) { let mut i = iSkip - 1;
while i < maxI {
// for (int i = iSkip - 1; i < maxI; 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++) { for j in 0..maxJ {
if (image.get(j, i)) { // for (int j = 0; j < maxJ; j++) {
if 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) && handlePossibleCenter(stateCount, i, j)) { // Yes // Counting black pixels
if currentState == 4 {
// A winner?
if FinderPatternFinder::foundPatternCross(&stateCount)
&& self.0.handlePossibleCenter(&stateCount, i, j)
{
// Yes
// 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;
} }
} }
} // for j=... } // for j=...
if (foundPatternCross(stateCount)) { if FinderPatternFinder::foundPatternCross(&stateCount) {
handlePossibleCenter(stateCount, i, maxJ); self.0.handlePossibleCenter(&stateCount, i, maxJ);
} }
i += iSkip;
} // for i=iSkip-1 ... } // for i=iSkip-1 ...
FinderPattern[][] patternInfo = selectMultipleBestPatterns(); let mut patternInfo = self.selectMultipleBestPatterns()?;
List<FinderPatternInfo> result = new ArrayList<>(); let mut result = Vec::new(); //new ArrayList<>();
for (FinderPattern[] pattern : patternInfo) { for pattern in patternInfo.iter_mut() {
RXingResultPoint.orderBestPatterns(pattern); result_point_utils::orderBestPatterns(pattern);
result.add(new FinderPatternInfo(pattern)); result.push(FinderPatternInfo::new(*pattern));
} }
if (result.isEmpty()) { // if result.isEmpty() {
return EMPTY_RESULT_ARRAY; // return EMPTY_RESULT_ARRAY;
// } else {
// return result.toArray(EMPTY_RESULT_ARRAY);
// }
Ok(result)
}
}
/**
* A comparator that orders FinderPatterns by their estimated module size.
*/
// private static final class ModuleSizeComparator implements Comparator<FinderPattern>, Serializable {
// @Override
fn compare_finder_patterns(center1: &FinderPattern, center2: &FinderPattern) -> Ordering {
let value = center2.getEstimatedModuleSize() - center1.getEstimatedModuleSize();
if value < 0.0 {
Ordering::Less
} else if value > 0.0 {
Ordering::Greater
} else { } else {
return result.toArray(EMPTY_RESULT_ARRAY); Ordering::Equal
} }
// return value < 0.0 ? -1 : value > 0.0 ? 1 : 0;
} }
// }
}

View File

@@ -37,10 +37,10 @@ pub struct FinderPatternFinder {
resultPointCallback: Option<RXingResultPointCallback>, resultPointCallback: Option<RXingResultPointCallback>,
} }
impl FinderPatternFinder { impl FinderPatternFinder {
const CENTER_QUORUM: usize = 2; pub 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 pub 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 pub const MAX_MODULES: u32 = 97; // support up to version 20 for mobile clients
/** /**
* <p>Creates a finder that will search the image for three finder patterns.</p> * <p>Creates a finder that will search the image for three finder patterns.</p>