Golang:如何将image.image转换为uint16

时间:2017-01-15 16:53:36

标签: go types type-conversion

我正在尝试使用带有一些深度图像的go-skeltrack库(不使用freenect)。为此,我需要通过自己替换kinect图像来修改提供的示例。为此,我必须阅读图像并稍后将其转换为[]uint16变量。我试过的代码是:

file, err := os.Open("./images/4.png")
if err != nil {
    fmt.Println("4.png file not found!")
    os.Exit(1)
}
defer file.Close()

fileInfo, _ := file.Stat()
var size int64 = fileInfo.Size()
bytes := make([]byte, size)

// read file into bytes 
buffer := bufio.NewReader(file)
_, err = buffer.Read(bytes)  

integerImage := binary.BigEndian.Uint16(bytes)

onDepthFrame(integerImage)

其中onDepthFrame是具有

形式的函数
func onDepthFrame(depth []uint16).

但是我在编译时遇到以下错误:

  

./ skeltrackOfflineImage.go:155:不能在onDepthFrame的参数中使用integerImage(类型uint16)作为类型[] uint16

当然,这是指我生成一个整数而不是数组的事实。我对Go数据类型转换的工作方式感到很困惑。请帮忙!

提前感谢您的帮助。 路易斯

2 个答案:

答案 0 :(得分:0)

binary.BigEndian.Uint16使用big endian字节顺序将两个字节(在一个片中)转换为16位值。如果要将字节转换为uint16的切片,则应使用binary.Read

// This reads 10 uint16s from file.
slice := make([]uint16, 10)
err := binary.Read(file, binary.BigEndian, slice)

答案 1 :(得分:0)

听起来你正在寻找原始像素。如果是这种情况,我建议不要直接将文件作为二进制文件读取。这意味着您需要自己解析文件格式,因为图像文件包含的信息不仅仅是原始像素值。图像包中已经有工具来处理它。

此代码可让您走上正轨。它读取RGBA值,因此它最终得到长度为* height * 4的uint8的一维数组,因为每个像素有四个值。

https://play.golang.org/p/WUgHQ3pRla

import (
    "bufio"
    "fmt"
    "image"
    "os"

    // for decoding png files
    _ "image/png"
)

// RGBA attempts to load an image from file and return the raw RGBA pixel values.
func RGBA(path string) ([]uint8, error) {
    file, err := os.Open(path)
    if err != nil {
        return nil, err
    }

    img, _, err := image.Decode(bufio.NewReader(file))
    if err != nil {
        return nil, err
    }

    switch trueim := img.(type) {
    case *image.RGBA:
        return trueim.Pix, nil
    case *image.NRGBA:
        return trueim.Pix, nil
    }
    return nil, fmt.Errorf("unhandled image format")
}

我不完全确定你需要的uint16值应该来自哪里,但可能是每个像素的数据,所以除trueim上的开关外,代码应与此非常相似应该检查image.RGBA以外的其他内容。查看https://golang.org/pkg/image

中的其他图片类型
相关问题