I wrote a colorizer function which changes a grayscale image to color and I would like to put it in a shader.
The colorizer function takes a array colors (of any length) and divides those over the 256 shades.
I would like the shader to work in a similar way if possible, so that I can simply pass in any nr of colors. I’m not sure how best to pass the colors and then check the nr of colors passed, which I need for dividing them evenly.
Test code below, I want to put the colorizer functionality into a shader.
-- Colorising
-- Use this function to perform your initial setup
function setup()
cols = {color(255, 255, 255, 255), color(255, 179, 0, 255), color(255, 22, 0, 255)}
originalImg = gradient(WIDTH*.5,HEIGHT*.5)
coloredImg = colorize(originalImg, cols)
end
function colorize(img, colors)
local nImg = image(img.width, img.height)
local dStep = 255/(#colors-1)
for i=1, img.width do
for j=1, img.height do
local pix = img:get(i,j)
local cr = pix % dStep / dStep -- color mix ratio
local ci = #colors - pix // dStep -1 -- color index
local r = pix / 255 -- transparency ratio
local newc = mix(colors[ci], colors[ci+1], 1-cr)
nImg:set(i,j, color(newc.r, newc.g, newc.b, r*255))
end
end
return nImg
end
function mix(v1, v2, r)
return (1-r) * v1 + r*v2
end
function gradient(w,h)
local img = image(w,h)
setContext(img)
fill(0,0)
strokeWidth(1)
for i=0, img.width do
local r = i/img.width
stroke(255, r*255)
ellipse(img.width/2, img.height/2, (1-r)*img.width)
end
setContext()
return img
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(0, 0, 0, 255)
-- This sets the line thickness
strokeWidth(5)
-- Do your drawing here
sprite(originalImg, WIDTH/2, originalImg.height/2)
sprite(coloredImg, WIDTH/2, HEIGHT-coloredImg.height/2)
end