The simplest possible dither


I saw this exchange yesterday:

"Is there a trick for doing dithering that is so simple you can tell it to me in 500 chars and I will instantly memorize it and then never have to look it up again?"

"Add noise before quantization."

And of course I had to play with this idea. Here's a program that creates a simple greyscale image and quantizes it to 4 levels of greyscale -- after adding varying levels of noise.

N = 100  -- image size
img = {}
for y=1,N do
  local row = {}
  for x=1,N do
    table.insert(row, x/N)
  end
  table.insert(img, row)
end
function add_noise_then_quantize(img, f, q)
  local result = {}
  for y=1,#img do
    local row = {}
    for x=1,#img[y] do
      local c = img[y][x] + love.math.noise(x,y)*f  -- add noise
      table.insert(row, floor(c*q)/q)  -- quantize
    end
    table.insert(result, row)
  end
  return result
end
dithered_img = {}
for i=0,10 do
  dithered_img[i] = add_noise_then_quantize(img, i/10, 4)
end
function car.draw()
  draw_image(img, 700, 100)
  for i=0,10 do
    draw_image(dithered_img[i], 700+(10-i)*110, 300)
  end end
function draw_image(img, x0,y0)
  for y=1,#img do
    for x=1,#img[y] do
      local c = img[y][x]
      color(c,c,c)
      pt(x0+x, y0+y)
    end end end

Get Lua Carousel

Leave a comment

Log in with itch.io to leave a comment.