1
1
import { BitMatrix } from "../BitMatrix" ;
2
+ import { GreyscaleWeigths } from "../index" ;
2
3
3
4
const REGION_SIZE = 8 ;
4
5
const MIN_DYNAMIC_RANGE = 24 ;
@@ -23,18 +24,35 @@ class Matrix {
23
24
}
24
25
}
25
26
26
- export function binarize ( data : Uint8ClampedArray , width : number , height : number , returnInverted : boolean ) {
27
+ export function binarize ( data : Uint8ClampedArray , width : number , height : number , returnInverted : boolean ,
28
+ greyscaleWeigths : GreyscaleWeigths ) {
27
29
if ( data . length !== width * height * 4 ) {
28
30
throw new Error ( "Malformed data passed to binarizer." ) ;
29
31
}
30
32
// Convert image to greyscale
31
33
const greyscalePixels = new Matrix ( width , height ) ;
32
- for ( let x = 0 ; x < width ; x ++ ) {
33
- for ( let y = 0 ; y < height ; y ++ ) {
34
- const r = data [ ( ( y * width + x ) * 4 ) + 0 ] ;
35
- const g = data [ ( ( y * width + x ) * 4 ) + 1 ] ;
36
- const b = data [ ( ( y * width + x ) * 4 ) + 2 ] ;
37
- greyscalePixels . set ( x , y , 0.2126 * r + 0.7152 * g + 0.0722 * b ) ;
34
+ if ( greyscaleWeigths . useIntegerApproximation ) {
35
+ for ( let x = 0 ; x < width ; x ++ ) {
36
+ for ( let y = 0 ; y < height ; y ++ ) {
37
+ const pixelPosition = ( y * width + x ) * 4 ;
38
+ const r = data [ pixelPosition ] ;
39
+ const g = data [ pixelPosition + 1 ] ;
40
+ const b = data [ pixelPosition + 2 ] ;
41
+ greyscalePixels . set ( x , y ,
42
+ // tslint:disable-next-line no-bitwise
43
+ ( greyscaleWeigths . red * r + greyscaleWeigths . green * g + greyscaleWeigths . blue * b + 128 ) >> 8 ) ;
44
+ }
45
+ }
46
+ } else {
47
+ for ( let x = 0 ; x < width ; x ++ ) {
48
+ for ( let y = 0 ; y < height ; y ++ ) {
49
+ const pixelPosition = ( y * width + x ) * 4 ;
50
+ const r = data [ pixelPosition ] ;
51
+ const g = data [ pixelPosition + 1 ] ;
52
+ const b = data [ pixelPosition + 2 ] ;
53
+ greyscalePixels . set ( x , y ,
54
+ greyscaleWeigths . red * r + greyscaleWeigths . green * g + greyscaleWeigths . blue * b ) ;
55
+ }
38
56
}
39
57
}
40
58
const horizontalRegionCount = Math . ceil ( width / REGION_SIZE ) ;
0 commit comments