-- random neighbor
-- MEDIUM!
-- take random pixel value from current pixel neighbour and replace current pixel 
-- with random pixel if difference of original and random luminance is less then tolerance
-- author: Siniša Petrić http://www.sigmapi-design.com, 2008-2014

seed_window = 20
seed_retries = 3

lum_tol = 40/255.0

-- create images/process objects
imgA = TLuaImageWrap(inputImage)
imgB = TLuaImageWrap(outputImage)
proC = TLuaProcessWrap(procObj)


-- get random pixel from neighborhood and check the luminance 

function get_random_rgb(x, y, window, retries)
   local rand_x, rand_y, r, g, b, lum1, lum2
   b, g, r = imgA:GetImageBGR(x, y)    
   for k = 0, retries do
      rand_x =  x + math.floor((math.random(window + 1) - 1) - window/2) 
      rand_y =  y + math.floor((math.random(window + 1) - 1) - window/2)        
      lum1 = imgA:GetImageLuminance(rand_x, rand_y)      
      lum2 = imgA:GetImageLuminance(x, y)      
      if math.abs(lum1 - lum2) < lum_tol then
         b, g, r = imgA:GetImageBGR(rand_x, rand_y)    
         break
      end   
   end
   return r, g, b
end

-- main routine

math.randomseed( os.time() )
eos = false
x = 0            
y = 0
iWidth, iHeight = imgA:GetImageSize()
total = iHeight   
done = 0   
while (not eos) do
   r,g,b = get_random_rgb(x,y, seed_window, seed_retries)   
   imgB:SetScanBGR(b, g, r)
   eos, x, y = imgB:ScanNext()
   if (y > done) then
      proC:ShowProgress(y, total)
      done = y
   end
end 



