Posted by Anonymous on Sun 28th Oct 16:26 (modification of post by view diff)
download | new post
- require 5.008;
- use strict;
- use Exporter;
- use base 'Exporter';
- our %EXPORT_TAGS = (
- DISABLE_CACHE ENABLE_CACHE
- DISABLE_DRAW ENABLE_DRAW
- LINEBIT_IDENTIFIER
- ON_CLOCK AFTER_CLOCK
- SEARCH_DOWN SEARCH_UP
- BLACK_PIXEL WHITE_PIXEL
- )],
- );
- our @EXPORT_OK = (
- @{ $EXPORT_TAGS{'all'} },
- );
- our $VERSION = '1.00';
- =head1 Name
- ARS::Coupon::OMR::Clock - Optical Mark Recognition for clock based coupons
- =head1 VERSION
- Version 1.0
- =head1 SYNOPSIS
- use ARS::Coupon::OMR::Clock;
- $omr = ARS::Coupon::OMR::Clock->new($img, $struct);
- =head1 DESCRIPTION
- C<ARS::Coupon::OMR::Clock> provides an object interface to process an
- Image::Magick image resource, converting it into a grid reference
- =head1 CONSTANTS
- =item (CACHE) DISABLE_CACHE, ENABLE_CACHE
- Enable or disable caching
- =item (DRAW) DISABLE_DRAW, ENABLE_DRAW
- Enable or disable drawing
- =item (IDTYPE) LINEBIT_IDENTIFIER
- The type of identifier to use, only LINEBIT_IDENTIFIER exists at the
- moment.
- =item (CLOCK) ON_CLOCK, AFTER_CLOCK
- Where to look for cells, on the clock or after the clock?
- =item (SEARCH) SEARCH_DOWN, SEARCH_UP
- Which direction to search in
- =item (COLOR) BLACK_PIXEL, WHITE_PIXEL
- What color pixel are we looking for
- =cut
- use constant DISABLE_CACHE => 0;
- use constant ENABLE_CACHE => 1;
- use constant DISABLE_DRAW => 0;
- use constant ENABLE_DRAW => 1;
- use constant LINEBIT_IDENTIFIER => 0;
- use constant LEFT_ALIGNED => 0;
- use constant RIGHT_ALIGNED => 1;
- use constant ON_CLOCK => 0;
- use constant AFTER_CLOCK => 1;
- use constant SEARCH_DOWN => 0;
- use constant SEARCH_UP => 1;
- use constant BLACK_PIXEL => 0;
- use constant WHITE_PIXEL => 1;
- =head1 CONSTRUCTOR
- =over 4
- =item new ( $img, $struct[, CACHE, DRAW] )
- $img is an Image::Magick image handle
- $struct is the structure defined below
- CACHE (default ENABLE_CACHE) set to DISABLE_CACHE to disable caching of information
- =item $struct
- This is a basic definition of the structure the library needs to do the dirty work.
- All the numbers below are percentages (0.5 = 50%) of page dimensions
- $strut = {
- sensitivity => 0.5, # Global Sensitivity - Optional, defaults to 0.01
- # Clock defines the parameters of the clock and is required once
- clock => {
- indent => 0.0123, # How far to look in from the side for the clock marks
- side => RIGHT_ALIGNED, # Which side is the clock on (LEFT_ALIGNED / RIGHT_ALIGNED)
- type => AFTER_CLOCK, # ON_CLOCK / AFTER_CLOCK
- width => 0.01845, # Approx width of the black clock mark (only used as a guide)
- height => 0.01231, # The approx height of the black clock mark (Again only used as a guide)
- padding => 0.01212, # The approx spacing between black clock marks (see above)
- after => 0.1294, # (Optional) Only start looking X distance down the page for the clock
- before => 0.9481, # (Optional) Don't look any further then X distance down the page
- },
- # Identifier defines the parameters of an identifier and is optional, but can only be used once
- # if Identifier is not supplied it guesses that the identifier is the first row of results
- identifier => {
- after => 0.1294, # (Optional) Only start looking X distance down the page for the identifier
- before => 0.9481, # (Optional) Don't look any further then X distance down the page
- width => 0.01845, # Approx width of the identifier
- sensitivity => 0.4, # How much black pixel coverage are we looking for (1px X widthpx)
- type => LINEBIT_IDENTIFIER, # Reserved, required (IDTYPE)
- side => LEFT_ALIGNED, # Which side to look on (LEFT_ALIGNED / RIGHT_ALIGNED)
- },
- # Cell lets you define the basic parameters of the cells, you can have more then one
- # definition - this is required
- cell => {
- default => { # If no other definition exists, use this one
- width => 0.123, # The width of the cell
- indent => 0.123, # Padding between the cell and the reference side
- side => RIGHT_ALIGNED, # Reference side - (LEFT_ALIGNED / RIGHT_ALIGNED)
- padding => 0.123, # Padding between cells
- }
- 1234 => { # Special configuration for game identified as 1234
- width => 0.123, # The width of the cell
- indent => 0.123, # Padding between the cell and the reference side
- side => RIGHT_ALIGNED, # Reference side - (LEFT_ALIGNED / RIGHT_ALIGNED)
- padding => 0.123, # Padding between cells
- }
- },
- }
- =back
- =cut
- sub new {
- my $self = {
- image => shift,
- struct => shift,
- caching => shift || ENABLE_CACHE,
- draw => shift || DISABLE_DRAW,
- cache => {},
- };
- my $image_width = $self->{image}->Get('width');
- my $image_height = $self->{image}->Get('height');
- # Calculate the real pixel sizes based on the percentages in the structure
- $self->{image_height} = $image_height;
- $self->{image_width} = $image_width;
- # We do our quick searches by halves, technically could do it by 1.1 or something
- # but I dowbt it would make much difference
- $self->{clock_search_y} = $self->{clock_height} / 3;
- $self->{clock_search_x} = $self->{clock_width} / 2;
- # Make sure that we have a default sensitivity
- # Left or right orientated clock?
- if ($self->{struct}->{clock}->{side} == 1) {
- $self->{clock_search_x} = $image_width - ($self->{clock_indent} + $self->{clock_search_x});
- }
- else {
- $self->{clock_search_x} += $self->{clock_indent};
- }
- # Define sensible clock boundaries, notice the 5 px margin on the default def.
- ? $image_height * $self->{struct}->{clock}->{before}
- : $image_height - 5
- );
- ? $image_height * $self->{struct}->{clock}->{after}
- : 5
- );
- # Search down the image looking for the approximate location of the clock
- my $approx
- = $self->clockSearch( $clock_after, $clock_before, $self->{clock_search_y}, SEARCH_DOWN, BLACK_PIXEL );
- # Search back up looking for the first white bit
- $self->{clock_top} = int($self->clockSearch( $clock_after, $approx, 1, SEARCH_UP, WHITE_PIXEL )) + 1;
- # Measure the size of the clock (We trust this more then the provided size)
- $self->{clock_height}
- = int($self->clockSearch( $self->{clock_top}, $clock_before, 1, SEARCH_DOWN, WHITE_PIXEL)) - $self->{clock_top};
- # Measure the spacing between clocks (We don't trust the padding either)
- my $clock_mark_bottom = $self->{clock_top} + $self->{clock_height};
- $self->{clock_padding}
- = int($self->clockSearch( $clock_mark_bottom, $clock_before, 1, SEARCH_DOWN, BLACK_PIXEL)) - $clock_mark_bottom;
- # Search up from the bottom of the image looking for the approximate end of the clock
- $approx = $self->clockSearch( $self->{clock_top}, $clock_before, $self->{clock_search_y}, SEARCH_UP, BLACK_PIXEL );
- # Search back down looking for the first black bit
- $self->{clock_bottom} = int($self->clockSearch( $approx, $clock_before, 1, SEARCH_DOWN, WHITE_PIXEL ));
- # Set ourselves up with the default specs (The tatts cards require this as the identifier is part of the result set)
- $self->{cell} = 'default';
- $self->_defineCell();
- # Now that we know about the clock, lets identify the card.
- $self->{card_id} = $self->getIdentifier();
- $self->{cell} = $self->{card_id};
- $self->_defineCell();
- }
- return $self;
- }
- sub _defineCell() {
- $self->{cell_indent} = int($self->{image_width} * $self->{struct}->{cell}->{$self->{cell}}->{indent});
- # We need these not to be whole integers...
- $self->{cell_padding} = $self->{image_width} * $self->{struct}->{cell}->{$self->{cell}}->{padding};
- $self->{cell_width} = $self->{image_width} * $self->{struct}->{cell}->{$self->{cell}}->{width};
- $self->{cell_count} = int(($self->{image_width} - $self->{cell_indent}) / ($self->{cell_width} + $self->{cell_padding}));
- }
- =head1 METHODS
- getIdentifier
- detect
- getCellCoverage
- getPixelCoverage
- countClock
- getClock
- clockSearch
- getSinglePixel
- =over 4
- =item getIdentifier
- Scans the gamecard to return the identifier.
- and find it. If not, then it guesses that the first line of results from the
- clock is what you want.
- =cut
- sub getIdentifier {
- my $self = shift;
- if ( !( exists $self->{cache}->{getIdentifier} && $self->{caching} ) ) {
- if (exists($self->{struct}->{identifier})) {
- # Shortcut, I'm lazy
- my $id_props = $self->{struct}->{identifier};
- # Create logical upper and lower boundries, again notice the 5 px padding
- ? $self->{image_height} * $id_props->{before}
- : $self->{image_height} - 5
- );
- ? $self->{image_height} * $id_props->{after}
- : 5
- );
- my $line_max_size = 0;
- my @id_lines = ();
- # The only type here at the moment
- if ($id_props->{type} == LINEBIT_IDENTIFIER) {
- # Left or right side
- $id_props->{side}
- ? $self->{image_width} - ($id_width + $id_indent)
- : $id_indent
- );
- # Find the top of the identifier
- my $coverage = 0;
- while ($coverage < $id_props->{sensitivity}) {
- $coverage = $self->getPixelCoverage($id_left, ++$id_top, $id_width, ENABLE_DRAW);
- }
- # Find the bottom of the identifier
- $coverage = 0;
- while ($coverage < $id_props->{sensitivity}) {
- $coverage = $self->getPixelCoverage($id_left, --$id_bottom, $id_width, ENABLE_DRAW);
- }
- my $cursor = $id_top;
- # Assume we're starting in a 100% covered area
- $coverage = 1;
- # Loop through the area defined by $id_top and $id_bottom
- while ($cursor < $id_bottom) {
- # Work the blackspace
- my $cur_start = $cursor;
- while ($coverage >= $id_props->{sensitivity}) {
- $coverage = $self->getPixelCoverage($id_left, ++$cursor, $id_width, ENABLE_DRAW);
- }
- if ($self->{draw}) {
- $self->{image}->Draw(
- primitive => 'line',
- stroke => 'red',
- points => ($id_left + $id_width) . ",$cur_start $id_left,$cursor"
- );
- }
- my $height = $cursor - $cur_start;
- $line_max_size = $height > $line_max_size ? $height : $line_max_size;
- # Work the whitespace
- $cur_start = $cursor;
- while ($coverage < $id_props->{sensitivity}) {
- last if ($cursor >= $id_bottom);
- $coverage = $self->getPixelCoverage($id_left, ++$cursor, $id_width, ENABLE_DRAW);
- }
- if ($self->{draw}) {
- $self->{image}->Draw(
- primitive => 'line', stroke => 'blue', points => "$id_left,$cur_start $id_left,$cursor "
- );
- $self->{image}->Draw(
- primitive => 'line', stroke => 'blue', points => ($id_left + $id_width) . ",$cur_start " . ($id_left + $id_width) . ",$cursor"
- );
- }
- }
- }
- # Convert the array into an integer we can use
- # Not the best theory used here, but based on the fact
- # that I have not seen a card with two sequential blank
- # bits, I've just made the rather poor assumption that
- # there is none.
- # Should re-address this when I'm not so tired, I suspect
- # I can knock something up with ratios against the blank spots
- # to work out the maximum blank size
- my $identifier = 0;
- foreach (@id_lines) {
- if (${$_}[0] == 1) {
- $identifier = ($identifier << 1) + 1;
- } elsif (${$_}[1] > $line_max_size * 2) {
- $identifier <<= 1;
- }
- }
- $self->{cache}->{getIdentifier} = $identifier;
- }
- # Default action is to extract the identifier from the first clock (ala Tatts)
- else {
- my $identifier = 0;
- for my $cell (0..($self->{cell_count} - 1)) {
- if ( $self->getCellCoverage( $cell, 0 ) >= $self->{struct}->{sensitivity} ) {
- $identifier += 1 << $cell;
- }
- }
- $self->{cache}->{getIdentifier} = $identifier;
- }
- }
- }
- =item detect
- The brains and brawn of this module, this should be the only function you need
- to call. Returns a game hash (compatible with Pdi's with the exception of a
- new iGame element that has the identifier from the card)
- =cut
- sub detect {
- my $self = shift;
- my $sensitivity = $self->{struct}->{sensitivity};
- my @indices;
- my $index_counter = 0;
- for my $row ( 0..($self->countClock() - 1) ) {
- my $line = '';
- for my $column ( 0..($self->{cell_count} - 1) ) {
- if ($self->getCellCoverage($column,$row) > $sensitivity) {
- my %record = (
- iOmrRow => $row + 1,
- iOmrColumn => $column + 1,
- iIndex => ++$index_counter,
- );
- push @indices, \%record;
- if ($self->{draw}) {
- print "1";
- }
- }
- elsif ($self->{draw}) {
- print "0";
- }
- }
- if ($self->{draw}) {
- print "\n";
- }
- }
- my $data = {
- aZones => [
- {
- pIndices => $index_counter,
- aIndices => \@indices,
- },
- ],
- pZones => 1,
- iGame => $self->getIdentifier(),
- };
- return $data;
- }
- =item getCellCoverage($position_x, $position_y)
- Get the % of black in the cell at $position_x and $position_y.
- Automatically calculates the geometry and location of the cell.
- =cut
- sub getCellCoverage {
- my $self = shift;
- my $position_x = shift;
- my $position_y = shift;
- if ( !( exists $self->{cache}->{getCellCoverage}->{$position_x}->{$position_y} ) ) {
- my $cell_indent = $self->{cell_indent} + (($self->{cell_padding} + $self->{cell_width}) * $position_x);
- # Right aligned cells...
- if ( $self->{struct}->{cell}->{$self->{cell}}->{side} == RIGHT_ALIGNED ) {
- $cell_indent = $self->{image_width} - ($cell_indent + $self->{cell_width});
- }
- my $clock = $self->getClock($position_y);
- # Cell after clock
- if ($self->{struct}->{clock}->{type} == AFTER_CLOCK) {
- # Some of the samples provided the cells actually overlap the clock a little, we compensate here for that
- my $cell_top = $clock->{top} + $self->{clock_height} / 3;
- $self->{cache}->{getCellCoverage}->{$position_x}->{$position_y}
- = $self->getPixelCoverage($cell_indent, $cell_top, $self->{cell_width}, $self->{clock_padding}, ENABLE_DRAW);
- }
- # Cell on clock
- else {
- my $cell_top = $clock->{top};
- $self->{cache}->{getCellCoverage}->{$position_x}->{$position_y}
- = $self->getPixelCoverage($cell_indent, $cell_top, $self->{cell_width}, $self->{clock_height}, ENABLE_DRAW);
- }
- }
- return $self->{cache}->{getCellCoverage}->{$position_x}->{$position_y};
- }
- =item getPixelCoverage($left, $top, $width, $height[, (DRAW)])
- Get the % of black in a given area, if $draw is one it draws
- a red box around the area on the canvas.
- =cut
- sub getPixelCoverage {
- my $self = shift;
- my $left = shift;
- my $top = shift;
- my $width = shift;
- my $height = shift;
- my $draw = shift;
- my @pixels = $self->{image}->GetPixels(
- x => $left,
- y => $top,
- width => $width,
- height => $height,
- normalize => 'true',
- );
- # Draw back to the canvas, this is useful for trying to define the slips
- if ($draw && $self->{draw}) {
- $self->{image}->Draw(
- primitive => 'rectangle',
- stroke => "red",
- points => ($left-1).','.($top-1).' '.($left+$width+1).','.($top+$height+1),
- );
- }
- # We want inverse values, normally white is 1 and black is 0.
- return 1 - sum( @pixels ) / 3 / ( @pixels / 3);
- }
- =item countClock
- Counts the clock marks on the page
- =cut
- sub countClock {
- my $self = shift;
- if ( !( exists $self->{cache}->{countClock} && $self->{caching} ) ) {
- # Get the first clock mark
- my $clock = $self->getClock(0);
- my $count = 1;
- while ($clock) {
- $clock = $self->getClock($count++);
- }
- # We end up with one to many (c:
- $self->{cache}->{countClock} = $count - 1;
- }
- return $self->{cache}->{countClock};
- }
- =item getClock($index)
- Get the co-ordinates of the clock at $index, recursive function
- could be very slow without caching turned on.
- =cut
- sub getClock {
- my $self = shift;
- my $index = shift;
- if ( !( exists $self->{cache}->{getClock}->{$index} && $self->{caching} ) ) {
- my $clock_top = 0;
- if ($index == 0) {
- # We already know where clock 0 is.
- $self->{cache}->{getClock}->{$index} = {
- top => $self->{clock_top},
- bottom => $self->{clock_top} + $self->{clock_height},
- };
- }
- else {
- # Provided caching is on, this doesn't hurt us (c:
- my $clock = $self->getClock($index - 1);
- $clock_top = $clock->{bottom};
- # Save some looking, guess approximately where the next clock is
- my $approx = $clock_top + $self->{clock_padding} + $self->{clock_search_y};
- if ($approx < $self->{clock_bottom}) {
- my $next_clock_top = 0;
- my $pixel = $self->getSinglePixel($self->{clock_search_x}, $approx);
- # If it's a white pixel we'll search down for a black one
- if ($pixel == 1) {
- $next_clock_top = $self->clockSearch($approx, $self->{clock_bottom}, 1, SEARCH_DOWN, BLACK_PIXEL) - 1;
- }
- # If ti's a white pixel we'll search up for a white one
- else {
- $next_clock_top = $self->clockSearch($clock_top, $approx, 1, SEARCH_UP, WHITE_PIXEL) + 1;
- }
- $self->{cache}->{getClock}->{$index} = {
- top => $next_clock_top,
- bottom => $next_clock_top + $self->{clock_height},
- };
- }
- else {
- }
- }
- }
- }
- =item clockSearch($start, $stop, $increment[, (SEARCH), (COLOR)])
- Search the page between $start and $stop in $increment steps
- =cut
- sub clockSearch {
- # Saves us an op or two later, we can use all the help we can get (c:
- my $black = !$white;
- if ($direction == SEARCH_DOWN) {
- $increment = -1 * $increment;
- }
- my $search_y = $direction ? $stop : $start;
- while ($search_y >= $start && $search_y <= $stop) {
- $search_y += $increment;
- my $pixel = $self->getSinglePixel($self->{clock_search_x}, $search_y);
- if ($black && $pixel == BLACK_PIXEL) {
- if ($self->{draw}) {
- $self->{image}->Set("pixel[".$self->{clock_search_x}.",$search_y" => '#FF0000');
- }
- return $search_y;
- }
- elsif ($white && $pixel == WHITE_PIXEL) {
- if ($self->{draw}) {
- $self->{image}->Set("pixel[".$self->{clock_search_x}.",$search_y" => '#00FF00');
- }
- return $search_y;
- }
- }
- }
- =item getSinglePixel($position_x, $position_y)
- Shortcut function to get if a single pixel is black or white.
- =cut
- sub getSinglePixel {
- my @pixel = $self->{image}->GetPixels(
- x => $x,
- y => $y,
- width => 1,
- height => 1,
- normalize => 'true',
- );
- # Will result in 1 for white, 0 for black (or any strage obscure result)
- }
- 1;
- __END__
- =back
- =head1 AUTHOR
- ...
- =head1 COPYRIGHT
- ...
- =cut
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.