#! /usr/bin/python3 # Last edited on 2020-11-15 12:48:52 by jstolfi # Generates a grayscale ".pgm" image whose samples are defined by a quadratic # equation with given coefficients. import sys from math import floor def gen_quadr_samples(NX,NY,CX,CY,FXX,FXY,FYY): """Genereates and array (list of lists) of float samples with {NX} columns and {NY} rows, where sample on column {ix} and row {iy} has value {(FXX/2)*x^2 + FXY*x*y + (FYY/2)*y^2}, where {x = ix + 0.5 - CX} and {y = iy + 0.5 - CY}.""" sys.stderr.write("creating image\n") sys.stderr.write("size = %d %d\n" % (NX, NY)) sys.stderr.write("center = (%.2f %.2f)\n" % (CX, CY)) sys.stderr.write("derivatives = (%.3f %.3f %.3f)\n" % (FXX, FXY, FYY)) img = [] for iy in range(NY): y = iy + 0.5 - CY row = [] for ix in range(NX): x = ix + 0.5 - CX v = 0.5*FXX*x*x + FXY*x*y + 0.5*FYY*y*y row.append(v) img.append(row) return img def write_image(img): """Writes the array of samples {img} to standard output as a PGM file, after affnely normalizing them so that their range is {0..65535}.""" # Array dimensions: NY = len(img) NX = len(img[0]) # Find the max and min samples: vmin = +1.0e100 vmax = -1.0e100 for row in img: for v in row: vmin = min(v, vmin) vmax = max(v, vmax) sys.stderr.write("raw range = [%.6f %.6f]\n" % (vmin, vmax)) # Write the PGM header: sys.stdout.write("P2\n") sys.stdout.write("%d %d\n" % (NX, NY)) sys.stdout.write("65535\n") # Write the samples, normalized: for row in img: for v in row: vn = (v - vmin)/(vmax - vmin) ivn = int(floor(65535*vn + 0.5)) sys.stdout.write(" %d" % ivn) sys.stdout.write("\n") sys.stdout.flush() # Main program: NX = int(sys.argv[1]) NY = int(sys.argv[2]) CX = float(sys.argv[3]) CY = float(sys.argv[4]) FXX = float(sys.argv[5]) FXY = float(sys.argv[6]) FYY = float(sys.argv[7]) img = gen_quadr_samples(NX,NY,CX,CY,FXX,FXY,FYY) write_image(img)