Bitmap/Flood fill: Difference between revisions

→‎{{header|Lua}}: added Lua solution
(→‎{{header|Lua}}: added Lua solution)
Line 1,767:
Lingo has built-in flood fill for image objects, so a custom implementation would be pointless:
<lang lingo>img.floodFill(x, y, rgb(r,g,b))</lang>
 
 
=={{header|Lua}}==
Uses Bitmap class [[Bitmap#Lua|here]], with an RGB tuple pixel representation, then extending..
 
Preprocess with ImageMagick to simplify loading:
<lang lua>$ magick unfilledcirc.png -depth 8 unfilledcirc.ppm</lang>
Some rudimentary PPM support:
<lang lua>function Bitmap:loadPPM(filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
end
 
function Bitmap:savePPM(filename)
local fp = io.open( filename, "wb" )
if fp == nil then return false end
fp:write(string.format("P6\n%d %d\n%d\n", self.width, self.height, 255))
for y = 1, self.height do
for x = 1, self.width do
local pix = self.pixels[y][x]
fp:write(string.char(pix[1]), string.char(pix[2]), string.char(pix[3]))
end
end
fp:close()
end</lang>
The task itself:
<lang lua>function Bitmap:floodfill(x, y, c)
local b = self:get(x, y)
if not b then return end
local function matches(a)
if not a then return false end
-- this is where a "tolerance" could be implemented:
return a[1]==b[1] and a[2]==b[2] and a[3]==b[3]
end
local function ff(x, y)
if not matches(self:get(x, y)) then return end
self:set(x, y, c)
ff(x+1, y)
ff(x, y-1)
ff(x-1, y)
ff(x, y+1)
end
ff(x, y)
end</lang>
Demo:
<lang lua>bitmap = Bitmap(0, 0)
bitmap:loadPPM("unfilledcirc.ppm")
bitmap:floodfill( 1, 1, { 255,0,0 }) -- fill exterior (except bottom right) with red
bitmap:floodfill( 50, 50, { 0,255,0 })-- fill larger circle with green
bitmap:floodfill( 100, 100, { 0,0,255 })-- fill smaller circle with blue
bitmap:savePPM("filledcirc.ppm")</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Anonymous user