Created
November 10, 2016 21:53
-
-
Save nticaric/b07da8180375d1beb9148293afa827f2 to your computer and use it in GitHub Desktop.
A function that returns an array containing raw MNIST images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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