90 likes | 219 Vues
CPSC 231 Tutorial. Xin Liu April 1, 2013. Just announced Due: 4pm Friday, 12 April. Assignment 4. Black and White bitmap image Plain text file (ASCII) First line: P1 Comments starting with # Width height Data (1 for white, 0 for black, separated by space or Carriage Return)
E N D
CPSC 231 Tutorial Xin Liu April 1, 2013
Just announced • Due: 4pm Friday, 12 April Assignment 4
Black and White bitmap image • Plain text file (ASCII) • First line: P1 • Comments starting with # • Width height • Data (1 for white, 0 for black, separated by space or Carriage Return) • See the four files for As4 for examples PBM file - type p1
Create a program inv-img.py to • Read a pbm image • Invert the bits (1-> 0; 0 -> 1) • Write out the inverted image Exercise
defreadimage(filename): infile = open(filename, 'r') img = [] width = 0 height = 0 # read the image header while True: line = infile.readline() if line == 'P1\n': continue; if line[0] == '#': continue; fields = line.split() width = int(fields[0]) height = int(fields[1]) break
# read the image data row = 0 fields = [] i = 0 while row < height: col = 0 listrow = [] while col < width: if i == len(fields): line = infile.readline() fields = line.split() i = 0 listrow.append(int(fields[i])) col = col + 1 i = i + 1 img.append(listrow) row = row + 1 infile.close() return img
definvert(img): invimg = [] width = len(img[0]) height = len(img) for row in range(0, height): listrow = [] for col in range(0, width): listrow.append(1 - img[row][col]) invimg.append(listrow) return invimg
defwriteimage(filename, img): outfile = open(filename, 'w') outfile.write('P1\n') outfile.write('# inversed image\n') width = len(img[0]) height = len(img) outfile.write(str(width) + ' ' + str(height) + '\n') for row in range(0, height): line = '' for col in range(0, width): line = line + str(img[row][col]) + ' ' outfile.write(line + '\n') outfile.close()
# main program import sys if len(sys.argv) != 3: print('usage: python3', sys.argv[0], 'infileoutfile') exit() infilename = sys.argv[1] outfilename = sys.argv[2] inimg = readimage(infilename) outimg = invert(inimg) writeimage(outfilename, outimg)