【问题标题】:ioutil ReadFile adds extra bytesioutil ReadFile 添加额外的字节
【发布时间】:2018-09-10 15:03:56
【问题描述】:

我一直在努力尝试将一些 MNIST 数据库绘制到一个图像文件中,在我的第一次尝试中,生成的图像似乎发生了变化,如下所示:

我知道训练文件由 60,000 张图像组成,每张图像大小为 28 x 28 像素,在文件中表示为 28 x 28 x 60,000 uint8 的数组,其长度应为 47040000。

但是,当打印文件的长度时,它会给出 47040016 作为它的长度,额外的 16 个数字是导致图像移动的原因。

使用的代码如下,const imgNum 由我要打印的图像和图像的长度定义。读取图像文件时,我真的没有看到任何奇怪的事情发生。

package main

import (
    "image"
    "image/color"
    "image/png"

    "io/ioutil"

    "os"
)

const (
    imgSideLength = 28
    imgSize = imgSideLength * imgSideLength
    imgNum = 499 * imgSize
)

var images []uint8

func main() {
    images, err := ioutil.ReadFile("train-images")
    check(err)

    canvas := image.NewRGBA(image.Rect(0, 0, imgSideLength, imgSideLength))

    pixelIndex := imgNum
    for i := 0; i < imgSideLength; i++ {
        for j := 0; j < imgSideLength; j++ {
            currPixel := images[pixelIndex]
            pixelIndex++

            pixelColor := color.RGBA{currPixel, currPixel, currPixel, 255}
            canvas.Set(j, i, pixelColor)
        }   
    }

    numFile, err := os.Create("number.png")
    check(err)
    defer numFile.Close()

    png.Encode(numFile, canvas)
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

知道这 16 个像素是导致图像偏移的像素,我决定修改 imgNum:

imgNum = 499 * imgSize + 16

通过这种更改,图像绘制得很好。

但我还是想知道为什么不应该多出16个数字?

【问题讨论】:

    标签: file go mnist


    【解决方案1】:

    查看their web site可以看到该文件的数据格式为:

    [offset] [type]          [value]          [description]
    0000     32 bit integer  0x00000803(2051) magic number
    0004     32 bit integer  60000            number of images
    0008     32 bit integer  28               number of rows
    0012     32 bit integer  28               number of columns
    0016     unsigned byte   ??               pixel
    0017     unsigned byte   ??               pixel
    ........
    xxxx     unsigned byte   ??               pixel
    

    这意味着前 16 个字节是 4 个 32 位整数,因此是 16 个字节的标头信息。

    【讨论】:

    • 哦,没意识到。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2021-06-22
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多