format aztec

This commit is contained in:
Henry Schimke
2022-08-17 16:40:52 -05:00
parent 1035164fd7
commit ebe219b50d
4 changed files with 1622 additions and 1312 deletions

View File

@@ -2,14 +2,18 @@ pub mod decoder;
pub mod detector; pub mod detector;
pub mod encoder; pub mod encoder;
use crate::{ResultPoint,BarcodeFormat,EncodeHintType,Writer,Reader,ReaderException,WriterException};
use crate::common::{BitMatrix,DetectorResult,DecoderResult};
use crate::{BarcodeFormat,BinaryBitmap,DecodeHintType,FormatException,NotFoundException,Reader,Result,ResultMetadataType,ResultPoint,ResultPointCallback};
use crate::aztec::decoder::Decoder; use crate::aztec::decoder::Decoder;
use crate::aztec::detector::Detector; use crate::aztec::detector::Detector;
use crate::common::{BitMatrix, DecoderResult, DetectorResult};
use crate::{
BarcodeFormat, BinaryBitmap, DecodeHintType, FormatException, NotFoundException, Reader,
Result, ResultMetadataType, ResultPoint, ResultPointCallback,
};
use crate::{
BarcodeFormat, EncodeHintType, Reader, ReaderException, ResultPoint, Writer, WriterException,
};
use crate::aztec::encoder::{AztecCode,Encoder}; use crate::aztec::encoder::{AztecCode, Encoder};
// AztecDetectorResult.java // AztecDetectorResult.java
/** /**
@@ -20,43 +24,53 @@ use crate::aztec::encoder::{AztecCode,Encoder};
*/ */
pub struct AztecDetectorResult { pub struct AztecDetectorResult {
//super: DetectorResult; //super: DetectorResult;
compact: bool,
compact: bool, nb_datablocks: i32,
nb_datablocks: i32, nb_layers: i32,
nb_layers: i32, bits: BitMatrix,
bits: BitMatrix, points: Vec<ResultPoint>,
points: Vec<ResultPoint>,
} }
impl DetectorResult for AztecDetectorResult { impl DetectorResult for AztecDetectorResult {
fn get_bits(&self) -> BitMatrix { fn get_bits(&self) -> BitMatrix {
return self.bits; return self.bits;
} }
fn get_points(&self) -> Vec<ResultPoint> { fn get_points(&self) -> Vec<ResultPoint> {
return self.points; return self.points;
} }
} }
impl AztecDetectorResult { impl AztecDetectorResult {
pub fn new(
pub fn new( bits: &BitMatrix, points: &Vec<ResultPoint>, compact: bool, nb_datablocks: i32, nb_layers: i32) -> Self { bits: &BitMatrix,
Self { compact: compact, nb_datablocks: nd_datablocks, nb_layers: nb_layers, bits: bits, points: points } points: &Vec<ResultPoint>,
compact: bool,
nb_datablocks: i32,
nb_layers: i32,
) -> Self {
Self {
compact: compact,
nb_datablocks: nd_datablocks,
nb_layers: nb_layers,
bits: bits,
points: points,
}
} }
pub fn get_nb_layers(&self) -> i32 { pub fn get_nb_layers(&self) -> i32 {
return self.nb_layers; return self.nb_layers;
} }
pub fn get_nb_datablocks(&self) -> i32 { pub fn get_nb_datablocks(&self) -> i32 {
return self.nb_datablocks; return self.nb_datablocks;
} }
pub fn is_compact(&self) -> bool { pub fn is_compact(&self) -> bool {
return self.compact; return self.compact;
} }
} }
@@ -68,33 +82,35 @@ impl AztecDetectorResult {
* *
* @author David Olivier * @author David Olivier
*/ */
pub struct AztecReader { pub struct AztecReader {}
}
impl Reader for AztecReader { impl Reader for AztecReader {
/** /**
* Locates and decodes a Data Matrix code in an image. * Locates and decodes a Data Matrix code in an image.
* *
* @return a String representing the content encoded by the Data Matrix code * @return a String representing the content encoded by the Data Matrix code
* @throws NotFoundException if a Data Matrix code cannot be found * @throws NotFoundException if a Data Matrix code cannot be found
* @throws FormatException if a Data Matrix code cannot be decoded * @throws FormatException if a Data Matrix code cannot be decoded
*/ */
/*fn decode(&self, image: &BinaryBitmap) -> /* throws NotFoundException, FormatException */Result<Result, Rc<Exception>> { /*fn decode(&self, image: &BinaryBitmap) -> /* throws NotFoundException, FormatException */Result<Result, Rc<Exception>> {
return Ok(self.decode(image, null)); return Ok(self.decode(image, null));
}*/ }*/
fn decode(&self, image: &BinaryBitmap, hints: &Map<DecodeHintType, _>) -> Result<Result, ReaderException> { fn decode(
let not_found_exception: NotFoundException = null; &self,
let format_exception: FormatException = null; image: &BinaryBitmap,
let detector: Detector = Detector::new(&image.get_black_matrix()); hints: &Map<DecodeHintType, _>,
let mut points: Vec<ResultPoint> = null; ) -> Result<Result, ReaderException> {
let decoder_result: DecoderResult = null; let not_found_exception: NotFoundException = null;
let format_exception: FormatException = null;
let detector: Detector = Detector::new(&image.get_black_matrix());
let mut points: Vec<ResultPoint> = null;
let decoder_result: DecoderResult = null;
let detector_result: AztecDetectorResult = detector.detect(Some(false))?; let detector_result: AztecDetectorResult = detector.detect(Some(false))?;
points = detector_result.get_points()?; points = detector_result.get_points()?;
decoder_result = Decoder::new().decode(detector_result); decoder_result = Decoder::new().decode(detector_result);
/* /*
let tryResult1 = 0; let tryResult1 = 0;
'try1: loop { 'try1: loop {
{ {
@@ -137,28 +153,39 @@ impl Reader for AztecReader {
} }
*/ */
if hints != null { if hints != null {
let rpcb: ResultPointCallback = hints.get(DecodeHintType::NEED_RESULT_POINT_CALLBACK) as ResultPointCallback; let rpcb: ResultPointCallback =
hints.get(DecodeHintType::NEED_RESULT_POINT_CALLBACK) as ResultPointCallback;
if rpcb != null { if rpcb != null {
for point in points { for point in points {
rpcb.found_possible_result_point(&point); rpcb.found_possible_result_point(&point);
} }
} }
} }
let result: Result = Result::new(&decoder_result.get_text(), &decoder_result.get_raw_bytes(), &decoder_result.get_num_bits(), points, BarcodeFormat::AZTEC, &System::current_time_millis()); let result: Result = Result::new(
let byte_segments: List<Vec<i8>> = decoder_result.get_byte_segments(); &decoder_result.get_text(),
&decoder_result.get_raw_bytes(),
&decoder_result.get_num_bits(),
points,
BarcodeFormat::AZTEC,
&System::current_time_millis(),
);
let byte_segments: List<Vec<i8>> = decoder_result.get_byte_segments();
if byte_segments != null { if byte_segments != null {
result.put_metadata(ResultMetadataType::BYTE_SEGMENTS, &byte_segments); result.put_metadata(ResultMetadataType::BYTE_SEGMENTS, &byte_segments);
} }
let ec_level: String = decoder_result.get_e_c_level(); let ec_level: String = decoder_result.get_e_c_level();
if ec_level != null { if ec_level != null {
result.put_metadata(ResultMetadataType::ERROR_CORRECTION_LEVEL, &ec_level); result.put_metadata(ResultMetadataType::ERROR_CORRECTION_LEVEL, &ec_level);
} }
result.put_metadata(ResultMetadataType::SYMBOLOGY_IDENTIFIER, format!("]z{}", decoder_result.get_symbology_modifier())); result.put_metadata(
ResultMetadataType::SYMBOLOGY_IDENTIFIER,
format!("]z{}", decoder_result.get_symbology_modifier()),
);
return Ok(result); return Ok(result);
} }
fn reset(&self) { fn reset(&self) {
// do nothing // do nothing
} }
} }
@@ -167,30 +194,44 @@ impl Reader for AztecReader {
/** /**
* Renders an Aztec code as a {@link BitMatrix}. * Renders an Aztec code as a {@link BitMatrix}.
*/ */
pub struct AztecWriter { pub struct AztecWriter {}
}
impl Writer for AztecWriter { impl Writer for AztecWriter {
fn encode(
fn encode(&self, contents: &String, format: &BarcodeFormat, width: i32, height: i32, hints: Option<&HashMap<EncodeHintType, _>>) -> BitMatrix { &self,
contents: &String,
format: &BarcodeFormat,
width: i32,
height: i32,
hints: Option<&HashMap<EncodeHintType, _>>,
) -> BitMatrix {
// Do not add any ECI code by default // Do not add any ECI code by default
let mut charset: Charset = null; let mut charset: Charset = null;
let ecc_percent: i32 = Encoder::DEFAULT_EC_PERCENT; let ecc_percent: i32 = Encoder::DEFAULT_EC_PERCENT;
let mut layers: i32 = Encoder::DEFAULT_AZTEC_LAYERS; let mut layers: i32 = Encoder::DEFAULT_AZTEC_LAYERS;
if hints != null { if hints != null {
if hints.contains_key(EncodeHintType::CHARACTER_SET) { if hints.contains_key(EncodeHintType::CHARACTER_SET) {
charset = Charset::for_name(&hints.get(EncodeHintType::CHARACTER_SET).to_string()); charset = Charset::for_name(&hints.get(EncodeHintType::CHARACTER_SET).to_string());
} }
if hints.contains_key(EncodeHintType::ERROR_CORRECTION) { if hints.contains_key(EncodeHintType::ERROR_CORRECTION) {
ecc_percent = Integer::parse_int(&hints.get(EncodeHintType::ERROR_CORRECTION).to_string()); ecc_percent =
Integer::parse_int(&hints.get(EncodeHintType::ERROR_CORRECTION).to_string());
} }
if hints.contains_key(EncodeHintType::AZTEC_LAYERS) { if hints.contains_key(EncodeHintType::AZTEC_LAYERS) {
layers = Integer::parse_int(&hints.get(EncodeHintType::AZTEC_LAYERS).to_string()); layers = Integer::parse_int(&hints.get(EncodeHintType::AZTEC_LAYERS).to_string());
} }
} }
return ::encode(&contents, format, width, height, &charset, ecc_percent, layers); return ::encode(
&contents,
format,
width,
height,
&charset,
ecc_percent,
layers,
);
} }
/* /*
fn encode( contents: &String, format: &BarcodeFormat, width: i32, height: i32, charset: &Charset, ecc_percent: i32, layers: i32) -> BitMatrix { fn encode( contents: &String, format: &BarcodeFormat, width: i32, height: i32, charset: &Charset, ecc_percent: i32, layers: i32) -> BitMatrix {
if format != BarcodeFormat::AZTEC { if format != BarcodeFormat::AZTEC {
return Err( IllegalArgumentException::new(format!("Can only encode AZTEC, but got {}", format))); return Err( IllegalArgumentException::new(format!("Can only encode AZTEC, but got {}", format)));
@@ -198,16 +239,14 @@ impl Writer for AztecWriter {
let aztec: AztecCode = Encoder::encode(&contents, ecc_percent, layers, &charset); let aztec: AztecCode = Encoder::encode(&contents, ecc_percent, layers, &charset);
return ::render_result(aztec, width, height); return ::render_result(aztec, width, height);
}*/ }*/
} }
impl AztecWriter { impl AztecWriter {
fn render_result( code: &AztecCode, width: i32, height: i32) -> BitMatrix { fn render_result(code: &AztecCode, width: i32, height: i32) -> BitMatrix {
let input: BitMatrix = code.get_matrix(); let input: BitMatrix = code.get_matrix();
if input == null { if input == null {
return Err( IllegalStateException::new()); return Err(IllegalStateException::new());
} }
let input_width: i32 = input.get_width(); let input_width: i32 = input.get_width();
let input_height: i32 = input.get_height(); let input_height: i32 = input.get_height();
let output_width: i32 = Math::max(width, input_width); let output_width: i32 = Math::max(width, input_width);
@@ -218,30 +257,29 @@ impl AztecWriter {
let output: BitMatrix = BitMatrix::new(output_width, output_height); let output: BitMatrix = BitMatrix::new(output_width, output_height);
{ {
let input_y: i32 = 0; let input_y: i32 = 0;
let output_y: i32 = top_padding; let output_y: i32 = top_padding;
while input_y < input_height { while input_y < input_height {
{ {
// Write the contents of this row of the barcode // Write the contents of this row of the barcode
{ {
let input_x: i32 = 0; let input_x: i32 = 0;
let output_x: i32 = left_padding; let output_x: i32 = left_padding;
while input_x < input_width { while input_x < input_width {
{ {
if input.get(input_x, input_y) { if input.get(input_x, input_y) {
output.set_region(output_x, output_y, multiple, multiple); output.set_region(output_x, output_y, multiple, multiple);
} }
} }
input_x += 1; input_x += 1;
output_x += multiple; output_x += multiple;
} }
} }
}
} input_y += 1;
input_y += 1; output_y += multiple;
output_y += multiple;
} }
} }
return output; return output;
} }
} }

View File

@@ -1,7 +1,7 @@
use create::FormatException;
use crate::aztec::AztecDetectorResult; use crate::aztec::AztecDetectorResult;
use crate::common::{BitMatrix,CharacterSetECI,DecoderResult}; use crate::common::reedsolomon::{GenericGF, ReedSolomonDecoder, ReedSolomonException};
use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonException}; use crate::common::{BitMatrix, CharacterSetECI, DecoderResult};
use create::FormatException;
/** /**
* <p>The main class which implements Aztec Code decoding -- as opposed to locating and extracting * <p>The main class which implements Aztec Code decoding -- as opposed to locating and extracting
@@ -10,78 +10,101 @@ use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonExcepti
* @author David Olivier * @author David Olivier
*/ */
const UPPER_TABLE: vec![Vec<String>; 32] = vec!["CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS", ] const UPPER_TABLE: vec![Vec<String>; 32] = vec![
; "CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS",
];
const LOWER_TABLE: vec![Vec<String>; 32] = vec!["CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS", ] const LOWER_TABLE: vec![Vec<String>; 32] = vec![
; "CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS",
];
const MIXED_TABLE: vec![Vec<String>; 32] = vec!["CTRL_PS", " ", "\u{0001}", "\u{0002}", "\u{0003}", "\u{0004}", "\u{0005}", "\u{0006}", "\u{0007}", "\u{000b}", "\t", "\n", "\u{000d}", "\u{000f}", "\r", "\u{0021}", "\u{0022}", "\u{0023}", "\u{0024}", "\u{0025}", "@", "\\", "^", "_", "`", "|", "~", "\u{00b1}", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS", ] const MIXED_TABLE: vec![Vec<String>; 32] = vec![
; "CTRL_PS", " ", "\u{0001}", "\u{0002}", "\u{0003}", "\u{0004}", "\u{0005}", "\u{0006}",
"\u{0007}", "\u{000b}", "\t", "\n", "\u{000d}", "\u{000f}", "\r", "\u{0021}", "\u{0022}",
"\u{0023}", "\u{0024}", "\u{0025}", "@", "\\", "^", "_", "`", "|", "~", "\u{00b1}", "CTRL_LL",
"CTRL_UL", "CTRL_PL", "CTRL_BS",
];
const PUNCT_TABLE: vec![Vec<String>; 32] = vec!["FLG(n)", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL", ] const PUNCT_TABLE: vec![Vec<String>; 32] = vec![
; "FLG(n)", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*",
"+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL",
];
const DIGIT_TABLE: vec![Vec<String>; 16] = vec!["CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US", ] const DIGIT_TABLE: vec![Vec<String>; 16] = vec![
; "CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL",
"CTRL_US",
];
const DEFAULT_ENCODING: Charset = StandardCharsets::ISO_8859_1; const DEFAULT_ENCODING: Charset = StandardCharsets::ISO_8859_1;
pub struct Decoder { pub struct Decoder {
ddata: AztecDetectorResult,
ddata: AztecDetectorResult
} }
enum Table { enum Table {
UPPER(),
UPPER(), LOWER(), MIXED(), DIGIT(), PUNCT(), BINARY() LOWER(),
MIXED(),
DIGIT(),
PUNCT(),
BINARY(),
} }
impl Decoder { impl Decoder {
pub fn decode(
&self,
detector_result: &AztecDetectorResult,
pub fn decode(&self, detector_result: &AztecDetectorResult) -> Result<DecoderResult, FormatException> { ) -> Result<DecoderResult, FormatException> {
self.ddata = detector_result; self.ddata = detector_result;
let matrix: BitMatrix = detector_result.get_bits(); let matrix: BitMatrix = detector_result.get_bits();
let rawbits: Vec<bool> = self.extract_bits(&matrix); let rawbits: Vec<bool> = self.extract_bits(&matrix);
let corrected_bits: CorrectedBitsResult = self.correct_bits(&rawbits); let corrected_bits: CorrectedBitsResult = self.correct_bits(&rawbits);
let raw_bytes: Vec<i8> = ::convert_bool_array_to_byte_array(corrected_bits.correctBits); let raw_bytes: Vec<i8> = ::convert_bool_array_to_byte_array(corrected_bits.correctBits);
let result: String = ::get_encoded_data(corrected_bits.correctBits); let result: String = ::get_encoded_data(corrected_bits.correctBits);
let decoder_result: DecoderResult = DecoderResult::new(&raw_bytes, &result, null, &String::format("%d%%", corrected_bits.ecLevel), None, None, None); let decoder_result: DecoderResult = DecoderResult::new(
&raw_bytes,
&result,
null,
&String::format("%d%%", corrected_bits.ecLevel),
None,
None,
None,
);
decoder_result.set_num_bits(corrected_bits.correctBits.len()); decoder_result.set_num_bits(corrected_bits.correctBits.len());
return Ok(decoder_result); return Ok(decoder_result);
} }
// This method is used for testing the high-level encoder // This method is used for testing the high-level encoder
pub fn high_level_decode( corrected_bits: &Vec<bool>) -> /* throws FormatException */Result<String, Rc<Exception>> { pub fn high_level_decode(corrected_bits: &Vec<bool>) -> Result<String, Rc<Exception>> {
return Ok(::get_encoded_data(&corrected_bits)); return Ok(::get_encoded_data(&corrected_bits));
} }
/** /**
* Gets the string encoded in the aztec code bits * Gets the string encoded in the aztec code bits
* *
* @return the decoded string * @return the decoded string
*/ */
fn get_encoded_data( corrected_bits: &Vec<bool>) -> /* throws FormatException */Result<String, Rc<Exception>> { fn get_encoded_data(corrected_bits: &Vec<bool>) -> Result<String, Rc<Exception>> {
let end_index: i32 = corrected_bits.len(); let end_index: i32 = corrected_bits.len();
// table most recently latched to // table most recently latched to
let latch_table: Table = Table::UPPER; let latch_table: Table = Table::UPPER;
// table to use for the next read // table to use for the next read
let shift_table: Table = Table::UPPER; let shift_table: Table = Table::UPPER;
// Final decoded string result // Final decoded string result
// (correctedBits-5) / 4 is an upper bound on the size (all-digit result) // (correctedBits-5) / 4 is an upper bound on the size (all-digit result)
let result: StringBuilder = StringBuilder::new((corrected_bits.len() - 5) / 4); let result: StringBuilder = StringBuilder::new((corrected_bits.len() - 5) / 4);
// Intermediary buffer of decoded bytes, which is decoded into a string and flushed // Intermediary buffer of decoded bytes, which is decoded into a string and flushed
// when character encoding changes (ECI) or input ends. // when character encoding changes (ECI) or input ends.
let decoded_bytes: ByteArrayOutputStream = ByteArrayOutputStream::new(); let decoded_bytes: ByteArrayOutputStream = ByteArrayOutputStream::new();
let mut encoding: Charset = DEFAULT_ENCODING; let mut encoding: Charset = DEFAULT_ENCODING;
let mut index: i32 = 0; let mut index: i32 = 0;
while index < end_index { while index < end_index {
if shift_table == Table::BINARY { if shift_table == Table::BINARY {
if end_index - index < 5 { if end_index - index < 5 {
break; break;
} }
let mut length: i32 = ::read_code(&corrected_bits, index, 5); let mut length: i32 = ::read_code(&corrected_bits, index, 5);
index += 5; index += 5;
if length == 0 { if length == 0 {
if end_index - index < 11 { if end_index - index < 11 {
@@ -90,8 +113,8 @@ impl Decoder {
length = ::read_code(&corrected_bits, index, 11) + 31; length = ::read_code(&corrected_bits, index, 11) + 31;
index += 11; index += 11;
} }
{ {
let char_count: i32 = 0; let char_count: i32 = 0;
while char_count < length { while char_count < length {
{ {
if end_index - index < 8 { if end_index - index < 8 {
@@ -99,71 +122,68 @@ impl Decoder {
index = end_index; index = end_index;
break; break;
} }
let code: i32 = ::read_code(&corrected_bits, index, 8); let code: i32 = ::read_code(&corrected_bits, index, 8);
decoded_bytes.write(code as i8); decoded_bytes.write(code as i8);
index += 8; index += 8;
} }
char_count += 1; char_count += 1;
} }
} }
// Go back to whatever mode we had been in // Go back to whatever mode we had been in
shift_table = latch_table; shift_table = latch_table;
} else { } else {
let size: i32 = if shift_table == Table::DIGIT { 4 } else { 5 }; let size: i32 = if shift_table == Table::DIGIT { 4 } else { 5 };
if end_index - index < size { if end_index - index < size {
break; break;
} }
let code: i32 = ::read_code(&corrected_bits, index, size); let code: i32 = ::read_code(&corrected_bits, index, size);
index += size; index += size;
let str: String = ::get_character(shift_table, code); let str: String = ::get_character(shift_table, code);
if "FLG(n)".equals(&str) { if "FLG(n)".equals(&str) {
if end_index - index < 3 { if end_index - index < 3 {
break; break;
} }
let mut n: i32 = ::read_code(&corrected_bits, index, 3); let mut n: i32 = ::read_code(&corrected_bits, index, 3);
index += 3; index += 3;
// flush bytes, FLG changes state // flush bytes, FLG changes state
let tryResult1 = 0; let tryResult1 = 0;
result.append(&decoded_bytes.to_string(&encoding.name())); result.append(&decoded_bytes.to_string(&encoding.name()));
decoded_bytes.reset(); decoded_bytes.reset();
match n { match n {
0 => 0 => {
{ // translate FNC1 as ASCII 29
// translate FNC1 as ASCII 29 result.append(29 as char);
result.append(29 as char); break;
}
7 => {
// FLG(7) is reserved and illegal
return Err(FormatException::get_format_instance());
}
_ => {
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode
let mut eci: i32 = 0;
if end_index - index < 4 * n {
break; break;
} }
7 => while (n -= 1) > 0 {
{ let next_digit: i32 = ::read_code(&corrected_bits, index, 4);
// FLG(7) is reserved and illegal index += 4;
return Err( FormatException::get_format_instance()); if next_digit < 2 || next_digit > 11 {
// Not a decimal digit
return Err(FormatException::get_format_instance());
}
eci = eci * 10 + (next_digit - 2);
} }
_ => let charset_e_c_i: CharacterSetECI =
{ CharacterSetECI::get_character_set_e_c_i_by_value(eci);
// ECI is decimal integer encoded as 1-6 codes in DIGIT mode if charset_e_c_i == null {
let mut eci: i32 = 0; return Err(FormatException::get_format_instance());
if end_index - index < 4 * n {
break;
}
while (n -= 1) > 0 {
let next_digit: i32 = ::read_code(&corrected_bits, index, 4);
index += 4;
if next_digit < 2 || next_digit > 11 {
// Not a decimal digit
return Err( FormatException::get_format_instance());
}
eci = eci * 10 + (next_digit - 2);
}
let charset_e_c_i: CharacterSetECI = CharacterSetECI::get_character_set_e_c_i_by_value(eci);
if charset_e_c_i == null {
return Err( FormatException::get_format_instance());
}
encoding = charset_e_c_i.get_charset();
} }
encoding = charset_e_c_i.get_charset();
}
} }
// Go back to whatever mode we had been in // Go back to whatever mode we had been in
shift_table = latch_table; shift_table = latch_table;
@@ -180,7 +200,7 @@ impl Decoder {
} }
} else { } else {
// Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*. // Though stored as a table of strings for convenience, codes actually represent 1 or 2 *bytes*.
let b: Vec<i8> = str.get_bytes(StandardCharsets::US_ASCII); let b: Vec<i8> = str.get_bytes(StandardCharsets::US_ASCII);
decoded_bytes.write(&b, 0, b.len()); decoded_bytes.write(&b, 0, b.len());
// Go back to whatever mode we had been in // Go back to whatever mode we had been in
shift_table = latch_table; shift_table = latch_table;
@@ -188,93 +208,77 @@ impl Decoder {
} }
} }
result.append(&decoded_bytes.to_string(&encoding.name())); result.append(&decoded_bytes.to_string(&encoding.name()));
return Ok(result.to_string()); return Ok(result.to_string());
} }
/** /**
* gets the table corresponding to the char passed * gets the table corresponding to the char passed
*/ */
fn get_table( t: char) -> Table { fn get_table(t: char) -> Table {
match t { match t {
'L' => 'L' => {
{ return Table::LOWER;
return Table::LOWER; }
} 'P' => {
'P' => return Table::PUNCT;
{ }
return Table::PUNCT; 'M' => {
} return Table::MIXED;
'M' => }
{ 'D' => {
return Table::MIXED; return Table::DIGIT;
} }
'D' => 'B' => {
{ return Table::BINARY;
return Table::DIGIT; }
} 'U' => {}
'B' => _ => {
{ return Table::UPPER;
return Table::BINARY; }
}
'U' =>
{
}
_ =>
{
return Table::UPPER;
}
} }
} }
/** /**
* Gets the character (or string) corresponding to the passed code in the given table * Gets the character (or string) corresponding to the passed code in the given table
* *
* @param table the table used * @param table the table used
* @param code the code of the character * @param code the code of the character
*/ */
fn get_character( table: &Table, code: i32) -> String { fn get_character(table: &Table, code: i32) -> String {
match table { match table {
UPPER => UPPER => {
{ return UPPER_TABLE[code];
return UPPER_TABLE[code]; }
} LOWER => {
LOWER => return LOWER_TABLE[code];
{ }
return LOWER_TABLE[code]; MIXED => {
} return MIXED_TABLE[code];
MIXED => }
{ PUNCT => {
return MIXED_TABLE[code]; return PUNCT_TABLE[code];
} }
PUNCT => DIGIT => {
{ return DIGIT_TABLE[code];
return PUNCT_TABLE[code]; }
} _ => {
DIGIT => // Should not reach here.
{ return Err(IllegalStateException::new("Bad table"));
return DIGIT_TABLE[code]; }
}
_ =>
{
// Should not reach here.
return Err( IllegalStateException::new("Bad table"));
}
} }
} }
/** /**
* <p>Performs RS error correction on an array of bits.</p> * <p>Performs RS error correction on an array of bits.</p>
* *
* @return the corrected array * @return the corrected array
* @throws FormatException if the input contains too many errors * @throws FormatException if the input contains too many errors
*/ */
fn correct_bits(&self, rawbits: &Vec<bool>) -> Result<CorrectedBitsResult, FormatException> { fn correct_bits(&self, rawbits: &Vec<bool>) -> Result<CorrectedBitsResult, FormatException> {
let mut gf: GenericGF; let mut gf: GenericGF;
let codeword_size: i32; let codeword_size: i32;
if self.ddata.get_nb_layers() <= 2 { if self.ddata.get_nb_layers() <= 2 {
codeword_size = 6; codeword_size = 6;
gf = GenericGF::AZTEC_DATA_6; gf = GenericGF::AZTEC_DATA_6;
@@ -288,175 +292,198 @@ impl Decoder {
codeword_size = 12; codeword_size = 12;
gf = GenericGF::AZTEC_DATA_12; gf = GenericGF::AZTEC_DATA_12;
} }
let num_data_codewords: i32 = self.ddata.get_nb_datablocks(); let num_data_codewords: i32 = self.ddata.get_nb_datablocks();
let num_codewords: i32 = rawbits.len() / codeword_size; let num_codewords: i32 = rawbits.len() / codeword_size;
if num_codewords < num_data_codewords { if num_codewords < num_data_codewords {
return Err( FormatException::get_format_instance()); return Err(FormatException::get_format_instance());
} }
let mut offset: i32 = rawbits.len() % codeword_size; let mut offset: i32 = rawbits.len() % codeword_size;
let data_words: [i32; num_codewords] = [0; num_codewords]; let data_words: [i32; num_codewords] = [0; num_codewords];
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < num_codewords { while i < num_codewords {
{ {
data_words[i] = ::read_code(&rawbits, offset, codeword_size); data_words[i] = ::read_code(&rawbits, offset, codeword_size);
} }
i += 1; i += 1;
offset += codeword_size; offset += codeword_size;
} }
} }
let tryResult1 = 0; let tryResult1 = 0;
let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(gf)?; let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(gf)?;
rs_decoder.decode(&data_words, num_codewords - num_data_codewords); rs_decoder.decode(&data_words, num_codewords - num_data_codewords);
// Now perform the unstuffing operation. // Now perform the unstuffing operation.
// First, count how many bits are going to be thrown out as stuffing // First, count how many bits are going to be thrown out as stuffing
let mask: i32 = (1 << codeword_size) - 1; let mask: i32 = (1 << codeword_size) - 1;
let stuffed_bits: i32 = 0; let stuffed_bits: i32 = 0;
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < num_data_codewords { while i < num_data_codewords {
{ {
let data_word: i32 = data_words[i]; let data_word: i32 = data_words[i];
if data_word == 0 || data_word == mask { if data_word == 0 || data_word == mask {
return Err( FormatException::get_format_instance()); return Err(FormatException::get_format_instance());
} else if data_word == 1 || data_word == mask - 1 { } else if data_word == 1 || data_word == mask - 1 {
stuffed_bits += 1; stuffed_bits += 1;
} }
} }
i += 1; i += 1;
} }
} }
// Now, actually unpack the bits and remove the stuffing // Now, actually unpack the bits and remove the stuffing
let corrected_bits: [bool; num_data_codewords * codeword_size - stuffed_bits] = [false; num_data_codewords * codeword_size - stuffed_bits]; let corrected_bits: [bool; num_data_codewords * codeword_size - stuffed_bits] =
let mut index: i32 = 0; [false; num_data_codewords * codeword_size - stuffed_bits];
{ let mut index: i32 = 0;
let mut i: i32 = 0; {
let mut i: i32 = 0;
while i < num_data_codewords { while i < num_data_codewords {
{ {
let data_word: i32 = data_words[i]; let data_word: i32 = data_words[i];
if data_word == 1 || data_word == mask - 1 { if data_word == 1 || data_word == mask - 1 {
// next codewordSize-1 bits are all zeros or all ones // next codewordSize-1 bits are all zeros or all ones
Arrays::fill(&corrected_bits, index, index + codeword_size - 1, data_word > 1); Arrays::fill(
&corrected_bits,
index,
index + codeword_size - 1,
data_word > 1,
);
index += codeword_size - 1; index += codeword_size - 1;
} else { } else {
{ {
let mut bit: i32 = codeword_size - 1; let mut bit: i32 = codeword_size - 1;
while bit >= 0 { while bit >= 0 {
{ {
corrected_bits[index += 1 ] = (data_word & (1 << bit)) != 0; corrected_bits[index += 1] = (data_word & (1 << bit)) != 0;
} }
bit -= 1; bit -= 1;
} }
} }
} }
} }
i += 1; i += 1;
} }
} }
return Ok(CorrectedBitsResult::new(&corrected_bits, 100 * (num_codewords - num_data_codewords) / num_codewords)); return Ok(CorrectedBitsResult::new(
&corrected_bits,
100 * (num_codewords - num_data_codewords) / num_codewords,
));
} }
/** /**
* Gets the array of bits from an Aztec Code matrix * Gets the array of bits from an Aztec Code matrix
* *
* @return the array of bits * @return the array of bits
*/ */
fn extract_bits(&self, matrix: &BitMatrix) -> Vec<bool> { fn extract_bits(&self, matrix: &BitMatrix) -> Vec<bool> {
let compact: bool = self.ddata.is_compact(); let compact: bool = self.ddata.is_compact();
let layers: i32 = self.ddata.get_nb_layers(); let layers: i32 = self.ddata.get_nb_layers();
// not including alignment lines // not including alignment lines
let base_matrix_size: i32 = ( if compact { 11 } else { 14 }) + layers * 4; let base_matrix_size: i32 = (if compact { 11 } else { 14 }) + layers * 4;
let alignment_map: [i32; base_matrix_size] = [0; base_matrix_size]; let alignment_map: [i32; base_matrix_size] = [0; base_matrix_size];
let mut rawbits: [bool; ::total_bits_in_layer(layers, compact)] = [false; ::total_bits_in_layer(layers, compact)]; let mut rawbits: [bool; ::total_bits_in_layer(layers, compact)] =
[false; ::total_bits_in_layer(layers, compact)];
if compact { if compact {
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < alignment_map.len() { while i < alignment_map.len() {
{ {
alignment_map[i] = i; alignment_map[i] = i;
} }
i += 1; i += 1;
} }
} }
} else { } else {
let matrix_size: i32 = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15); let matrix_size: i32 = base_matrix_size + 1 + 2 * ((base_matrix_size / 2 - 1) / 15);
let orig_center: i32 = base_matrix_size / 2; let orig_center: i32 = base_matrix_size / 2;
let center: i32 = matrix_size / 2; let center: i32 = matrix_size / 2;
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < orig_center { while i < orig_center {
{ {
let new_offset: i32 = i + i / 15; let new_offset: i32 = i + i / 15;
alignment_map[orig_center - i - 1] = center - new_offset - 1; alignment_map[orig_center - i - 1] = center - new_offset - 1;
alignment_map[orig_center + i] = center + new_offset + 1; alignment_map[orig_center + i] = center + new_offset + 1;
} }
i += 1; i += 1;
} }
} }
} }
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
let row_offset: i32 = 0; let row_offset: i32 = 0;
while i < layers { while i < layers {
{ {
let row_size: i32 = (layers - i) * 4 + ( if compact { 9 } else { 12 }); let row_size: i32 = (layers - i) * 4 + (if compact { 9 } else { 12 });
// The top-left most point of this layer is <low, low> (not including alignment lines) // The top-left most point of this layer is <low, low> (not including alignment lines)
let low: i32 = i * 2; let low: i32 = i * 2;
// The bottom-right most point of this layer is <high, high> (not including alignment lines) // The bottom-right most point of this layer is <high, high> (not including alignment lines)
let high: i32 = base_matrix_size - 1 - low; let high: i32 = base_matrix_size - 1 - low;
// We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows // We pull bits from the two 2 x rowSize columns and two rowSize x 2 rows
{ {
let mut j: i32 = 0; let mut j: i32 = 0;
while j < row_size { while j < row_size {
{ {
let column_offset: i32 = j * 2; let column_offset: i32 = j * 2;
{ {
let mut k: i32 = 0; let mut k: i32 = 0;
while k < 2 { while k < 2 {
{ {
// left column // left column
rawbits[row_offset + column_offset + k] = matrix.get(alignment_map[low + k], alignment_map[low + j]); rawbits[row_offset + column_offset + k] = matrix.get(
alignment_map[low + k],
alignment_map[low + j],
);
// bottom row // bottom row
rawbits[row_offset + 2 * row_size + column_offset + k] = matrix.get(alignment_map[low + j], alignment_map[high - k]); rawbits
[row_offset + 2 * row_size + column_offset + k] =
matrix.get(
alignment_map[low + j],
alignment_map[high - k],
);
// right column // right column
rawbits[row_offset + 4 * row_size + column_offset + k] = matrix.get(alignment_map[high - k], alignment_map[high - j]); rawbits
[row_offset + 4 * row_size + column_offset + k] =
matrix.get(
alignment_map[high - k],
alignment_map[high - j],
);
// top row // top row
rawbits[row_offset + 6 * row_size + column_offset + k] = matrix.get(alignment_map[high - j], alignment_map[low + k]); rawbits
[row_offset + 6 * row_size + column_offset + k] =
matrix.get(
alignment_map[high - j],
alignment_map[low + k],
);
} }
k += 1; k += 1;
} }
} }
} }
j += 1; j += 1;
} }
} }
row_offset += row_size * 8; row_offset += row_size * 8;
} }
i += 1; i += 1;
} }
} }
return rawbits; return rawbits;
} }
/** /**
* Reads a code of given length and at given index in an array of bits * Reads a code of given length and at given index in an array of bits
*/ */
fn read_code( rawbits: &Vec<bool>, start_index: i32, length: i32) -> i32 { fn read_code(rawbits: &Vec<bool>, start_index: i32, length: i32) -> i32 {
let mut res: i32 = 0; let mut res: i32 = 0;
{ {
let mut i: i32 = start_index; let mut i: i32 = start_index;
while i < start_index + length { while i < start_index + length {
{ {
res <<= 1; res <<= 1;
@@ -465,17 +492,17 @@ impl Decoder {
} }
} }
i += 1; i += 1;
} }
} }
return res; return res;
} }
/** /**
* Reads a code of length 8 in an array of bits, padding with zeros * Reads a code of length 8 in an array of bits, padding with zeros
*/ */
fn read_byte( rawbits: &Vec<bool>, start_index: i32) -> i8 { fn read_byte(rawbits: &Vec<bool>, start_index: i32) -> i8 {
let n: i32 = rawbits.len() - start_index; let n: i32 = rawbits.len() - start_index;
if n >= 8 { if n >= 8 {
return ::read_code(&rawbits, start_index, 8) as i8; return ::read_code(&rawbits, start_index, 8) as i8;
} }
@@ -483,38 +510,39 @@ impl Decoder {
} }
/** /**
* Packs a bit array into bytes, most significant bit first * Packs a bit array into bytes, most significant bit first
*/ */
fn convert_bool_array_to_byte_array( bool_arr: &Vec<bool>) -> Vec<i8> { fn convert_bool_array_to_byte_array(bool_arr: &Vec<bool>) -> Vec<i8> {
let byte_arr: [i8; (bool_arr.len() + 7) / 8] = [0; (bool_arr.len() + 7) / 8]; let byte_arr: [i8; (bool_arr.len() + 7) / 8] = [0; (bool_arr.len() + 7) / 8];
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < byte_arr.len() { while i < byte_arr.len() {
{ {
byte_arr[i] = ::read_byte(&bool_arr, 8 * i); byte_arr[i] = ::read_byte(&bool_arr, 8 * i);
} }
i += 1; i += 1;
} }
} }
return byte_arr; return byte_arr;
} }
fn total_bits_in_layer( layers: i32, compact: bool) -> i32 { fn total_bits_in_layer(layers: i32, compact: bool) -> i32 {
return (( if compact { 88 } else { 112 }) + 16 * layers) * layers; return ((if compact { 88 } else { 112 }) + 16 * layers) * layers;
} }
} }
struct CorrectedBitsResult { struct CorrectedBitsResult {
correct_bits: Vec<bool>,
correct_bits: Vec<bool>, ec_level: i32,
ec_level: i32
} }
impl CorrectedBitsResult { impl CorrectedBitsResult {
fn new(correct_bits: &Vec<bool>, ec_level: i32) -> Self {
fn new( correct_bits: &Vec<bool>, ec_level: i32) -> Self { Self {
Self { correct_bits: correct_bits, ec_level: ec_level } correct_bits: correct_bits,
} ec_level: ec_level,
}
}
} }

