mnistの手書き数字を画像に
mnist のファイルをダウンロード
今回は学習用データーだけで行います。
ダウンロードはここから。
http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
train-images-idx3-ubyteの形式
train-images-idx3-ubyte.gzを展開してできるtrain-images-idx3-ubyteは以下のような形式になっています。
オフセット | 0 | 4 | 8 | 12 |
内容 | 識別子 | 画像の枚数 | 画像の縦の長さ | 画像の横の長さ |
offset = 16からはグレースケールの画像データーが連続しています。
オフセット | 16 | 17 | 18 | 19 |
内容 | 1枚目 (0, 0) | 1枚目 (0, 1) | 1枚目 (0, 2) | 1枚目 (0, 3) |
オフセット | 800 | 801 | 802 | 803 |
内容 | 2枚目 (0, 0) | 2枚目 (0, 1) | 2枚目 (0, 2) | 2枚目 (0, 3) |
k枚目の(i, j)を取得したい場合は、
$offset(k, i, j) = 784k + 28i + j + 16$
スクリプトで画像60000枚に変換
require "matrix" require "mini_magick" %w(train-images-idx3-ubyte.gz).each do |file| unless File.exist? file system "wget http://yann.lecun.com/exdb/mnist/#{file}" system "gzip -d #{file}" end end bin = nil open "train-images-idx3-ubyte", "rb" do |f| bin = f.each_byte.to_a end mat = nil 60000.times do |k| mat = Matrix.zero(28, 28) 28.times do |i| 28.times do |j| mat[i, j] = bin[784*k+16+28*i+j] end end img = MiniMagick::Image.import_pixels(blob = mat.to_a.flatten.pack("C*"), columns = 28, rows = 28, depth = 8, map = "gray") img.write "images/#{k}.png" end