2017-01-15 92 views
0

我正在嘗試使用帶有一些深度圖像的go-skeltrack庫(不使用freenect)。爲此,我需要通過我自己的替換kinect圖像來修改所提供的示例。爲此,我必須讀取圖像並稍後將其轉換爲[]uint16變量。這是我試過的代碼是:Golang:如何將image.image轉換爲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。去:155:不能使用integerImage(類型uint16)作爲類型[] uint16 onDepthFrame的參數

這當然是指我生成一個整數而不是數組的事實。我很困惑Go數據類型轉換的工作方式。請幫忙!

在此先感謝您的幫助。 Luis

+3

一個PNG不是一系列的big endian uint16s。你究竟想要做什麼? – JimB

回答

0

binary.BigEndian.Uint16使用大端字節順序將兩個字節(片中)轉換爲16位值。如果您想字節轉換到uint16片,你應該使用binary.Read

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

這聽起來像你正在尋找獲得原始像素。如果是這種情況,我不建議直接將文件作爲二進制文件讀取。這意味着你需要自己解析文件格式,因爲圖像文件包含的信息不僅僅是原始像素值。圖像包中已經有工具可以處理這個問題。

這段代碼應該讓你走上正確的軌道。它讀取RGBA值,所以它以一個長度爲寬*高* 4的uint8的1D數組結束,因爲每個像素有四個值。

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