2016-10-03 128 views
1

我嘗試拍攝Image PixelRGB8並將其轉換爲矩陣,以在矩陣上進行一些卷積運算。對於第一次嘗試,我想將其轉換爲矩陣並將矩陣轉換回圖像。Haskell,將圖像轉換爲矩陣

我收到此錯誤:

• No instance for (Element Word8) 
     arising from a use of ‘matrixToImg’ 
    • In the expression: matrixToImg $ imgToMatrix img 
     In an equation for ‘convImg’: 
      convImg img = matrixToImg $ imgToMatrix img 
Failed, modules loaded: none. 

這是什麼意思?

這是代碼。

import Codec.Picture 
import Data.Matrix 
import Data.Vector 
import Data.Vector.Storable 

import Debug.Trace 
import GHC.Word 

import Numeric.LinearAlgebra.Data 
import Numeric.LinearAlgebra 
convImg ::Image PixelRGB8 -> Image PixelRGB8 
convImg img = matrixToImg $ imgToMatrix img 

imgToMatrix ::Image PixelRGB8->Numeric.LinearAlgebra.Matrix Word8 
imgToMatrix Image { imageWidth = w, imageHeight = h, imageData = vec } = ((3*w)><h) (Data.Vector.Storable.toList vec) 

matrixToImg::Numeric.LinearAlgebra.Matrix Word8-> Image PixelRGB8 
matrixToImg matrix = Image (rows matrix `quot` 3) (cols matrix) (vectorToStorableVector (Numeric.LinearAlgebra.Data.flatten(matrix))) 
    where vectorToStorableVector vec= Data.Vector.Storable.fromList $ Numeric.LinearAlgebra.Data.toList vec 

謝謝。

+0

請張貼再現您的錯誤的確切代碼。 – leftaroundabout

+0

我添加了導入。此代碼重現錯誤 – Alon

+2

具有'Element'實例的類型是'Float'' Double','Complex Float'和'Complex Double'。也就是說,你不能用'Word8'做到這一點。如果例如我把浮法代替,這編譯罰款http://sprunge.us/WTIK – Michael

回答

1

hmatrix對於Element具有有限數量的實例,並且Word8不是其中之一。它使用的簡單Integral類型是type Z = Int64。如果你記住,對你而言,Matrix Int64認爲道德上是Word8 s,可以進行如下的轉換。 (這是一樣的你所寫的只是把fromIntegral在幾個地方。)

import Codec.Picture 
import Data.Vector 
import Data.Vector.Storable 

import Debug.Trace 
import GHC.Word 

import Numeric.LinearAlgebra.Data 
import Numeric.LinearAlgebra 

convImg ::Image PixelRGB8 -> Image PixelRGB8 
convImg img = matrixToImg $ imgToMatrix img 

imgToMatrix ::Image PixelRGB8 -> Numeric.LinearAlgebra.Matrix Z 
imgToMatrix Image { imageWidth = w, imageHeight = h, imageData = vec } = ((3*w)><h) (Data.Vector.Storable.toList $ (Data.Vector.Storable.map fromIntegral) (vec)) 

matrixToImg::Numeric.LinearAlgebra.Matrix Z -> Image PixelRGB8 
matrixToImg matrix = Image (rows matrix `quot` 3) (cols matrix) (vectorToStorableVector (Numeric.LinearAlgebra.Data.flatten(matrix))) 
    where vectorToStorableVector = 
       Data.Vector.Storable.fromList . Prelude.map fromIntegral . Numeric.LinearAlgebra.Data.toList