| 1 | use strict; | ||
| 2 | use warnings; | ||
| 3 | package Imager::Filter::Binarization; | ||
| 4 | # ABSTRACT: A collection of image binarization algorthims as image filter. | ||
| 5 | |||
| 6 | |||
| 7 | use List::Util qw<min max>; | ||
| 8 | use Statistics::Basic qw<vector mean stddev>; | ||
| 9 | |||
| 10 | sub binarization_filter { | ||
| 11 | my %param = @_; | ||
| 12 | my $ctx = { param => \%param }; | ||
| 13 | $ctx->{img_copy} = $param{imager}->copy(); | ||
| 14 | return binarize_with_niblack($ctx); | ||
| 15 | } | ||
| 16 | |||
| 17 | sub binarize_with_niblack { | ||
| 18 | my ($ctx) = @_; | ||
| 19 | my $img = $ctx->{param}{imager}; | ||
| 20 | my $img_copy = $ctx->{img_copy}; | ||
| 21 | |||
| 22 | my ($w,$h) = split("x", $ctx->{param}{geometry}); | ||
| 23 | |||
| 24 | my $img_bound_y = $img->getheight - 1; | ||
| 25 | my $img_bound_x = $img->getwidth - 1; | ||
| 26 | $w ||= $h; | ||
| 27 | my $w_half_1 = int(($w-1)/2); | ||
| 28 | my $w_half_2 = int($w/2); | ||
| 29 | my $h_half_1 = int(($h-1)/2); | ||
| 30 | my $h_half_2 = int($h/2); | ||
| 31 | |||
| 32 | my $summerize_method = __PACKAGE__->can("summerize_" . $ctx->{param}{method}); | ||
| 33 | die "Unknown method: $ctx->{param}{method}" unless $summerize_method; | ||
| 34 | |||
| 35 | for my $y (0 .. $img_bound_y) { | ||
| 36 | for my $x (0..$img_bound_x) { | ||
| 37 | my $y_0 = max(0, $y - $h_half_1); | ||
| 38 | my $y_1 = min($y + $h_half_2, $img_bound_y); | ||
| 39 | my $x_0 = max(0, $x - $w_half_1); | ||
| 40 | my $x_1 = min($x + $w_half_2, $img_bound_x); | ||
| 41 | my $w_ = $x_1 - $x_0 + 1; | ||
| 42 | my $center = $img_copy->getpixel( x=> $x, y => $y ); | ||
| 43 | my @px = map { $img_copy->getscanline(y => $_, x => $x_0, width => $w_) } ($y_0 .. $y_1); | ||
| 44 | |||
| 45 | my $new_px = $summerize_method->($ctx, $center, \@px); | ||
| 46 | |||
| 47 | $img->setpixel( y => $y, x => $x, color => $new_px); | ||
| 48 | } | ||
| 49 | } | ||
| 50 | } | ||
| 51 | |||
| 52 | sub summerize_niblack { | ||
| 53 | my ($ctx, $current_pixel, $pixels) = @_; | ||
| 54 | my @c = map { ($_->rgba)[0] } @$pixels; | ||
| 55 | my $v = vector(@c); | ||
| 56 | my $T = mean($v) + ($ctx->{params}{k} // 0.2) * stddev($v); | ||
| 57 | my $c = ($current_pixel->rgba)[0]; | ||
| 58 | return [ (($c > $T) ? 255 : 0) , 0, 0 ]; | ||
| 59 | } | ||
| 60 | |||
| 61 | sub summerize_sauvola { | ||
| 62 | my ($ctx, $current_pixel, $pixels) = @_; | ||
| 63 | my @c = map { ($_->rgba)[0] } @$pixels; | ||
| 64 | my $v = vector(@c); | ||
| 65 | my $T = mean($v) * (1 + ($ctx->{params}{k} // 0.5) * (stddev($v)/ ($ctx->{params}{R} // 128) - 1)); | ||
| 66 | my $c = ($current_pixel->rgba)[0]; | ||
| 67 | return [ (($c > $T) ? 255 : 0) , 0, 0 ]; | ||
| 68 | } | ||
| 69 | |||
| 70 | Imager->register_filter( | ||
| 71 | type => 'binarization', | ||
| 72 | callsub => \&binarization_filter, | ||
| 73 | callseq => ['image', 'method', 'geometry'], | ||
| 74 | defaults => {}, | ||
| 75 | ); | ||
| 76 | |||
| 77 | __END__ |