This hole is experimental, no solutions will be saved. Please leave feedback on the GitHub issue.

Floyd-Steinberg Dithering

Details

Given a 64x64 grayscale image in plain PGM format, convert it to a palette of black (0) and white (255) using the Floyd-Steinberg algorithm. Print the result, using "#" for black and spaces for white.

The input is 3 lines of header information, followed by 4096 pixel values, each on their own line.

    P2          # magic number
    64 64       # image dimensions
    255         # maximum pixel value
    19          # (0,0) value
    18          # (1,0) value
    ...
Pixels are processed one at a time, left-to-right then top-to-bottom. For each pixel:
  • Let a be the pixel value.
  • Let b be the nearest palette value to a (either 0 or 255).
  • Set the current pixel to b. Now a "debt" of a-b needs to be spread to 4 of the neighboring pixels. For each of these 4 neighbors and its corresponding fraction f (as seen below), add floor((a-b)*f) to its value.
     --   --   --
     --   []  7/16
    3/16 5/16 1/16
Notes:
  • Some pixel values may temporarily become less than 0 or greater than 255.
  • When processing pixels on the edge, any adjustments made to pixels outside of the image should be ignored.
0 bytes, 0 chars
Restore solution
All
Compiled from AT&T syntax to x86-64 Linux. Use syscalls to write output.
Fennel is an experimental language, no solutions will be saved. Please leave feedback on the GitHub issue.
Uiua is an experimental language, no solutions will be saved. Please leave feedback on the GitHub issue.
ctrl + enter or

Delete Solution

Are you sure you want to delete your solution(s) for Floyd-Steinberg Dithering?

If you have separate bytes and chars solutions then both will be deleted.

This is irreversible, please backup any code you care about.

Type I understand and press confirm to continue.