2017-10-18 123 views
0

最近,我一直對機器學習感興趣,特別是機器學習與圖像,但要做到這一點,我需要能夠處理圖像。我希望對圖像處理庫的工作方式有更全面的瞭解,所以我決定建立自己的圖書館來閱讀我能理解的圖像。但是,我似乎有一個問題,當談到讀取圖像的SIZE,因爲這個錯誤彈出,當我嘗試編譯:爲什麼你不能把一個變量作爲一個多維數組大小放在Go中?

./imageProcessing.go:33:11: non-constant array bound Size 

這是我的代碼:

package main 

import (
// "fmt" 
// "os" 
) 

// This function reads a dimension of an image you would use it like readImageDimension("IMAGENAME.PNG", "HEIGHT") 

func readImageDimension(path string, which string) int{ 

var dimensionyes int 

if(which == "" || which == " "){ 
    panic ("You have not entered which dimension you want to have.") 
} else if (which == "Height" || which == "HEIGHT" || which == "height" || which == "h" || which =="H"){ 
    //TODO: Insert code for reading the Height of the image 

    return dimensionyes 

} else if (which == "Width" || which == "WIDTH" || which == "width" || which == "w" || which =="W"){ 
    //TODO: Insert code for reading the Width of the image 

    return dimensionyes 

} else { 
    panic("Dimension type not recognized.") 
    } 
} 

func addImage(path string, image string, Height int, Width int){ 
    var Size int 
    Size = Width * Height 
    var Pix [Size][3]int 
} 

func main() { 


} 

我剛剛開始用Go編程,所以如果這個問題聽起來不怎麼樣,我很抱歉

回答

5

因爲Go是一種靜態類型語言,這意味着變量類型需要在編譯時知道。

Go中的Arrays是固定大小:一旦您在Go中創建數組,您將無法在以後更改其大小。這是因爲數組的長度是數組類型的一部分(這意味着類型[2]int[3]int是2個不同的類型)。

變量的值在編譯時通常是不知道的,所以使用它作爲數組的長度,編譯時就不會知道類型,因此它是不允許的。

閱讀相關的問題:How do I find the size of the array in go

如果你不知道在編譯時的大小,使用slices代替陣列(還有其他原因可以使用切片太)。

例如這樣的代碼:

func addImage(path string, image string, Height int, Width int){ 
    var Size int 
    Size = Width * Height 
    var Pix [Size][3]int 
    // use Pix 
} 

可以轉化創建和使用這樣的片:

func addImage(path string, image string, Height int, Width int){ 
    var Size int 
    Size = Width * Height 
    var Pix = make([][3]int, Size) 
    // use Pix 
} 
相關問題