Skip to content

Instantly share code, notes, and snippets.

@robinkraft
Created February 13, 2012 03:05
Show Gist options
  • Save robinkraft/1813036 to your computer and use it in GitHub Desktop.
Save robinkraft/1813036 to your computer and use it in GitHub Desktop.
Convert an image file readable by GDAL into a row-indexed text file
import numpy as np
from osgeo import gdal
def progress(n, interval=100):
"Print progress at regular intervals"
# don't want to divide by zero on first try
if n > 0:
if n % interval == 0:
print "Parsing item %i" % n
return
def image2indexed(fin, fout):
"""Convert image to text, with image row index as first element of each line."""
print "\nLoading file %s" % fin
fp = gdal.Open(fin)
fp_out = open(fout, "w")
arr = fp.ReadAsArray()
print "Parsing file"
for row in xrange(arr.shape[0]):
# this will create a string of the array row
line = " ".join(arr[row, :].astype(str).tolist())
# this writes a line that starts with the row number
fp_out.write(" ".join([str(row), line, "\n"]))
progress(row)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment