Initial generics

This commit is contained in:
Steve Cook
2023-03-01 22:08:12 -05:00
parent 26325928e7
commit a9bc58108c
65 changed files with 1013 additions and 883 deletions

View File

@@ -43,12 +43,12 @@ fn test_get_set() {
#[test]
fn test_get_next_set1() {
let array = BitArray::with_size(32);
for i in 0..array.getSize() {
for i in 0..array.get_size() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!(32, array.getNextSet(i), "{i}");
}
let array = BitArray::with_size(33);
for i in 0..array.getSize() {
for i in 0..array.get_size() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!(33, array.getNextSet(i), "{i}");
}
@@ -58,13 +58,13 @@ fn test_get_next_set1() {
fn test_get_next_set2() {
let mut array = BitArray::with_size(33);
array.set(31);
for i in 0..array.getSize() {
for i in 0..array.get_size() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!(if i <= 31 { 31 } else { 33 }, array.getNextSet(i), "{i}");
}
array = BitArray::with_size(33);
array.set(32);
for i in 0..array.getSize() {
for i in 0..array.get_size() {
// for (int i = 0; i < array.getSize(); i++) {
assert_eq!(32, array.getNextSet(i), "{i}");
}
@@ -75,7 +75,7 @@ fn test_get_next_set3() {
let mut array = BitArray::with_size(63);
array.set(31);
array.set(32);
for i in 0..array.getSize() {
for i in 0..array.get_size() {
// for (int i = 0; i < array.getSize(); i++) {
let expected;
if i <= 31 {
@@ -94,7 +94,7 @@ fn test_get_next_set4() {
let mut array = BitArray::with_size(63);
array.set(33);
array.set(40);
for i in 0..array.getSize() {
for i in 0..array.get_size() {
// for (int i = 0; i < array.getSize(); i++) {
let expected;
if i <= 33 {
@@ -117,14 +117,14 @@ fn test_get_next_set5() {
let numSet = r.gen_range(0..20);
for _j in 0..numSet {
// for (int j = 0; j < numSet; j++) {
array.set(r.gen_range(0..array.getSize()));
array.set(r.gen_range(0..array.get_size()));
}
let numQueries = r.gen_range(0..20);
for _j in 0..numQueries {
// for (int j = 0; j < numQueries; j++) {
let query = r.gen_range(0..array.getSize());
let query = r.gen_range(0..array.get_size());
let mut expected = query;
while expected < array.getSize() && !array.get(expected) {
while expected < array.get_size() && !array.get(expected) {
expected += 1;
}
let actual = array.getNextSet(query);

View File

@@ -57,7 +57,7 @@ impl BitArray {
Self { bits, size }
}
pub fn getSize(&self) -> usize {
pub fn get_size(&self) -> usize {
self.size
}

View File

@@ -156,12 +156,12 @@ fn test_get_row() {
// Should allocate
let array = matrix.getRow(2);
assert_eq!(102, array.getSize());
assert_eq!(102, array.get_size());
// Should reallocate
// let mut array2 = BitArray::with_size(60);
let array2 = matrix.getRow(2);
assert_eq!(102, array2.getSize());
assert_eq!(102, array2.get_size());
// Should use provided object, with original BitArray size
// let mut array3 = BitArray::with_size(200);

View File

@@ -20,7 +20,7 @@
// import com.google.zxing.LuminanceSource;
// import com.google.zxing.NotFoundException;
use std::{borrow::Cow, rc::Rc};
use std::borrow::Cow;
use once_cell::unsync::OnceCell;
@@ -29,6 +29,10 @@ use crate::{Binarizer, Exceptions, LuminanceSource};
use super::{BitArray, BitMatrix};
const LUMINANCE_BITS: usize = 5;
const LUMINANCE_SHIFT: usize = 8 - LUMINANCE_BITS;
const LUMINANCE_BUCKETS: usize = 1 << LUMINANCE_BITS;
/**
* This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
* for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
@@ -40,34 +44,35 @@ use super::{BitArray, BitMatrix};
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
pub struct GlobalHistogramBinarizer {
pub struct GlobalHistogramBinarizer<LS: LuminanceSource> {
//_luminances: Vec<u8>,
width: usize,
height: usize,
source: Box<dyn LuminanceSource>,
source: LS,
black_matrix: OnceCell<BitMatrix>,
black_row_cache: Vec<OnceCell<BitArray>>,
}
impl Binarizer for GlobalHistogramBinarizer {
fn getLuminanceSource(&self) -> &Box<dyn LuminanceSource> {
impl<LS: LuminanceSource> Binarizer for GlobalHistogramBinarizer<LS> {
type Source = LS;
fn get_luminance_source(&self) -> &Self::Source {
&self.source
}
// Applies simple sharpening to the row data to improve performance of the 1D Readers.
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
fn get_black_row(&self, y: usize) -> Result<Cow<BitArray>> {
let row = self.black_row_cache[y].get_or_try_init(|| {
let source = self.getLuminanceSource();
let width = source.getWidth();
let source = self.get_luminance_source();
let width = source.get_width();
let mut row = BitArray::with_size(width);
// self.initArrays(width);
let localLuminances = source.getRow(y);
let mut localBuckets = [0; GlobalHistogramBinarizer::LUMINANCE_BUCKETS]; //self.buckets.clone();
let localLuminances = source.get_row(y);
let mut localBuckets = [0; LUMINANCE_BUCKETS]; //self.buckets.clone();
for x in 0..width {
// for (int x = 0; x < width; x++) {
localBuckets[((localLuminances[x]) >> GlobalHistogramBinarizer::LUMINANCE_SHIFT)
as usize] += 1;
localBuckets[((localLuminances[x]) >> LUMINANCE_SHIFT) as usize] += 1;
}
let blackPoint = Self::estimateBlackPoint(&localBuckets)?;
@@ -102,63 +107,60 @@ impl Binarizer for GlobalHistogramBinarizer {
}
// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
fn getBlackMatrix(&self) -> Result<&BitMatrix> {
fn get_black_matrix(&self) -> Result<&BitMatrix> {
let matrix = self
.black_matrix
.get_or_try_init(|| Self::build_black_matrix(&self.source))?;
Ok(matrix)
}
fn createBinarizer(&self, source: Box<dyn crate::LuminanceSource>) -> Rc<dyn Binarizer> {
Rc::new(GlobalHistogramBinarizer::new(source))
fn create_binarizer(&self, source: LS) -> Self {
Self::new(source)
}
fn getWidth(&self) -> usize {
fn get_width(&self) -> usize {
self.width
}
fn getHeight(&self) -> usize {
fn get_height(&self) -> usize {
self.height
}
}
impl GlobalHistogramBinarizer {
const LUMINANCE_BITS: usize = 5;
const LUMINANCE_SHIFT: usize = 8 - GlobalHistogramBinarizer::LUMINANCE_BITS;
const LUMINANCE_BUCKETS: usize = 1 << GlobalHistogramBinarizer::LUMINANCE_BITS;
impl<LS: LuminanceSource> GlobalHistogramBinarizer<LS> {
// const EMPTY: [u8; 0] = [0; 0];
pub fn new(source: Box<dyn LuminanceSource>) -> Self {
pub fn new(source: LS) -> Self {
Self {
//_luminances: vec![0; source.getWidth()],
width: source.getWidth(),
height: source.getHeight(),
width: source.get_width(),
height: source.get_height(),
black_matrix: OnceCell::new(),
black_row_cache: vec![OnceCell::default(); source.getHeight()],
black_row_cache: vec![OnceCell::default(); source.get_height()],
source,
}
}
fn build_black_matrix(source: &Box<dyn LuminanceSource>) -> Result<BitMatrix> {
fn build_black_matrix(source: &LS) -> Result<BitMatrix> {
// let source = source.getLuminanceSource();
let width = source.getWidth();
let height = source.getHeight();
let width = source.get_width();
let height = source.get_height();
let mut matrix = BitMatrix::new(width as u32, height as u32)?;
// Quickly calculates the histogram by sampling four rows from the image. This proved to be
// more robust on the blackbox tests than sampling a diagonal as we used to do.
// self.initArrays(width);
let mut localBuckets = [0; GlobalHistogramBinarizer::LUMINANCE_BUCKETS]; //self.buckets.clone();
let mut localBuckets = [0; LUMINANCE_BUCKETS]; //self.buckets.clone();
for y in 1..5 {
// for (int y = 1; y < 5; y++) {
let row = height * y / 5;
let localLuminances = source.getRow(row);
let localLuminances = source.get_row(row);
let right = (width * 4) / 5;
let mut x = width / 5;
while x < right {
// for (int x = width / 5; x < right; x++) {
let pixel = localLuminances[x];
localBuckets[(pixel >> GlobalHistogramBinarizer::LUMINANCE_SHIFT) as usize] += 1;
localBuckets[(pixel >> LUMINANCE_SHIFT) as usize] += 1;
x += 1;
}
}
@@ -167,7 +169,7 @@ impl GlobalHistogramBinarizer {
// We delay reading the entire image luminance until the black point estimation succeeds.
// Although we end up reading four rows twice, it is consistent with our motto of
// "fail quickly" which is necessary for continuous scanning.
let localLuminances = source.getMatrix();
let localLuminances = source.get_matrix();
for y in 0..height {
// for (int y = 0; y < height; y++) {
let offset = y * width;
@@ -255,6 +257,6 @@ impl GlobalHistogramBinarizer {
x -= 1;
}
Ok((bestValley as u32) << GlobalHistogramBinarizer::LUMINANCE_SHIFT)
Ok((bestValley as u32) << LUMINANCE_SHIFT)
}
}

View File

@@ -20,7 +20,7 @@
// import com.google.zxing.LuminanceSource;
// import com.google.zxing.NotFoundException;
use std::{borrow::Cow, rc::Rc};
use std::borrow::Cow;
use once_cell::unsync::OnceCell;
@@ -46,20 +46,22 @@ use super::{BitArray, BitMatrix, GlobalHistogramBinarizer};
*
* @author dswitkin@google.com (Daniel Switkin)
*/
pub struct HybridBinarizer {
pub struct HybridBinarizer<LS: LuminanceSource> {
//width: usize,
//height: usize,
//source: Box<dyn LuminanceSource>,
ghb: GlobalHistogramBinarizer,
ghb: GlobalHistogramBinarizer<LS>,
black_matrix: OnceCell<BitMatrix>,
}
impl Binarizer for HybridBinarizer {
fn getLuminanceSource(&self) -> &Box<dyn LuminanceSource> {
self.ghb.getLuminanceSource()
impl<LS: LuminanceSource> Binarizer for HybridBinarizer<LS> {
type Source = LS;
fn get_luminance_source(&self) -> &LS {
self.ghb.get_luminance_source()
}
fn getBlackRow(&self, y: usize) -> Result<Cow<BitArray>> {
self.ghb.getBlackRow(y)
fn get_black_row(&self, y: usize) -> Result<Cow<BitArray>> {
self.ghb.get_black_row(y)
}
/**
@@ -67,35 +69,36 @@ impl Binarizer for HybridBinarizer {
* constructor instead, but there are some advantages to doing it lazily, such as making
* profiling easier, and not doing heavy lifting when callers don't expect it.
*/
fn getBlackMatrix(&self) -> Result<&BitMatrix> {
fn get_black_matrix(&self) -> Result<&BitMatrix> {
let matrix = self
.black_matrix
.get_or_try_init(|| Self::calculateBlackMatrix(&self.ghb))?;
Ok(matrix)
}
fn createBinarizer(&self, source: Box<dyn LuminanceSource>) -> Rc<dyn Binarizer> {
Rc::new(HybridBinarizer::new(source))
fn create_binarizer(&self, source: LS) -> Self {
Self::new(source)
}
fn getWidth(&self) -> usize {
self.ghb.getWidth()
fn get_width(&self) -> usize {
self.ghb.get_width()
}
fn getHeight(&self) -> usize {
self.ghb.getHeight()
fn get_height(&self) -> usize {
self.ghb.get_height()
}
}
impl HybridBinarizer {
// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
// So this is the smallest dimension in each axis we can accept.
const BLOCK_SIZE_POWER: usize = 3;
const BLOCK_SIZE: usize = 1 << HybridBinarizer::BLOCK_SIZE_POWER; // ...0100...00
const BLOCK_SIZE_MASK: usize = HybridBinarizer::BLOCK_SIZE - 1; // ...0011...11
const MINIMUM_DIMENSION: usize = HybridBinarizer::BLOCK_SIZE * 5;
const MIN_DYNAMIC_RANGE: usize = 24;
pub fn new(source: Box<dyn LuminanceSource>) -> Self {
// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
// So this is the smallest dimension in each axis we can accept.
const BLOCK_SIZE_POWER: usize = 3;
const BLOCK_SIZE: usize = 1 << BLOCK_SIZE_POWER; // ...0100...00
const BLOCK_SIZE_MASK: usize = BLOCK_SIZE - 1; // ...0011...11
const MINIMUM_DIMENSION: usize = BLOCK_SIZE * 5;
const MIN_DYNAMIC_RANGE: usize = 24;
impl<LS: LuminanceSource> HybridBinarizer<LS> {
pub fn new(source: LS) -> Self {
let ghb = GlobalHistogramBinarizer::new(source);
Self {
black_matrix: OnceCell::new(),
@@ -103,21 +106,21 @@ impl HybridBinarizer {
}
}
fn calculateBlackMatrix(ghb: &GlobalHistogramBinarizer) -> Result<BitMatrix> {
fn calculateBlackMatrix<LS2: LuminanceSource>(
ghb: &GlobalHistogramBinarizer<LS2>,
) -> Result<BitMatrix> {
// let matrix;
let source = ghb.getLuminanceSource();
let width = source.getWidth();
let height = source.getHeight();
let matrix = if width >= HybridBinarizer::MINIMUM_DIMENSION
&& height >= HybridBinarizer::MINIMUM_DIMENSION
{
let luminances = source.getMatrix();
let mut sub_width = width >> HybridBinarizer::BLOCK_SIZE_POWER;
if (width & HybridBinarizer::BLOCK_SIZE_MASK) != 0 {
let source = ghb.get_luminance_source();
let width = source.get_width();
let height = source.get_height();
let matrix = if width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION {
let luminances = source.get_matrix();
let mut sub_width = width >> BLOCK_SIZE_POWER;
if (width & BLOCK_SIZE_MASK) != 0 {
sub_width += 1;
}
let mut sub_height = height >> HybridBinarizer::BLOCK_SIZE_POWER;
if (height & HybridBinarizer::BLOCK_SIZE_MASK) != 0 {
let mut sub_height = height >> BLOCK_SIZE_POWER;
if (height & BLOCK_SIZE_MASK) != 0 {
sub_height += 1;
}
let black_points = Self::calculateBlackPoints(
@@ -141,7 +144,7 @@ impl HybridBinarizer {
Ok(new_matrix)
} else {
// If the image is too small, fall back to the global histogram approach.
let m = ghb.getBlackMatrix()?;
let m = ghb.get_black_matrix()?;
Ok(m.clone())
};
// dbg!(matrix.to_string());
@@ -162,18 +165,18 @@ impl HybridBinarizer {
black_points: &[Vec<u32>],
matrix: &mut BitMatrix,
) {
let maxYOffset = height - HybridBinarizer::BLOCK_SIZE as u32;
let maxXOffset = width - HybridBinarizer::BLOCK_SIZE as u32;
let maxYOffset = height - BLOCK_SIZE as u32;
let maxXOffset = width - BLOCK_SIZE as u32;
for y in 0..sub_height {
// for (int y = 0; y < subHeight; y++) {
let mut yoffset = y << HybridBinarizer::BLOCK_SIZE_POWER;
let mut yoffset = y << BLOCK_SIZE_POWER;
if yoffset > maxYOffset {
yoffset = maxYOffset;
}
let top = Self::cap(y, sub_height - 3);
for x in 0..sub_width {
// for (int x = 0; x < subWidth; x++) {
let mut xoffset = x << HybridBinarizer::BLOCK_SIZE_POWER;
let mut xoffset = x << BLOCK_SIZE_POWER;
if xoffset > maxXOffset {
xoffset = maxXOffset;
}
@@ -215,9 +218,9 @@ impl HybridBinarizer {
matrix: &mut BitMatrix,
) {
let mut offset = yoffset * stride + xoffset;
for y in 0..HybridBinarizer::BLOCK_SIZE {
for y in 0..BLOCK_SIZE {
// for (int y = 0, offset = yoffset * stride + xoffset; y < HybridBinarizer::BLOCK_SIZE; y++, offset += stride) {
for x in 0..HybridBinarizer::BLOCK_SIZE {
for x in 0..BLOCK_SIZE {
// for (int x = 0; x < HybridBinarizer::BLOCK_SIZE; x++) {
// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
if luminances[offset as usize + x] as u32 <= threshold {
@@ -240,18 +243,18 @@ impl HybridBinarizer {
width: u32,
height: u32,
) -> Vec<Vec<u32>> {
let maxYOffset = height as usize - HybridBinarizer::BLOCK_SIZE;
let maxXOffset = width as usize - HybridBinarizer::BLOCK_SIZE;
let maxYOffset = height as usize - BLOCK_SIZE;
let maxXOffset = width as usize - BLOCK_SIZE;
let mut blackPoints = vec![vec![0; subWidth as usize]; subHeight as usize];
for y in 0..subHeight {
// for (int y = 0; y < subHeight; y++) {
let mut yoffset = y << HybridBinarizer::BLOCK_SIZE_POWER;
let mut yoffset = y << BLOCK_SIZE_POWER;
if yoffset > maxYOffset as u32 {
yoffset = maxYOffset as u32;
}
for x in 0..subWidth {
// for (int x = 0; x < subWidth; x++) {
let mut xoffset = x << HybridBinarizer::BLOCK_SIZE_POWER;
let mut xoffset = x << BLOCK_SIZE_POWER;
if xoffset > maxXOffset as u32 {
xoffset = maxXOffset as u32;
}
@@ -261,9 +264,9 @@ impl HybridBinarizer {
let mut offset = yoffset * width + xoffset;
let mut yy = 0;
while yy < HybridBinarizer::BLOCK_SIZE {
while yy < BLOCK_SIZE {
// for (int yy = 0, offset = yoffset * width + xoffset; yy < HybridBinarizer::BLOCK_SIZE; yy++, offset += width) {
for xx in 0..HybridBinarizer::BLOCK_SIZE {
for xx in 0..BLOCK_SIZE {
// for (int xx = 0; xx < HybridBinarizer::BLOCK_SIZE; xx++) {
let pixel = luminances[offset as usize + xx];
sum += pixel as u32;
@@ -276,13 +279,13 @@ impl HybridBinarizer {
}
}
// short-circuit min/max tests once dynamic range is met
if (max - min) as usize > HybridBinarizer::MIN_DYNAMIC_RANGE {
if (max - min) as usize > MIN_DYNAMIC_RANGE {
// finish the rest of the rows quickly
offset += width;
yy += 1;
while yy < HybridBinarizer::BLOCK_SIZE {
while yy < BLOCK_SIZE {
// for (yy++, offset += width; yy < HybridBinarizer::BLOCK_SIZE; yy++, offset += width) {
for xx in 0..HybridBinarizer::BLOCK_SIZE {
for xx in 0..BLOCK_SIZE {
// for (int xx = 0; xx < BLOCK_SIZE; xx++) {
sum += luminances[offset as usize + xx] as u32;
}
@@ -296,8 +299,8 @@ impl HybridBinarizer {
}
// The default estimate is the average of the values in the block.
let mut average = sum >> (HybridBinarizer::BLOCK_SIZE_POWER * 2);
if (max - min) as usize <= HybridBinarizer::MIN_DYNAMIC_RANGE {
let mut average = sum >> (BLOCK_SIZE_POWER * 2);
if (max - min) as usize <= MIN_DYNAMIC_RANGE {
// If variation within the block is low, assume this is a block with only light or only
// dark pixels. In that case we do not want to use the average, as it would divide this
// low contrast area into black and white pixels, essentially creating data out of noise.

View File

@@ -19,7 +19,7 @@ pub struct OtsuLevelBinarizer {
impl OtsuLevelBinarizer {
fn generate_threshold_matrix(source: &dyn LuminanceSource) -> Result<BitMatrix> {
let image_buffer = {
let Some(buff) : Option<ImageBuffer<Luma<u8>,Vec<u8>>> = ImageBuffer::from_vec(source.getWidth() as u32, source.getHeight() as u32, source.getMatrix()) else {
let Some(buff) : Option<ImageBuffer<Luma<u8>,Vec<u8>>> = ImageBuffer::from_vec(source.get_width() as u32, source.get_height() as u32, source.get_matrix()) else {
return Err(Exceptions::ILLEGAL_ARGUMENT)
};
buff
@@ -36,9 +36,9 @@ impl OtsuLevelBinarizer {
pub fn new(source: Box<dyn LuminanceSource>) -> Self {
Self {
width: source.getWidth(),
height: source.getHeight(),
black_row_cache: vec![OnceCell::default(); source.getHeight()],
width: source.get_width(),
height: source.get_height(),
black_row_cache: vec![OnceCell::default(); source.get_height()],
source,
black_matrix: OnceCell::new(),
}
@@ -46,38 +46,38 @@ impl OtsuLevelBinarizer {
}
impl Binarizer for OtsuLevelBinarizer {
fn getLuminanceSource(&self) -> &Box<dyn crate::LuminanceSource> {
fn get_luminance_source(&self) -> &Box<dyn crate::LuminanceSource> {
&self.source
}
fn getBlackRow(&self, y: usize) -> Result<std::borrow::Cow<super::BitArray>> {
fn get_black_row(&self, y: usize) -> Result<std::borrow::Cow<super::BitArray>> {
let row = self.black_row_cache[y].get_or_try_init(|| {
let matrix = self.getBlackMatrix()?;
let matrix = self.get_black_matrix()?;
Ok(matrix.getRow(y as u32))
})?;
Ok(Cow::Borrowed(row))
}
fn getBlackMatrix(&self) -> Result<&super::BitMatrix> {
fn get_black_matrix(&self) -> Result<&super::BitMatrix> {
let matrix = self
.black_matrix
.get_or_try_init(|| Self::generate_threshold_matrix(self.source.as_ref()))?;
Ok(matrix)
}
fn createBinarizer(
fn create_binarizer(
&self,
source: Box<dyn crate::LuminanceSource>,
) -> std::rc::Rc<dyn Binarizer> {
Rc::new(Self::new(source))
}
fn getWidth(&self) -> usize {
fn get_width(&self) -> usize {
self.width
}
fn getHeight(&self) -> usize {
fn get_height(&self) -> usize {
self.height
}
}