Haskell,将图像转换为矩阵

时间:2016-10-03 13:09:59

标签: haskell matrix

我尝试拍摄Image PixelRGB8并将其转换为矩阵,在矩阵上进行一些卷积。第一次尝试我想将其转换为矩阵并将矩阵转换回图像。

我收到此错误:

    • 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

感谢。

1 个答案:

答案 0 :(得分: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  
相关问题