2016-10-03 101 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