import sys import os def read_ppm(filename): with open(filename, "rb") as f: header = f.readline() if header != b"P6\n": raise ValueError(f"Not a P6 PPM file: {filename}") while True: line = f.readline() if not line.startswith(b"#"): break dims = line.split() width, height = int(dims[0]), int(dims[1]) line = f.readline() maxval = int(line.strip()) data = f.read() return width, height, data def compare_ppm(file1, file2, threshold): w1, h1, d1 = read_ppm(file1) w2, h2, d2 = read_ppm(file2) if w1 != w2 or h1 != h2: print(f"ERROR: Size mismatch - {file1}: {w1}x{h1}, {file2}: {w2}x{h2}") return False total_pixels = w1 * h1 diff_count = 0 for i in range(len(d1)): diff = abs(d1[i] - d2[i]) if diff > threshold: diff_count += 1 diff_percent = (diff_count / (total_pixels * 3)) * 100 print(f"Image 1: {file1} ({w1}x{h1})") print(f"Image 2: {file2} ({w2}x{h2})") print(f"Threshold: {threshold}") print(f"Different pixels: {diff_count} / {total_pixels * 3} ({diff_percent:.2f}%)") if diff_percent <= 1.0: print("PASS: Images match!") return True else: print("FAIL: Images differ!") return False if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: python compare_ppm.py ") sys.exit(1) file1 = sys.argv[1] file2 = sys.argv[2] threshold = int(sys.argv[3]) if not os.path.exists(file1): print(f"ERROR: File not found: {file1}") sys.exit(1) if not os.path.exists(file2): print(f"ERROR: File not found: {file2}") sys.exit(1) result = compare_ppm(file1, file2, threshold) sys.exit(0 if result else 1)