View File

@@ -1,9 +1,8 @@
use crate::{NotFoundException,ResultPoint};
use crate::aztec::AztecDetectorResult; use crate::aztec::AztecDetectorResult;
use crate::common::{BitMatrix,GridSampler}; use crate::common::detector::{MathUtils, WhiteRectangleDetector};
use crate::common::detector::{MathUtils,WhiteRectangleDetector}; use crate::common::reedsolomon::{GenericGF, ReedSolomonDecoder, ReedSolomonException};
use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonException}; use crate::common::{BitMatrix, GridSampler};
use crate::{NotFoundException, ResultPoint};
/** /**
* Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code * Encapsulates logic that can detect an Aztec Code in an image, even if the Aztec Code
@@ -13,93 +12,115 @@ use crate::common::reedsolomon::{GenericGF,ReedSolomonDecoder,ReedSolomonExcepti
* @author Frank Yellin * @author Frank Yellin
*/ */
const EXPECTED_CORNER_BITS: vec![Vec<i32>; 4] = vec![// 07340 XXX .XX X.. ... const EXPECTED_CORNER_BITS: vec![Vec<i32>; 4] = vec![
0xee0, // 00734 ... XXX .XX X.. // 07340 XXX .XX X.. ...
0x1dc, // 04073 X.. ... XXX .XX 0xee0, // 00734 ... XXX .XX X..
0x83b, // 03407 .XX X.. ... XXX 0x1dc, // 04073 X.. ... XXX .XX
0x707, ] 0x83b, // 03407 .XX X.. ... XXX
; 0x707,
];
pub struct Detector { pub struct Detector {
image: BitMatrix,
image: BitMatrix, compact: bool,
compact: bool, nb_layers: i32,
nb_layers: i32, nb_data_blocks: i32,
nb_data_blocks: i32, nb_center_layers: i32,
nb_center_layers: i32, shift: i32,
shift: i32
} }
impl Detector { impl Detector {
pub fn new(image: &BitMatrix) -> Self {
pub fn new( image: &BitMatrix) -> Self { let new_d: Self;
let new_d : Self;
new_d.image = image; new_d.image = image;
new_d new_d
} }
/** /**
* Detects an Aztec Code in an image. * Detects an Aztec Code in an image.
* *
* @param isMirror if true, image is a mirror-image of original * @param isMirror if true, image is a mirror-image of original
* @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code * @return {@link AztecDetectorResult} encapsulating results of detecting an Aztec Code
* @throws NotFoundException if no Aztec Code can be found * @throws NotFoundException if no Aztec Code can be found
*/ */
pub fn detect(&self, is_mirror: Option<bool>) -> Result<AztecDetectorResult,NotFoundException> { pub fn detect(
&self,
is_mirror: Option<bool>,
) -> Result<AztecDetectorResult, NotFoundException> {
// 1. Get the center of the aztec matrix // 1. Get the center of the aztec matrix
let p_center: Point = self.get_matrix_center(); let p_center: Point = self.get_matrix_center();
// 2. Get the center points of the four diagonal points just outside the bull's eye // 2. Get the center points of the four diagonal points just outside the bull's eye
// [topRight, bottomRight, bottomLeft, topLeft] // [topRight, bottomRight, bottomLeft, topLeft]
let bulls_eye_corners: Vec<ResultPoint> = self.get_bulls_eye_corners(&p_center); let bulls_eye_corners: Vec<ResultPoint> = self.get_bulls_eye_corners(&p_center);
if is_mirror.unwrap_or(false) { if is_mirror.unwrap_or(false) {
let temp: ResultPoint = bulls_eye_corners[0]; let temp: ResultPoint = bulls_eye_corners[0];
bulls_eye_corners[0] = bulls_eye_corners[2]; bulls_eye_corners[0] = bulls_eye_corners[2];
bulls_eye_corners[2] = temp; bulls_eye_corners[2] = temp;
} }
// 3. Get the size of the matrix and other parameters from the bull's eye // 3. Get the size of the matrix and other parameters from the bull's eye
self.extract_parameters(&bulls_eye_corners); self.extract_parameters(&bulls_eye_corners);
// 4. Sample the grid // 4. Sample the grid
let bits: BitMatrix = self.sample_grid(&self.image, bulls_eye_corners[self.shift % 4], bulls_eye_corners[(self.shift + 1) % 4], bulls_eye_corners[(self.shift + 2) % 4], bulls_eye_corners[(self.shift + 3) % 4]); let bits: BitMatrix = self.sample_grid(
&self.image,
bulls_eye_corners[self.shift % 4],
bulls_eye_corners[(self.shift + 1) % 4],
bulls_eye_corners[(self.shift + 2) % 4],
bulls_eye_corners[(self.shift + 3) % 4],
);
// 5. Get the corners of the matrix. // 5. Get the corners of the matrix.
let corners: Vec<ResultPoint> = self.get_matrix_corner_points(&bulls_eye_corners); let corners: Vec<ResultPoint> = self.get_matrix_corner_points(&bulls_eye_corners);
return Ok(AztecDetectorResult::new(&bits, &corners, self.compact, self.nb_data_blocks, self.nb_layers)); return Ok(AztecDetectorResult::new(
&bits,
&corners,
self.compact,
self.nb_data_blocks,
self.nb_layers,
));
} }
/** /**
* Extracts the number of data layers and data blocks from the layer around the bull's eye. * Extracts the number of data layers and data blocks from the layer around the bull's eye.
* *
* @param bullsEyeCorners the array of bull's eye corners * @param bullsEyeCorners the array of bull's eye corners
* @throws NotFoundException in case of too many errors or invalid parameters * @throws NotFoundException in case of too many errors or invalid parameters
*/ */
fn extract_parameters(&self, bulls_eye_corners: &Vec<ResultPoint>) -> Result<(), NotFoundException> { fn extract_parameters(
if !self.is_valid(bulls_eye_corners[0]) || !self.is_valid(bulls_eye_corners[1]) || !self.is_valid(bulls_eye_corners[2]) || !self.is_valid(bulls_eye_corners[3]) { &self,
return Err( NotFoundException::get_not_found_instance()); bulls_eye_corners: &Vec<ResultPoint>,
) -> Result<(), NotFoundException> {
if !self.is_valid(bulls_eye_corners[0])
|| !self.is_valid(bulls_eye_corners[1])
|| !self.is_valid(bulls_eye_corners[2])
|| !self.is_valid(bulls_eye_corners[3])
{
return Err(NotFoundException::get_not_found_instance());
} }
let length: i32 = 2 * self.nb_center_layers; let length: i32 = 2 * self.nb_center_layers;
// Get the bits around the bull's eye // Get the bits around the bull's eye
let sides: vec![Vec<i32>; 4] = vec![// Right side let sides: vec![Vec<i32>; 4] = vec![
self.sample_line(&bulls_eye_corners[0], &bulls_eye_corners[1], length), // Bottom // Right side
self.sample_line(&bulls_eye_corners[1], &bulls_eye_corners[2], length), // Left side self.sample_line(&bulls_eye_corners[0], &bulls_eye_corners[1], length), // Bottom
self.sample_line(&bulls_eye_corners[2], &bulls_eye_corners[3], length), // Top self.sample_line(&bulls_eye_corners[1], &bulls_eye_corners[2], length), // Left side
self.sample_line(&bulls_eye_corners[3], &bulls_eye_corners[0], length), ] self.sample_line(&bulls_eye_corners[2], &bulls_eye_corners[3], length), // Top
; self.sample_line(&bulls_eye_corners[3], &bulls_eye_corners[0], length),
];
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three // bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks. // orientation marks.
// sides[shift] is the row/column that goes from the corner with three // sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two. // orientation marks to the corner with two.
self.shift = ::get_rotation(&sides, length); self.shift = ::get_rotation(&sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long // Flatten the parameter bits into a single 28- or 40-bit long
let parameter_data: i64 = 0; let parameter_data: i64 = 0;
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < 4 { while i < 4 {
{ {
let side: i32 = sides[(self.shift + i) % 4]; let side: i32 = sides[(self.shift + i) % 4];
if self.compact { if self.compact {
// Each side of the form ..XXXXXXX. where Xs are parameter data // Each side of the form ..XXXXXXX. where Xs are parameter data
parameter_data <<= 7; parameter_data <<= 7;
@@ -111,12 +132,12 @@ impl Detector {
} }
} }
i += 1; i += 1;
} }
} }
// Corrects parameter data using RS. Returns just the data portion // Corrects parameter data using RS. Returns just the data portion
// without the error correction. // without the error correction.
let corrected_data: i32 = ::get_corrected_parameter_data(parameter_data, self.compact); let corrected_data: i32 = ::get_corrected_parameter_data(parameter_data, self.compact);
if self.compact { if self.compact {
// 8 bits: 2 bits layers and 6 bits data blocks // 8 bits: 2 bits layers and 6 bits data blocks
self.nb_layers = (corrected_data >> 6) + 1; self.nb_layers = (corrected_data >> 6) + 1;
@@ -130,7 +151,7 @@ impl Detector {
Ok(()) Ok(())
} }
fn get_rotation( sides: &Vec<i32>, length: i32) -> Result<i32, NotFoundException> { fn get_rotation(sides: &Vec<i32>, length: i32) -> Result<i32, NotFoundException> {
// In a normal pattern, we expect to See // In a normal pattern, we expect to See
// ** .* D A // ** .* D A
// * * // * *
@@ -140,10 +161,10 @@ impl Detector {
// //
// Grab the 3 bits from each of the sides the form the locator pattern and concatenate // Grab the 3 bits from each of the sides the form the locator pattern and concatenate
// into a 12-bit integer. Start with the bit at A // into a 12-bit integer. Start with the bit at A
let corner_bits: i32 = 0; let corner_bits: i32 = 0;
for side in sides { for side in sides {
// XX......X where X's are orientation marks // XX......X where X's are orientation marks
let t: i32 = ((side >> (length - 2)) << 1) + (side & 1); let t: i32 = ((side >> (length - 2)) << 1) + (side & 1);
corner_bits = (corner_bits << 3) + t; corner_bits = (corner_bits << 3) + t;
} }
// Mov the bottom bit to the top, so that the three bits of the locator pattern at A are // Mov the bottom bit to the top, so that the three bits of the locator pattern at A are
@@ -151,8 +172,8 @@ impl Detector {
// 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D // 3 orientation bits at A || 3 orientation bits at B || ... || 3 orientation bits at D
corner_bits = ((corner_bits & 1) << 11) + (corner_bits >> 1); corner_bits = ((corner_bits & 1) << 11) + (corner_bits >> 1);
// can easily tolerate two errors. // can easily tolerate two errors.
{ {
let mut shift: i32 = 0; let mut shift: i32 = 0;
while shift < 4 { while shift < 4 {
{ {
if Integer::bit_count(corner_bits ^ EXPECTED_CORNER_BITS[shift]) <= 2 { if Integer::bit_count(corner_bits ^ EXPECTED_CORNER_BITS[shift]) <= 2 {
@@ -160,22 +181,25 @@ impl Detector {
} }
} }
shift += 1; shift += 1;
} }
} }
return Err(NotFoundException::get_not_found_instance()); return Err(NotFoundException::get_not_found_instance());
} }
/** /**
* Corrects the parameter bits using Reed-Solomon algorithm. * Corrects the parameter bits using Reed-Solomon algorithm.
* *
* @param parameterData parameter bits * @param parameterData parameter bits
* @param compact true if this is a compact Aztec code * @param compact true if this is a compact Aztec code
* @throws NotFoundException if the array contains too many errors * @throws NotFoundException if the array contains too many errors
*/ */
fn get_corrected_parameter_data( parameter_data: i64, compact: bool) -> /* throws NotFoundException */Result<i32, Rc<Exception>> { fn get_corrected_parameter_data(
let num_codewords: i32; parameter_data: i64,
let num_data_codewords: i32; compact: bool,
) -> Result<i32, Rc<Exception>> {
let num_codewords: i32;
let num_data_codewords: i32;
if compact { if compact {
num_codewords = 7; num_codewords = 7;
num_data_codewords = 2; num_data_codewords = 2;
@@ -183,24 +207,24 @@ impl Detector {
num_codewords = 10; num_codewords = 10;
num_data_codewords = 4; num_data_codewords = 4;
} }
let num_e_c_codewords: i32 = num_codewords - num_data_codewords; let num_e_c_codewords: i32 = num_codewords - num_data_codewords;
let parameter_words: [i32; num_codewords] = [0; num_codewords]; let parameter_words: [i32; num_codewords] = [0; num_codewords];
{ {
let mut i: i32 = num_codewords - 1; let mut i: i32 = num_codewords - 1;
while i >= 0 { while i >= 0 {
{ {
parameter_words[i] = parameter_data as i32 & 0xF; parameter_words[i] = parameter_data as i32 & 0xF;
parameter_data >>= 4; parameter_data >>= 4;
} }
i -= 1; i -= 1;
} }
} }
let tryResult1 = 0; let tryResult1 = 0;
/*'try1: loop { /*'try1: loop {
{*/ {*/
let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(GenericGF::AZTEC_PARAM); let rs_decoder: ReedSolomonDecoder = ReedSolomonDecoder::new(GenericGF::AZTEC_PARAM);
rs_decoder.decode(&parameter_words, num_e_c_codewords); rs_decoder.decode(&parameter_words, num_e_c_codewords);
/*} /*}
break 'try1 break 'try1
} }
@@ -212,46 +236,50 @@ impl Detector {
*/ */
// Toss the error correction. Just return the data as an integer // Toss the error correction. Just return the data as an integer
let mut result: i32 = 0; let mut result: i32 = 0;
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < num_data_codewords { while i < num_data_codewords {
{ {
result = (result << 4) + parameter_words[i]; result = (result << 4) + parameter_words[i];
} }
i += 1; i += 1;
} }
} }
return Ok(result); return Ok(result);
} }
/** /**
* Finds the corners of a bull-eye centered on the passed point. * Finds the corners of a bull-eye centered on the passed point.
* This returns the centers of the diagonal points just outside the bull's eye * This returns the centers of the diagonal points just outside the bull's eye
* Returns [topRight, bottomRight, bottomLeft, topLeft] * Returns [topRight, bottomRight, bottomLeft, topLeft]
* *
* @param pCenter Center point * @param pCenter Center point
* @return The corners of the bull-eye * @return The corners of the bull-eye
* @throws NotFoundException If no valid bull-eye can be found * @throws NotFoundException If no valid bull-eye can be found
*/ */
fn get_bulls_eye_corners(&self, p_center: &Point) -> /* throws NotFoundException */Result<Vec<ResultPoint>, Rc<Exception>> { fn get_bulls_eye_corners(&self, p_center: &Point) -> Result<Vec<ResultPoint>, Rc<Exception>> {
let mut pina: Point = p_center; let mut pina: Point = p_center;
let mut pinb: Point = p_center; let mut pinb: Point = p_center;
let mut pinc: Point = p_center; let mut pinc: Point = p_center;
let mut pind: Point = p_center; let mut pind: Point = p_center;
let mut color: bool = true; let mut color: bool = true;
{ {
self.nb_center_layers = 1; self.nb_center_layers = 1;
while self.nb_center_layers < 9 { while self.nb_center_layers < 9 {
{ {
let pouta: Point = self.get_first_different(&pina, color, 1, -1); let pouta: Point = self.get_first_different(&pina, color, 1, -1);
let poutb: Point = self.get_first_different(&pinb, color, 1, 1); let poutb: Point = self.get_first_different(&pinb, color, 1, 1);
let poutc: Point = self.get_first_different(&pinc, color, -1, 1); let poutc: Point = self.get_first_different(&pinc, color, -1, 1);
let poutd: Point = self.get_first_different(&pind, color, -1, -1); let poutd: Point = self.get_first_different(&pind, color, -1, -1);
if self.nb_center_layers > 2 { if self.nb_center_layers > 2 {
let q: f32 = ::distance(poutd, pouta) * self.nb_center_layers / (::distance(pind, pina) * (self.nb_center_layers + 2)); let q: f32 = ::distance(poutd, pouta) * self.nb_center_layers
if q < 0.75 || q > 1.25 || !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd) { / (::distance(pind, pina) * (self.nb_center_layers + 2));
if q < 0.75
|| q > 1.25
|| !self.is_white_or_black_rectangle(&pouta, &poutb, &poutc, &poutd)
{
break; break;
} }
} }
@@ -262,62 +290,77 @@ impl Detector {
color = !color; color = !color;
} }
self.nb_center_layers += 1; self.nb_center_layers += 1;
} }
} }
if self.nb_center_layers != 5 && self.nb_center_layers != 7 { if self.nb_center_layers != 5 && self.nb_center_layers != 7 {
return Err( NotFoundException::get_not_found_instance()); return Err(NotFoundException::get_not_found_instance());
} }
self.compact = self.nb_center_layers == 5; self.compact = self.nb_center_layers == 5;
// Expand the square by .5 pixel in each direction so that we're on the border // Expand the square by .5 pixel in each direction so that we're on the border
// between the white square and the black square // between the white square and the black square
let pinax: ResultPoint = ResultPoint::new(pina.get_x() + 0.5f32, pina.get_y() - 0.5f32); let pinax: ResultPoint = ResultPoint::new(pina.get_x() + 0.5f32, pina.get_y() - 0.5f32);
let pinbx: ResultPoint = ResultPoint::new(pinb.get_x() + 0.5f32, pinb.get_y() + 0.5f32); let pinbx: ResultPoint = ResultPoint::new(pinb.get_x() + 0.5f32, pinb.get_y() + 0.5f32);
let pincx: ResultPoint = ResultPoint::new(pinc.get_x() - 0.5f32, pinc.get_y() + 0.5f32); let pincx: ResultPoint = ResultPoint::new(pinc.get_x() - 0.5f32, pinc.get_y() + 0.5f32);
let pindx: ResultPoint = ResultPoint::new(pind.get_x() - 0.5f32, pind.get_y() - 0.5f32); let pindx: ResultPoint = ResultPoint::new(pind.get_x() - 0.5f32, pind.get_y() - 0.5f32);
// just outside the bull's eye. // just outside the bull's eye.
return Ok(::expand_square( vec![pinax, pinbx, pincx, pindx, ] return Ok(::expand_square(
, 2 * self.nb_center_layers - 3, 2 * self.nb_center_layers)); vec![pinax, pinbx, pincx, pindx],
2 * self.nb_center_layers - 3,
2 * self.nb_center_layers,
));
} }
/** /**
* Finds a candidate center point of an Aztec code from an image * Finds a candidate center point of an Aztec code from an image
* *
* @return the center point * @return the center point
*/ */
fn get_matrix_center(&self) -> Point { fn get_matrix_center(&self) -> Point {
let point_a: ResultPoint; let point_a: ResultPoint;
let point_b: ResultPoint; let point_b: ResultPoint;
let point_c: ResultPoint; let point_c: ResultPoint;
let point_d: ResultPoint; let point_d: ResultPoint;
//Get a white rectangle that can be the border of the matrix in center bull's eye or //Get a white rectangle that can be the border of the matrix in center bull's eye or
let tryResult1 = 0; let tryResult1 = 0;
let corner_points_detector = WhiteRectangleDetector::new(&self.image, None, None, None); let corner_points_detector = WhiteRectangleDetector::new(&self.image, None, None, None);
if corner_points_detector.is_ok() { if corner_points_detector.is_ok() {
let corner_points: Vec<ResultPoint> = corner_points_detector.detect();
let corner_points: Vec<ResultPoint> = corner_points_detector.detect();
point_a = corner_points[0]; point_a = corner_points[0];
point_b = corner_points[1]; point_b = corner_points[1];
point_c = corner_points[2]; point_c = corner_points[2];
point_d = corner_points[3]; point_d = corner_points[3];
}else { } else {
let cx: i32 = self.image.get_width() / 2; let cx: i32 = self.image.get_width() / 2;
let cy: i32 = self.image.get_height() / 2; let cy: i32 = self.image.get_height() / 2;
point_a = self.get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1).to_result_point(); point_a = self
point_b = self.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1).to_result_point(); .get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1)
point_c = self.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1).to_result_point(); .to_result_point();
point_d = self.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1).to_result_point(); point_b = self
.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1)
.to_result_point();
point_c = self
.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1)
.to_result_point();
point_d = self
.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1)
.to_result_point();
} }
//Compute the center of the rectangle //Compute the center of the rectangle
let mut cx: i32 = MathUtils::round((point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32); let mut cx: i32 = MathUtils::round(
let mut cy: i32 = MathUtils::round((point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32); (point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32,
);
let mut cy: i32 = MathUtils::round(
(point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32,
);
// in order to compute a more accurate center. // in order to compute a more accurate center.
let tryResult1 = 0; let tryResult1 = 0;
let corner_points_wrd = WhiteRectangleDetector::new(&self.image, Some(15), Some(cx), Some(cy)); let corner_points_wrd =
WhiteRectangleDetector::new(&self.image, Some(15), Some(cx), Some(cy));
if corner_points_wrd.is_ok() { if corner_points_wrd.is_ok() {
let corner_points: Vec<ResultPoint> = corner_points_wrd.detect(); let corner_points: Vec<ResultPoint> = corner_points_wrd.detect();
point_a = corner_points[0]; point_a = corner_points[0];
@@ -325,95 +368,148 @@ impl Detector {
point_c = corner_points[2]; point_c = corner_points[2];
point_d = corner_points[3]; point_d = corner_points[3];
} else { } else {
point_a = self.get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1).to_result_point(); point_a = self
point_b = self.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1).to_result_point(); .get_first_different(&Point::new(cx + 7, cy - 7), false, 1, -1)
point_c = self.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1).to_result_point(); .to_result_point();
point_d = self.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1).to_result_point(); point_b = self
.get_first_different(&Point::new(cx + 7, cy + 7), false, 1, 1)
.to_result_point();
point_c = self
.get_first_different(&Point::new(cx - 7, cy + 7), false, -1, 1)
.to_result_point();
point_d = self
.get_first_different(&Point::new(cx - 7, cy - 7), false, -1, -1)
.to_result_point();
} }
// Recompute the center of the rectangle // Recompute the center of the rectangle
cx = MathUtils::round((point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32); cx = MathUtils::round(
cy = MathUtils::round((point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32); (point_a.get_x() + point_d.get_x() + point_b.get_x() + point_c.get_x()) / 4.0f32,
);
cy = MathUtils::round(
(point_a.get_y() + point_d.get_y() + point_b.get_y() + point_c.get_y()) / 4.0f32,
);
return Point::new(cx, cy); return Point::new(cx, cy);
} }
/** /**
* Gets the Aztec code corners from the bull's eye corners and the parameters. * Gets the Aztec code corners from the bull's eye corners and the parameters.
* *
* @param bullsEyeCorners the array of bull's eye corners * @param bullsEyeCorners the array of bull's eye corners
* @return the array of aztec code corners * @return the array of aztec code corners
*/ */
fn get_matrix_corner_points(&self, bulls_eye_corners: &Vec<ResultPoint>) -> Vec<ResultPoint> { fn get_matrix_corner_points(&self, bulls_eye_corners: &Vec<ResultPoint>) -> Vec<ResultPoint> {
return ::expand_square(bulls_eye_corners, 2 * self.nb_center_layers, &self.get_dimension()); return ::expand_square(
bulls_eye_corners,
2 * self.nb_center_layers,
&self.get_dimension(),
);
} }
/** /**
* Creates a BitMatrix by sampling the provided image. * Creates a BitMatrix by sampling the provided image.
* topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the * topLeft, topRight, bottomRight, and bottomLeft are the centers of the squares on the
* diagonal just outside the bull's eye. * diagonal just outside the bull's eye.
*/ */
fn sample_grid(&self, image: &BitMatrix, top_left: &ResultPoint, top_right: &ResultPoint, bottom_right: &ResultPoint, bottom_left: &ResultPoint) -> /* throws NotFoundException */Result<BitMatrix, Rc<Exception>> { fn sample_grid(
let sampler: GridSampler = GridSampler::get_instance(); &self,
let dimension: i32 = self.get_dimension(); image: &BitMatrix,
let low: f32 = dimension / 2.0f32 - self.nb_center_layers; top_left: &ResultPoint,
let high: f32 = dimension / 2.0f32 + self.nb_center_layers; top_right: &ResultPoint,
return Ok(sampler.sample_grid(image, dimension, dimension, // topleft bottom_right: &ResultPoint,
low, // topleft bottom_left: &ResultPoint,
low, // topright ) -> Result<BitMatrix, Rc<Exception>> {
high, // topright let sampler: GridSampler = GridSampler::get_instance();
low, // bottomright let dimension: i32 = self.get_dimension();
high, // bottomright let low: f32 = dimension / 2.0f32 - self.nb_center_layers;
high, // bottomleft let high: f32 = dimension / 2.0f32 + self.nb_center_layers;
low, // bottomleft return Ok(sampler.sample_grid(
high, &top_left.get_x(), &top_left.get_y(), &top_right.get_x(), &top_right.get_y(), &bottom_right.get_x(), &bottom_right.get_y(), &bottom_left.get_x(), &bottom_left.get_y())); image,
dimension,
dimension, // topleft
low, // topleft
low, // topright
high, // topright
low, // bottomright
high, // bottomright
high, // bottomleft
low, // bottomleft
high,
&top_left.get_x(),
&top_left.get_y(),
&top_right.get_x(),
&top_right.get_y(),
&bottom_right.get_x(),
&bottom_right.get_y(),
&bottom_left.get_x(),
&bottom_left.get_y(),
));
} }
/** /**
* Samples a line. * Samples a line.
* *
* @param p1 start point (inclusive) * @param p1 start point (inclusive)
* @param p2 end point (exclusive) * @param p2 end point (exclusive)
* @param size number of bits * @param size number of bits
* @return the array of bits as an int (first bit is high-order bit of result) * @return the array of bits as an int (first bit is high-order bit of result)
*/ */
fn sample_line(&self, p1: &ResultPoint, p2: &ResultPoint, size: i32) -> i32 { fn sample_line(&self, p1: &ResultPoint, p2: &ResultPoint, size: i32) -> i32 {
let mut result: i32 = 0; let mut result: i32 = 0;
let d: f32 = ::distance(p1, p2); let d: f32 = ::distance(p1, p2);
let module_size: f32 = d / size; let module_size: f32 = d / size;
let px: f32 = p1.get_x(); let px: f32 = p1.get_x();
let py: f32 = p1.get_y(); let py: f32 = p1.get_y();
let dx: f32 = module_size * (p2.get_x() - p1.get_x()) / d; let dx: f32 = module_size * (p2.get_x() - p1.get_x()) / d;
let dy: f32 = module_size * (p2.get_y() - p1.get_y()) / d; let dy: f32 = module_size * (p2.get_y() - p1.get_y()) / d;
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < size { while i < size {
{ {
if self.image.get(&MathUtils::round(px + i * dx), &MathUtils::round(py + i * dy)) { if self.image.get(
&MathUtils::round(px + i * dx),
&MathUtils::round(py + i * dy),
) {
result |= 1 << (size - i - 1); result |= 1 << (size - i - 1);
} }
} }
i += 1; i += 1;
} }
} }
return result; return result;
} }
/** /**
* @return true if the border of the rectangle passed in parameter is compound of white points only * @return true if the border of the rectangle passed in parameter is compound of white points only
* or black points only * or black points only
*/ */
fn is_white_or_black_rectangle(&self, p1: &Point, p2: &Point, p3: &Point, p4: &Point) -> bool { fn is_white_or_black_rectangle(&self, p1: &Point, p2: &Point, p3: &Point, p4: &Point) -> bool {
let corr: i32 = 3; let corr: i32 = 3;
p1 = &Point::new(&Math::max(0, p1.get_x() - corr), &Math::min(self.image.get_height() - 1, p1.get_y() + corr)); p1 = &Point::new(
p2 = &Point::new(&Math::max(0, p2.get_x() - corr), &Math::max(0, p2.get_y() - corr)); &Math::max(0, p1.get_x() - corr),
p3 = &Point::new(&Math::min(self.image.get_width() - 1, p3.get_x() + corr), &Math::max(0, &Math::min(self.image.get_height() - 1, p3.get_y() - corr))); &Math::min(self.image.get_height() - 1, p1.get_y() + corr),
p4 = &Point::new(&Math::min(self.image.get_width() - 1, p4.get_x() + corr), &Math::min(self.image.get_height() - 1, p4.get_y() + corr)); );
let c_init: i32 = self.get_color(p4, p1); p2 = &Point::new(
&Math::max(0, p2.get_x() - corr),
&Math::max(0, p2.get_y() - corr),
);
p3 = &Point::new(
&Math::min(self.image.get_width() - 1, p3.get_x() + corr),
&Math::max(
0,
&Math::min(self.image.get_height() - 1, p3.get_y() - corr),
),
);
p4 = &Point::new(
&Math::min(self.image.get_width() - 1, p4.get_x() + corr),
&Math::min(self.image.get_height() - 1, p4.get_y() + corr),
);
let c_init: i32 = self.get_color(p4, p1);
if c_init == 0 { if c_init == 0 {
return false; return false;
} }
let mut c: i32 = self.get_color(p1, p2); let mut c: i32 = self.get_color(p1, p2);
if c != c_init { if c != c_init {
return false; return false;
} }
@@ -426,24 +522,24 @@ impl Detector {
} }
/** /**
* Gets the color of a segment * Gets the color of a segment
* *
* @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else * @return 1 if segment more than 90% black, -1 if segment is more than 90% white, 0 else
*/ */
fn get_color(&self, p1: &Point, p2: &Point) -> i32 { fn get_color(&self, p1: &Point, p2: &Point) -> i32 {
let d: f32 = ::distance(p1, p2); let d: f32 = ::distance(p1, p2);
if d == 0.0f32 { if d == 0.0f32 {
return 0; return 0;
} }
let dx: f32 = (p2.get_x() - p1.get_x()) / d; let dx: f32 = (p2.get_x() - p1.get_x()) / d;
let dy: f32 = (p2.get_y() - p1.get_y()) / d; let dy: f32 = (p2.get_y() - p1.get_y()) / d;
let mut error: i32 = 0; let mut error: i32 = 0;
let mut px: f32 = p1.get_x(); let mut px: f32 = p1.get_x();
let mut py: f32 = p1.get_y(); let mut py: f32 = p1.get_y();
let color_model: bool = self.image.get(&p1.get_x(), &p1.get_y()); let color_model: bool = self.image.get(&p1.get_x(), &p1.get_y());
let i_max: i32 = Math::floor(d) as i32; let i_max: i32 = Math::floor(d) as i32;
{ {
let mut i: i32 = 0; let mut i: i32 = 0;
while i < i_max { while i < i_max {
{ {
if self.image.get(&MathUtils::round(px), &MathUtils::round(py)) != color_model { if self.image.get(&MathUtils::round(px), &MathUtils::round(py)) != color_model {
@@ -453,22 +549,26 @@ impl Detector {
py += dy; py += dy;
} }
i += 1; i += 1;
} }
} }
let err_ratio: f32 = error / d; let err_ratio: f32 = error / d;
if err_ratio > 0.1f32 && err_ratio < 0.9f32 { if err_ratio > 0.1f32 && err_ratio < 0.9f32 {
return 0; return 0;
} }
return if (err_ratio <= 0.1f32) == color_model { 1 } else { -1 }; return if (err_ratio <= 0.1f32) == color_model {
1
} else {
-1
};
} }
/** /**
* Gets the coordinate of the first point with a different color in the given direction * Gets the coordinate of the first point with a different color in the given direction
*/ */
fn get_first_different(&self, init: &Point, color: bool, dx: i32, dy: i32) -> Point { fn get_first_different(&self, init: &Point, color: bool, dx: i32, dy: i32) -> Point {
let mut x: i32 = init.get_x() + dx; let mut x: i32 = init.get_x() + dx;
let mut y: i32 = init.get_y() + dy; let mut y: i32 = init.get_y() + dy;
while self.is_valid(x, y) && self.image.get(x, y) == color { while self.is_valid(x, y) && self.image.get(x, y) == color {
x += dx; x += dx;
y += dy; y += dy;
@@ -487,86 +587,84 @@ impl Detector {
} }
/** /**
* Expand the square represented by the corner points by pushing out equally in all directions * Expand the square represented by the corner points by pushing out equally in all directions
* *
* @param cornerPoints the corners of the square, which has the bull's eye at its center * @param cornerPoints the corners of the square, which has the bull's eye at its center
* @param oldSide the original length of the side of the square in the target bit matrix * @param oldSide the original length of the side of the square in the target bit matrix
* @param newSide the new length of the size of the square in the target bit matrix * @param newSide the new length of the size of the square in the target bit matrix
* @return the corners of the expanded square * @return the corners of the expanded square
*/ */
fn expand_square( corner_points: &Vec<ResultPoint>, old_side: i32, new_side: i32) -> Vec<ResultPoint> { fn expand_square(
let ratio: f32 = new_side / (2.0f32 * old_side); corner_points: &Vec<ResultPoint>,
let mut dx: f32 = corner_points[0].get_x() - corner_points[2].get_x(); old_side: i32,
let mut dy: f32 = corner_points[0].get_y() - corner_points[2].get_y(); new_side: i32,
let mut centerx: f32 = (corner_points[0].get_x() + corner_points[2].get_x()) / 2.0f32; ) -> Vec<ResultPoint> {
let mut centery: f32 = (corner_points[0].get_y() + corner_points[2].get_y()) / 2.0f32; let ratio: f32 = new_side / (2.0f32 * old_side);
let result0: ResultPoint = ResultPoint::new(centerx + ratio * dx, centery + ratio * dy); let mut dx: f32 = corner_points[0].get_x() - corner_points[2].get_x();
let result2: ResultPoint = ResultPoint::new(centerx - ratio * dx, centery - ratio * dy); let mut dy: f32 = corner_points[0].get_y() - corner_points[2].get_y();
let mut centerx: f32 = (corner_points[0].get_x() + corner_points[2].get_x()) / 2.0f32;
let mut centery: f32 = (corner_points[0].get_y() + corner_points[2].get_y()) / 2.0f32;
let result0: ResultPoint = ResultPoint::new(centerx + ratio * dx, centery + ratio * dy);
let result2: ResultPoint = ResultPoint::new(centerx - ratio * dx, centery - ratio * dy);
dx = corner_points[1].get_x() - corner_points[3].get_x(); dx = corner_points[1].get_x() - corner_points[3].get_x();
dy = corner_points[1].get_y() - corner_points[3].get_y(); dy = corner_points[1].get_y() - corner_points[3].get_y();
centerx = (corner_points[1].get_x() + corner_points[3].get_x()) / 2.0f32; centerx = (corner_points[1].get_x() + corner_points[3].get_x()) / 2.0f32;
centery = (corner_points[1].get_y() + corner_points[3].get_y()) / 2.0f32; centery = (corner_points[1].get_y() + corner_points[3].get_y()) / 2.0f32;
let result1: ResultPoint = ResultPoint::new(centerx + ratio * dx, centery + ratio * dy); let result1: ResultPoint = ResultPoint::new(centerx + ratio * dx, centery + ratio * dy);
let result3: ResultPoint = ResultPoint::new(centerx - ratio * dx, centery - ratio * dy); let result3: ResultPoint = ResultPoint::new(centerx - ratio * dx, centery - ratio * dy);
return vec![result0, result1, result2, result3, ] return vec![result0, result1, result2, result3];
;
} }
fn is_valid_coords(&self, x: i32, y: i32) -> bool { fn is_valid_coords(&self, x: i32, y: i32) -> bool {
return x >= 0 && x < self.image.get_width() && y >= 0 && y < self.image.get_height(); return x >= 0 && x < self.image.get_width() && y >= 0 && y < self.image.get_height();
} }
fn is_valid_rp(&self, point: &ResultPoint) -> bool { fn is_valid_rp(&self, point: &ResultPoint) -> bool {
let x: i32 = MathUtils::round(&point.get_x()); let x: i32 = MathUtils::round(&point.get_x());
let y: i32 = MathUtils::round(&point.get_y()); let y: i32 = MathUtils::round(&point.get_y());
return self.is_valid(x, y); return self.is_valid(x, y);
} }
fn distance( a: &Point, b: &Point) -> f32 { fn distance(a: &Point, b: &Point) -> f32 {
return MathUtils::distance(&a.get_x(), &a.get_y(), &b.get_x(), &b.get_y()); return MathUtils::distance(&a.get_x(), &a.get_y(), &b.get_x(), &b.get_y());
} }
fn distance( a: &ResultPoint, b: &ResultPoint) -> f32 { fn distance(a: &ResultPoint, b: &ResultPoint) -> f32 {
return MathUtils::distance(&a.get_x(), &a.get_y(), &b.get_x(), &b.get_y()); return MathUtils::distance(&a.get_x(), &a.get_y(), &b.get_x(), &b.get_y());
} }
fn get_dimension(&self) -> i32 { fn get_dimension(&self) -> i32 {
if self.compact { if self.compact {
return 4 * self.nb_layers + 11; return 4 * self.nb_layers + 11;
} }
return 4 * self.nb_layers + 2 * ((2 * self.nb_layers + 6) / 15) + 15; return 4 * self.nb_layers + 2 * ((2 * self.nb_layers + 6) / 15) + 15;
} }
} }
struct Point { struct Point {
x: i32,
x: i32, y: i32,
y: i32
} }
impl Point { impl Point {
fn to_result_point(&self) -> ResultPoint {
return ResultPoint::new(self.x, self.y);
}
fn to_result_point(&self) -> ResultPoint { fn new(x: i32, y: i32) -> Self {
return ResultPoint::new(self.x, self.y); Self { x: x, y: y }
} }
fn new( x: i32, y: i32) -> Self { fn get_x(&self) -> i32 {
Self { x: x, y: y } return self.x;
} }
fn get_x(&self) -> i32 { fn get_y(&self) -> i32 {
return self.x; return self.y;
} }
fn get_y(&self) -> i32 { pub fn to_string(&self) -> String {
return self.y; return format!("<{} {}>", self.x, self.y);
} }
pub fn to_string(&self) -> String {
return format!("<{} {}>", self.x, self.y);
}
} }

File diff suppressed because it is too large Load Diff