Skip to content

Instantly share code, notes, and snippets.

@jsheedy
Created May 25, 2016 23:46
Show Gist options
  • Save jsheedy/331f033719f1e278ec835a4cc3b35616 to your computer and use it in GitHub Desktop.
Save jsheedy/331f033719f1e278ec835a4cc3b35616 to your computer and use it in GitHub Desktop.
floyd-steinberg dithering of a single channel uint8 image
def floyd_steinberg_dither(data):
result = data.astype(np.float64)
fs_matrix = np.array( (
( np.nan, np.nan, 7/16 ),
( 3/16, 5/16, 1/16),
), dtype=np.float64 );
fs_mask = np.array( (
(False, False, True),
(True, True, True),
), dtype=np.bool)
rows, cols = data.shape
for y in range(1,rows-1):
for x in range(1, cols-1):
val = result[y, x]
new_val = (val >= 127) and 255 or 0
error = val - new_val
result[y, x] = new_val
view = result[y:y+2, x-1:x+2]
new_view = view + error * fs_matrix
np.putmask(view, fs_mask, new_view)
return np.clip(result, 0, 255).astype(np.uint8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment