Skip to content

Instantly share code, notes, and snippets.

@nticaric
Created November 10, 2016 21:53
Show Gist options
  • Save nticaric/b07da8180375d1beb9148293afa827f2 to your computer and use it in GitHub Desktop.
Save nticaric/b07da8180375d1beb9148293afa827f2 to your computer and use it in GitHub Desktop.
A function that returns an array containing raw MNIST images
<?php
public function loadMNISTImages($filename)
{
$fp = fopen($filename, 'rb');
$array = unpack("N4", fread($fp, 16));
$magic = $array[1];
if($magic != 2051) {
throw new Exception("Bad magic number in $filename", 1);
}
$numOfImages = $array[2];
$numOfRows = $array[3];
$numOfColumns = $array[4];
$pixelsPerImage = $numOfRows * $numOfColumns;
$images = [];
while ( $stream = fread($fp, $pixelsPerImage) ) {
$image = unpack("C{$pixelsPerImage}", $stream);
$images[] = implode(',', $image);
}
fclose($fp);
return $images;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment