Skip to content

Commit

Permalink
Improved performance of the chessboard image recognition
Browse files Browse the repository at this point in the history
  • Loading branch information
programarivm committed Oct 22, 2024
1 parent fd1952c commit b336e34
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions src/Media/FEN/JpgToPiecePlacement.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,59 @@

namespace Chess\Media\FEN;

use Chess\Media\PGN\AN\JpgToPiece;
use Rubix\ML\PersistentModel;
use Rubix\ML\Datasets\Unlabeled;
use Rubix\ML\Persisters\Filesystem;

class JpgToPiecePlacement
{
protected \GdImage $image;
const ML_PATH = __DIR__ . '/../../../ml';

private \GdImage $image;

private PersistentModel $estimator;

private array $tiles;

public function __construct(\GdImage $image)
{
$this->image = $image;

$this->estimator = PersistentModel::load(
new Filesystem(self::ML_PATH . '/piece.rbx')
);
}

public function predict(): string
{
$result = '';

$side = imagesx($this->image) / 8;
$y = 0;
for ($i = 0; $i < 8; $i++) {
$x = 0;
for ($j = 0; $j < 8; $j++) {
$tile = imagecrop($this->image, [
$imagecrop = imagecrop($this->image, [
'x' => $x,
'y' => $y,
'width' => $side,
'height' => $side,
]);
if ($tile !== false) {
$result .= (new JpgToPiece($tile))->predict();
imagedestroy($tile);
}
$this->tiles[] = [$imagecrop];
$x += $side;
}
$result .= '/';
$y += $side;
}

$dataset = new Unlabeled($this->tiles);
$prediction = $this->estimator->predict($dataset);

$result = implode('', $prediction);
$result = chunk_split($result, 8, '/');
$result = substr($result, 0, -1);
$result = str_replace('11111111', '8', $result);
$result = str_replace('1111111', '7', $result);
$result = str_replace('111111', '6', $result);
$result = str_replace('11111', '5', $result);
$result = str_replace('1111', '4', $result);
$result = str_replace('111', '3', $result);
$result = str_replace('11', '2', $result);

return $result;

return str_replace(
['11111111', '1111111', '111111', '11111', '1111', '111', '11'],
['8', '7', '6', '5', '4', '3', '2'],
$result
);
}
}

0 comments on commit b336e34

Please sign in to comment.