Skip to content

Instantly share code, notes, and snippets.

@niklasschmitz
Created August 22, 2022 16:56
Show Gist options
  • Save niklasschmitz/895b98f05fc727c1a6ec5c4a8b4c3192 to your computer and use it in GitHub Desktop.
Save niklasschmitz/895b98f05fc727c1a6ec5c4a8b4c3192 to your computer and use it in GitHub Desktop.
Dither in dex-lang feat. @adrhill
import plot
import png
key = new_key 1234
Height = Fin 100
Width = Fin 300
img_ = for i:Height. for j:Width. n_to_f ((ordinal i) + (ordinal j))
img = img_ / (n_to_f (size Height + size Width))
:html matshow img
:t img
' # Round 1: Threshold dithering
def threshold_dither {h w} (img: h=>w=>Float) : (h=>w=>Float) =
for i j. b_to_f $ img.i.j > 0.5
:html matshow $ threshold_dither img
' # Round 2: Noise dithering
def noise_dither {h w} (k:Key) (img: h=>w=>Float) : (h=>w=>Float) =
for i j. b_to_f $ img.i.j > (rand (ixkey2 k i j))
:html matshow $ noise_dither key img
' # Round 3: Ordered dithering
bayer =[[1.0, 9, 3, 11],
[ 13, 5, 15, 7],
[ 4, 12, 2, 10],
[ 16, 8, 14, 6]] / 17.0
def ordered_dither {h w mh mw} (img: h=>w=>Float) (mat: mh=>mw=>Float): (h=>w=>Float) =
for i j. b_to_f $ img.i.j > mat.(asidx (mod (ordinal i) (size mh))).(asidx (mod (ordinal j) (size mw)))
:html matshow $ ordered_dither img bayer
mat2 = [[14.0, 10, 6, 13, 19, 23, 27, 20],
[ 7, 2, 1, 9, 26, 31, 32, 24],
[ 11, 3, 4, 5, 22, 30, 29, 28],
[ 15, 8, 12, 16, 18, 25, 21, 17],
[ 19, 23, 27, 20, 14, 10, 6, 13],
[ 26, 31, 32, 24, 7, 2, 1, 9],
[ 22, 30, 29, 28, 11, 3, 4, 5],
[ 18, 25, 21, 17, 15, 8, 12, 16]] / 33.0
:html matshow $ ordered_dither img mat2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment