How to parse ASCII PGM files in data structures with Haskell?

272 views Asked by At

I am completely new to functional programming and Haskell and i need to parse an ASCII PGM image into a data structure but i can't figure out how to do that.

I have looked at quite a few examples (including the Graphics.Pgm module) but still don't know how to write it in Haskell. Here is what i have so far (this code does not compile):

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

A example file (test_ascii.pgm) looks like this:

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
  1. The first line holds the "magicNumber" where P2 stands for 8bit grey image
  2. The second line is a comment
  3. The third line has the width and height of the image separated with a space
  4. In the fourth line is the max grey value
  5. From here on to the end of the file are the grey values for each pixel

I would like to parse this pgm file into the data structure (ASCIIGreymap) to compare two images later. But like i said i don't know how to get there. If my approach is wrong or if there are better ways of parsing a pgm image please let me know.

Any help is much appreciated!


Edit: Since i haven't made any progress with parsing a pgm file i am not so sure anymore if my approach is correct.
Can someone please comment on my general idea to take the content of the file and put it in a data structure to further work with the data? Or is there a better way?

Thanks again!

0

There are 0 answers