#! /usr/bin/python -t # _*_ coding: iso-8859-1 _*_ # Last edited on 2009-11-27 14:26:30 by stolfi MODULE_NAME = "image_pnm" MODULE_DESC = "Tools to create PNM images" MODULE_VERS = "1.0" MODULE_COPYRIGHT = "Copyright © 2009-11-26 by the State University of Campinas (UNICAMP)" import sys import os import math import copy # sys.path[1:0] = [ sys.path[0] + '/../lib', os.path.expandvars('${STOLFIHOME}/lib'), '.' ] # sys.stderr.write("%s.py: path = %r\n" % (MODULE_NAME, sys.path)); class Image_PNM : "PNM images." def __init__(im, nc,nx,ny, mv) : im.nc = nc; # Number of channels. im.nx = nx; # Number of pixel columns. im.ny = ny; # Symbol of pixel rows. im.mv = maxval; # Max sample value. im.smp = nc*nx*ny*[ 0 ]; # Samples, linearized. im.err = None; # Error message, if needed. #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def set_sample(im, c, x, y, v) : "Sets the sample in channel {c}, column {x}, and row {y} of {im} to {v}." assert ((c >= 0) && (c < im.nc)), "{c} out of range"; assert ((x >= 0) && (x < im.nx)), "{x} out of range"; assert ((y >= 0) && (y < im.ny)), "{y} out of range"; assert ((v >= 0) && (v < im.mv)), "{v} out of range"; im.smp[c + nc*(x + nx*y)] = v; return; #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def get_sample(im, c, x, y) : "Obtains the sample in channel {c}, column {x}, and row {y} of {im} to {v}." assert ((c >= 0) && (c < im.nc)), "{c} out of range"; assert ((x >= 0) && (x < im.nx)), "{x} out of range"; assert ((y >= 0) && (y < im.ny)), "{y} out of range"; assert ((v >= 0) && (v < im.mv)), "{v} out of range"; return im.smp[c + nc*(x + nx*y)] #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def write(im, wr) : "Writes {im} to {wr}." fm = "P?"; if im.nc == 1 : fm = "P2"; elif im.nc == 3 : fm = "P3"; else : assert false, "invalid channel count"; wr.write("%s\n%d %d\n%d\n" % (fm, im.nx, im.ny, im.mv)); k = 0; for y in range(im.ny) : for x in range(im.nx) : if (k + c > 12) : wr.write("\n"); k = 0; for c in range(im.nc) : v = im.get_sample(c, x, y); wr.write(" %d", v); wr.write("\n"); k = 0; wr.flush(); #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #----------------------------------------------------------------------