【问题标题】:Golang: How to convert an image.image to uint16Golang:如何将 image.image 转换为 uint16
【发布时间】:2017-01-15 16:53:36
【问题描述】:

我正在尝试将 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 数据类型转换的工作方式感到很困惑。请帮忙!

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

【问题讨论】:

  • PNG 不是一系列大端 uint16。你到底想做什么?

标签: go types type-conversion


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    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 上的开关应该可能检查除 @ 以外的其他内容987654325@。看看https://golang.org/pkg/image中的其他图片类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 2018-03-20
      相关资源
      最近更新 更多