"""Generate bit-plane-slicing-demo.png in cwd; Python 3.14, NumPy 2.3, Matplotlib 3.10.""" import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt r, c = np.indices((8, 8)) p = ((2*c + (r % 2)) % 16).astype(np.uint8) b3 = (p >> 3) & 1 b0 = p & 1 truncated = (p >> 2) << 2 assert np.array_equal(sum(((p >> k) & 1).astype(int) * (1 << k) for k in range(4)), p) assert np.all((p.astype(int)-truncated.astype(int) >= 0) & (p.astype(int)-truncated.astype(int) <= 3)) fig, axes = plt.subplots(1, 4, figsize=(8.4, 2.65), dpi=100, facecolor='white') for ax, data, title, top in zip(axes, [p, b3, b0, truncated], ['4-bit samples p', 'Plane 3: values 0 or 1', 'Plane 0: values 0 or 1', 'Keep planes 3 and 2'], [15, 1, 1, 15]): ax.imshow(data, cmap='gray', vmin=0, vmax=top, interpolation='nearest') ax.set_title(title, fontsize=9) ax.set_xticks([]) ax.set_yticks([]) for row in range(8): for col in range(8): value = int(data[row, col]) ax.text(col, row, str(value), ha='center', va='center', fontsize=7, color='white' if value < top/2 else 'black') fig.text(0.5, 0.07, 'Binary planes use their own black/white scale; reconstruction uses significance weights.', ha='center', fontsize=9) fig.subplots_adjust(left=.02, right=.98, bottom=.16, top=.86, wspace=.16) fig.savefig('bit-plane-slicing-demo.png', facecolor='white') plt.close(fig)