我对函数式编程和 Haskell 完全陌生,我需要将 ASCII PGM 图像解析为数据结构,但我不知道该怎么做。
我查看了很多示例(包括 Graphics.Pgm 模块),但仍然不知道如何在 Haskell 中编写它。这是我到目前为止所拥有的(此代码无法编译):
import System.IO
import Control.Monad
import Control.Applicative
import Data.Attoparsec.Char8
import qualified Data.ByteString as B
data ASCIIGreymap = ASCIIGreymap {
aGreyType :: String
, aGreyComment :: String
, aGreyWidth :: Int
, aGreyHeight :: Int
, aGreyMax :: Int
, aGreyData :: [Int]
} deriving (Eq)
instance Show ASCIIGreymap where
show ( ASCIIGreymap t c w h m _ ) = "ASCIIGreymap Type: "++show t ++ "Comment: " ++ show c ++ " w: " ++ show w ++ " h: " ++ show h ++ " max: " ++ show m
parseASCIIGreymap :: Parser ASCIIGreymap
parseASCIIGreymap = do
pgmType <- string
pgmComment <- string
pgmWidth <- integer
char ' '
pgmHeight <- integer
pgmMax <- integer
pgmGreyData <- [integer]
return $ ASCIIGreymap pgmType pgmComment pgmWidth pgmHeight pgmMax pgmGreyData
pgmFile :: FilePath
pgmFile = "test_ascii.pgm"
main = B.readFile logFile >>= print . parseOnly parseASCIIGreymap
示例文件 (test_ascii.pgm) 如下所示:
P2
# CREATOR: GIMP PNM Filter Version 1.1
10 10
255
0
0
0
0
0
64
255
255
255
179
0
0
0
0
0
159
255
255
255
243
0
0
0
0
96
223
255
255
255
255
0
0
64
96
223
255
255
255
255
255
128
128
191
223
255
255
255
255
255
255
255
255
255
255
255
249
217
179
128
128
255
255
255
255
249
198
89
51
0
0
255
255
255
249
198
77
0
0
0
0
255
255
255
236
128
0
0
0
0
0
191
255
255
218
51
0
0
0
0
0
- 第一行包含“magicNumber”,其中 P2 代表 8 位灰度图像
- 第二行是注释
- 第三行用空格分隔图像的宽度和高度
- 第四行是最大灰度值
- 从这里到文件末尾是每个像素的灰度值
我想将此 pgm 文件解析为数据结构(ASCIIGreymap),以便稍后比较两个图像。但就像我说的,我不知道如何到达那里。如果我的方法是错误的,或者如果有更好的方法来解析 pgm 图像,请告诉我。
任何帮助深表感谢!
编辑:由于我在解析 pgm 文件方面没有取得任何进展,我不太确定我的方法是否正确。
有人可以评论我获取文件内容并将其放入数据结构以进一步处理数据的一般想法吗?或者,还有更好的方法?
再次感谢!