Wednesday, August 09, 2006

How to create a .pgm file from an .ascii file

Creating a .pgm (portable greymap) file from an .ascii (ESRI Grid format) file, and vice versa, is a very simple task; if you know how to. I stumbled across this problem when I was trying to construct an Object2DGrid within the agent-based modelling toolkit Repast. There are three ways to construct an Object2DGrid: 1) specify the X and Y dimension; 2) construct from an input stream; or, 3) construct from a file. At present only a .pgm file can be read in as a stream or from a file location. This is fine if you wish to create a very basic agent space similar to those available in the Repast demo’s (e.g. Sugarscape) using a graphic’s package (Adobe Photoshop, Paintshop Pro, or GIMP (freeware) can all save as a .pgm file format). However, what happens if you have a raster file within a GIS (e.g. a digital elevation model, DEM), and you wish to use this within you repast model. For example, ArcGIS can only export a raster file (using ArcToolbox) as an .ascii file format. This is awkward because once you have converted a file to .ascii you can no longer view, or edit the file in ArcGIS, or any graphics package. Fortunately, there is a quick solution; just alter the header of the file and change the file extension and to .pgm and you will be able to open and edit the file in a graphic package..

This may seem far fetch, but this situation can arise. For example, Figure 1 is a .shapefile of a building floor plan. This was converted from ‘feature to raster’ using ESRI’s ArcToolbox so the ABM could use the underlying cell values to dictate the movement of the agents (Figure 2). Unfortunately, the raster file can only be exported as an .ascii file from ArcGIS. Figure 3 is a screen capture of the file viewed as text. However, the file can be converted by altering the header in Figure 3 to the header in Figure 4, and changing the file extension from .ascii to .pgm. The value ‘P2’ in the first line is always required, and ‘260’ and ‘260’ refer to the number of columns and rows, while the value in the third line refers to the highest value within the file (for scaling the values to be displayed). The third row should be set as either: 1, 3, 7, 15, 31, 63, 127, or 255. If this value is set considerably larger than the highest value within the file there will be less differential between the values (in terms of grey) to be displayed, and this may result in the image appearing as completely black.

Figure 1: ArcGIS .shapefile of a building floor plan.
Figure 2: Original .shapefile converted to a raster.

Figure 3: Raster file exported as .ascii file format.


Figure 4: Raster file altered to a .pgm file format

No comments: