Do not assume 255 bit depth. Generalize black/white inversion and rescaling to gamut.