# Last edited on 2025-08-18 22:09:57 by stolfi def write_image_via_PNM(rfile, R): # Expects {R} to be an RGB image with values in {[0_1]}. # Writes it out to file "{rfile}". # # The image should be a {numpy} array with shape {(ny,nx,nc)} # where {nc} is either 1 or 3. # ny, nx, nc = numpy.shape(R) assert nc == 1 or nc == 3, "bug {nc}" ext = "pgm" if nc == 1 else "ppm" # File name extension. magic = "P2" if nc == 1 else "P3" # Magic code for PGM or PPM file. inSpace = "linearGray" if nc == 1 else "linearRGB" outSpace = "Gray" if nc == 1 else "sRGB" tfile = f"/tmp/{os.getpid()}-R.{ext}" # Write an ascii PGM or PPM: maxval = 1023 with open(tfile, "w") as wr: wr.write(f"{magic}\n") wr.write(f"{nx} {ny}\n") wr.write(f"{maxval}\n") for iy in range(ny): for ix in range(nx): if ix % 20 == 0: wr.write("\n") for ic in range(nc): fsmp = R[iy,ix,ic] ival = int(floor(maxval*fsmp + 0.5)) if ival < 0 or ival > maxval: prog_error("int sample out of bounds") wr.write(f" {ival}") wr.write("\n") wr.close() # Convert to PNG: bash\ ( f"convert {tfile}" + \ f" -set colorspace {inSpace}" + \ f" -depth 8" + \ f" -colorspace {outSpace}" + f" {rfile}" ) return # ----------------------------------------------------------------------