#encoding:latin-1 from numpy import * import textwrap def read_pgm(path): fp = file(path,"rb") rr = lambda fp: fp.readline().strip() format = rr(fp) size = map(int, rr(fp).split()) maxcol = int(rr(fp)) if format=="P5": return fromfile(fp, dtype=uint8).reshape(size[1],size[0]) elif format=="P2": data = map(int, fp.read().split()) return array(data, dtype=uint8).reshape(size[1],size[0]) raise Exception("Can not read '%s', format '%s' not implemented" \ % (path, format)) def save_pgm(path, img): """ save image in pgm ascii-format, see http://netpbm.sourceforge.net/doc/pgm.html """ fp = file(path, "wb") fp.write("P2\n") fp.write("%d %d\n" % (img.shape[1], img.shape[0])) fp.write("255\n") scaled_image = require(255*img, uint8).T text = " ".join("%d" % v for v in scaled_image.flatten()) print >> fp, "\n".join(textwrap.wrap(text, 68))