Search code examples
c#imagecsvconvertersppm

Convert image to CSV


What is away to break up an image into a grid of square cells, color each cell with the average color it contains, and export the resulting averages as a csv file?

Since ppms are simple image formats, conversion to ppm format may be a good place start, but what next?

Motivation: I am making a game world map and wish to convert a color coded map (colors indicate biome type) into a data file (such as csv) that is readable by other source code files.

Since the game map will be updated as the game is developed, I hope to automate this process, so I feel a code based solution would be optimal; it is written in C#.


Solution

  • You can use ImageMagick which is installed on most Linux distros and is available for macOS and Windows.

    Just in Terminal (or Command Prompt on Windows), starting with this 500x256 image:

    enter image description here

    magick start.png -resize 3x2\! -depth 8 -compress none ppm:
    P3
    3 2
    255
    189 0 66 189 0 66 189 0 66 
    66 0 189 66 0 189 66 0 189
    

    That has resized the image and averaged the colours into a 3x2 image (choose a different size if you wish) and printed the output as a textual PPM file.

    The size is 3x2, and the first row is 3 pixels with rgb(189,0,66) which is largely red and the second row is 3 pixels with rgb(66,0,189) which is largely blue.

    I'll leave you to format as CSV :-)


    Here you can resize it down and scale it back up to see the effect of averaging over 8x3 blocks:

    magick start.png -resize 8x3\! -depth 8 -scale 400x result.png
    

    enter image description here


    Depending on what you like parsing, you can produce the same information in a slightly different format:

    magick start.png -resize 8x3\! -depth 8 txt:
    
    # ImageMagick pixel enumeration: 8,3,65535,srgb
    0,0: (54998,0,10537)  #D60029  srgb(214,0,41)
    1,0: (54998,0,10537)  #D60029  srgb(214,0,41)
    2,0: (54998,0,10537)  #D60029  srgb(214,0,41)
    3,0: (54998,0,10537)  #D60029  srgb(214,0,41)
    4,0: (54998,0,10537)  #D60029  srgb(214,0,41)
    5,0: (54998,0,10537)  #D60029  srgb(214,0,41)
    ...
    ...
    3,1: (32896,0,32896)  #800080  purple
    4,1: (32896,0,32896)  #800080  purple
    5,1: (32896,0,32896)  #800080  purple
    6,1: (32896,0,32896)  #800080  purple
    7,1: (32896,0,32896)  #800080  purple
    0,2: (10537,0,54998)  #2900D6  srgb(41,0,214)
    5,2: (10537,0,54998)  #2900D6  srgb(41,0,214)
    6,2: (10537,0,54998)  #2900D6  srgb(41,0,214)
    7,2: (10537,0,54998)  #2900D6  srgb(41,0,214)