Bitmap/Flood fill: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Raster graphics operations}}[[Category:Graphics algorithms]]
[[Category:Graphics algorithms]]
Implement a [[wp:flood fill|flood fill]].
{{task|Raster graphics operations}}Implement a [[wp:flood fill|flood fill]].


A flood fill is a way of filling an area using ''color banks'' to define the contained area or a ''target color'' which "determines" the area (the ''valley'' that can be flooded; Wikipedia uses the term ''target color''). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
A flood fill is a way of filling an area using ''color banks'' to define the contained area or a ''target color'' which "determines" the area (the ''valley'' that can be flooded; Wikipedia uses the term ''target color''). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the "connected valleys") get filled.
Line 8: Line 8:
[[Image:Unfilledcirc.png|128px|thumb|right]]
[[Image:Unfilledcirc.png|128px|thumb|right]]
'''Testing''': the basic algorithm is not suitable for ''truecolor'' images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.
'''Testing''': the basic algorithm is not suitable for ''truecolor'' images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle.

=={{header|Action!}}==
=={{header|Action!}}==
In the following solution a simple implementation of queue has been used.
In the following solution a simple implementation of queue has been used.
{{libheader|Action! Bitmap tools}}
{{libheader|Action! Bitmap tools}}
<syntaxhighlight lang=Action!>INCLUDE "H6:RGBCIRCL.ACT" ;from task Midpoint circle algorithm
<syntaxhighlight lang="action!">INCLUDE "H6:RGBCIRCL.ACT" ;from task Midpoint circle algorithm


RGB black,white,yellow,blue
RGB black,white,yellow,blue
Line 185: Line 184:
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Flood_fill.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Flood_fill.png Screenshot from Atari 8-bit computer]

=={{header|Ada}}==
=={{header|Ada}}==
<syntaxhighlight lang=ada>procedure Flood_Fill
<syntaxhighlight lang="ada">procedure Flood_Fill
( Picture : in out Image;
( Picture : in out Image;
From : Point;
From : Point;
Line 294: Line 292:
end Flood_Fill;</syntaxhighlight>
end Flood_Fill;</syntaxhighlight>
The procedure has the following parameters. ''Picture'' is the image to change. ''From'' is the point to start at. ''Fill'' is the color to fill with. ''Replace'' is the color to replace. ''Distance'' defines the range of color around ''Replace'' to replace as well. The distance is defined as a maximum of the differences of stimuli. The following code snippet reads the test file, fills the area between two circles red, and writes the result:
The procedure has the following parameters. ''Picture'' is the image to change. ''From'' is the point to start at. ''Fill'' is the color to fill with. ''Replace'' is the color to replace. ''Distance'' defines the range of color around ''Replace'' to replace as well. The distance is defined as a maximum of the differences of stimuli. The following code snippet reads the test file, fills the area between two circles red, and writes the result:
<syntaxhighlight lang=ada>declare
<syntaxhighlight lang="ada">declare
File : File_Type;
File : File_Type;
begin
begin
Line 314: Line 312:
end;</syntaxhighlight>
end;</syntaxhighlight>
=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang=gwbasic> 100 GR:GOSUB 330"DRAW THE DEATH STAR"
<syntaxhighlight lang="gwbasic"> 100 GR:GOSUB 330"DRAW THE DEATH STAR"
110 COLOR= 12
110 COLOR= 12
120 X = 20:Y = 30: GOSUB 140"FLOOD FILL"
120 X = 20:Y = 30: GOSUB 140"FLOOD FILL"
Line 351: Line 349:
=== Recursive ===
=== Recursive ===
This is limited to %StackSize% pixels.
This is limited to %StackSize% pixels.
<syntaxhighlight lang=AutoHotkey>SetBatchLines, -1
<syntaxhighlight lang="autohotkey">SetBatchLines, -1
CoordMode, Mouse
CoordMode, Mouse
CoordMode, Pixel
CoordMode, Pixel
Line 394: Line 392:


=== Iterative ===
=== Iterative ===
<syntaxhighlight lang=AutoHotkey>#NoEnv
<syntaxhighlight lang="autohotkey">#NoEnv
#SingleInstance, Force
#SingleInstance, Force


Line 449: Line 447:
DllCall("DeleteObject", UInt, hBrush)
DllCall("DeleteObject", UInt, hBrush)
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
BBC BASIC has a built-in flood fill statement, but to satisfy the terms of the task it is not used in this example.
BBC BASIC has a built-in flood fill statement, but to satisfy the terms of the task it is not used in this example.
<syntaxhighlight lang=bbcbasic> MODE 8
<syntaxhighlight lang="bbcbasic"> MODE 8
GCOL 15
GCOL 15
CIRCLE FILL 640, 512, 500
CIRCLE FILL 640, 512, 500
Line 476: Line 473:
NEXT
NEXT
ENDPROC</syntaxhighlight>
ENDPROC</syntaxhighlight>

=={{header|C}}==
=={{header|C}}==
===Simple and complete example in C89===
===Simple and complete example in C89===
<syntaxhighlight lang=C>/*
<syntaxhighlight lang="c">/*
* RosettaCode: Bitmap/Flood fill, language C, dialects C89, C99, C11.
* RosettaCode: Bitmap/Flood fill, language C, dialects C89, C99, C11.
*
*
Line 588: Line 584:


===Second example ===
===Second example ===
<syntaxhighlight lang=c>
<syntaxhighlight lang="c">
// http://commons.wikimedia.org/wiki/File:Julia_immediate_basin_1_3.png
// http://commons.wikimedia.org/wiki/File:Julia_immediate_basin_1_3.png


Line 703: Line 699:
The <code>sys/queue.h</code> is not POSIX. (See [[FIFO#C|FIFO]])
The <code>sys/queue.h</code> is not POSIX. (See [[FIFO#C|FIFO]])


<syntaxhighlight lang=c>/* #include <sys/queue.h> */
<syntaxhighlight lang="c">/* #include <sys/queue.h> */
typedef struct {
typedef struct {
color_component red, green, blue;
color_component red, green, blue;
Line 713: Line 709:
rgb_color_p rcolor);</syntaxhighlight>
rgb_color_p rcolor);</syntaxhighlight>


<syntaxhighlight lang=c>#include "imglib.h"
<syntaxhighlight lang="c">#include "imglib.h"


typedef struct _ffill_node {
typedef struct _ffill_node {
Line 813: Line 809:
(Comments show changes to fill the white area instead of the black circle)
(Comments show changes to fill the white area instead of the black circle)


<syntaxhighlight lang=c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include "imglib.h"
#include "imglib.h"
Line 840: Line 836:
return 0;
return 0;
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{works with|C#|3.0}}
{{works with|C#|3.0}}
Line 847: Line 842:
This implementation matches exact colours only. Since the example image has grey pixels around the edges of the circles, these will remain grey after the interiors are filled.
This implementation matches exact colours only. Since the example image has grey pixels around the edges of the circles, these will remain grey after the interiors are filled.


<syntaxhighlight lang=csharp>
<syntaxhighlight lang="csharp">
using System;
using System;
using System.Collections.Generic;
using System.Collections.Generic;
Line 902: Line 897:
}
}
</syntaxhighlight>
</syntaxhighlight>

=={{header|C++}}==
=={{header|C++}}==
{{libheader|OpenCV}}
{{libheader|OpenCV}}
Line 909: Line 903:


'''Interface'''
'''Interface'''
<syntaxhighlight lang=cpp>#ifndef PROCESSING_FLOODFILLALGORITHM_H_
<syntaxhighlight lang="cpp">#ifndef PROCESSING_FLOODFILLALGORITHM_H_
#define PROCESSING_FLOODFILLALGORITHM_H_
#define PROCESSING_FLOODFILLALGORITHM_H_


Line 938: Line 932:
</syntaxhighlight>
</syntaxhighlight>
'''Implementation'''
'''Implementation'''
<syntaxhighlight lang=cpp>#include "FloodFillAlgorithm.h"
<syntaxhighlight lang="cpp">#include "FloodFillAlgorithm.h"


FloodFillAlgorithm::~FloodFillAlgorithm() {
FloodFillAlgorithm::~FloodFillAlgorithm() {
Line 983: Line 977:


</syntaxhighlight>
</syntaxhighlight>

=={{header|D}}==
=={{header|D}}==
This version uses the bitmap module from the Bitmap Task, matches exact colours only, and is derived from the Go version (to avoid stack overflow because unlike Go the D stack is not segmented).
This version uses the bitmap module from the Bitmap Task, matches exact colours only, and is derived from the Go version (to avoid stack overflow because unlike Go the D stack is not segmented).


<syntaxhighlight lang=d>import std.array, bitmap;
<syntaxhighlight lang="d">import std.array, bitmap;


void floodFill(Color)(Image!Color img, in uint x, in uint y,
void floodFill(Color)(Image!Color img, in uint x, in uint y,
Line 1,022: Line 1,015:
Using the image type from [[Basic bitmap storage#E]].
Using the image type from [[Basic bitmap storage#E]].


<syntaxhighlight lang=e>def floodFill(image, x, y, newColor) {
<syntaxhighlight lang="e">def floodFill(image, x, y, newColor) {
def matchColor := image[x, y]
def matchColor := image[x, y]
def w := image.width()
def w := image.width()
Line 1,094: Line 1,087:
[[File:Filledcirc-E.png|128px|thumb|right|Filled sample image]]Note that this does not make any attempt to smoothly fill 'banks' or have a tolerance; it matches exact colors only. This will fill the example image with red inside green, and there will be black/white fringes:
[[File:Filledcirc-E.png|128px|thumb|right|Filled sample image]]Note that this does not make any attempt to smoothly fill 'banks' or have a tolerance; it matches exact colors only. This will fill the example image with red inside green, and there will be black/white fringes:


<syntaxhighlight lang=e>{
<syntaxhighlight lang="e">{
println("Read")
println("Read")
def i := readPPM(<import:java.io.makeFileInputStream>(<file:Unfilledcirc.ppm>))
def i := readPPM(<import:java.io.makeFileInputStream>(<file:Unfilledcirc.ppm>))
Line 1,105: Line 1,098:
println("Done")
println("Done")
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|ERRE}}==
=={{header|ERRE}}==
In "PC.LIB" library there is a FILL procedure that do the job, but the example program implements the algorithm in ERRE language using an iterative method. This program is taken from the distribution disk and works in 320x200 graphics.
In "PC.LIB" library there is a FILL procedure that do the job, but the example program implements the algorithm in ERRE language using an iterative method. This program is taken from the distribution disk and works in 320x200 graphics.
<syntaxhighlight lang=ERRE>
<syntaxhighlight lang="erre">
PROGRAM MYFILL_DEMO
PROGRAM MYFILL_DEMO


Line 1,198: Line 1,190:
</syntaxhighlight>
</syntaxhighlight>
Note: I haven't an "Upload files" item, so I can't show the resulting image!
Note: I haven't an "Upload files" item, so I can't show the resulting image!

=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


Using an emulated stack. EMT's recursive stack space is limited. For the notebook with images see [http://www.euler-math-toolbox.de/renegrothmann/Flood%20Fill.html this page].
Using an emulated stack. EMT's recursive stack space is limited. For the notebook with images see [http://www.euler-math-toolbox.de/renegrothmann/Flood%20Fill.html this page].


<syntaxhighlight lang=text>
<syntaxhighlight lang="text">
>file="test.png";
>file="test.png";
>A=loadrgb(file); ...
>A=loadrgb(file); ...
Line 1,241: Line 1,232:
>insrgb(B);
>insrgb(B);
</syntaxhighlight>
</syntaxhighlight>

=={{header|FBSL}}==
=={{header|FBSL}}==
'''Using pure FBSL's built-in graphics functions:'''
'''Using pure FBSL's built-in graphics functions:'''
<syntaxhighlight lang=qbasic>#DEFINE WM_LBUTTONDOWN 513
<syntaxhighlight lang="qbasic">#DEFINE WM_LBUTTONDOWN 513
#DEFINE WM_CLOSE 16
#DEFINE WM_CLOSE 16


Line 1,282: Line 1,272:
END SUB</syntaxhighlight>
END SUB</syntaxhighlight>
'''Output:''' [[File:FBSLFlood.PNG]]
'''Output:''' [[File:FBSLFlood.PNG]]

=={{header|Forth}}==
=={{header|Forth}}==
This simple recursive algorithm uses routines from [[Basic bitmap storage]].
This simple recursive algorithm uses routines from [[Basic bitmap storage]].
<syntaxhighlight lang=forth>: third 2 pick ;
<syntaxhighlight lang="forth">: third 2 pick ;
: 3dup third third third ;
: 3dup third third third ;
: 4dup 2over 2over ;
: 4dup 2over 2over ;
Line 1,313: Line 1,302:
then
then
r> drop ;</syntaxhighlight>
r> drop ;</syntaxhighlight>

=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
Line 1,319: Line 1,307:
Here the ''target color'' paradigm is used. Again the <code>matchdistance</code> parameter can be tuned to ignore small differences that could come because of antialiasing.
Here the ''target color'' paradigm is used. Again the <code>matchdistance</code> parameter can be tuned to ignore small differences that could come because of antialiasing.


<syntaxhighlight lang=fortran>module RCImageArea
<syntaxhighlight lang="fortran">module RCImageArea
use RCImageBasic
use RCImageBasic
use RCImagePrimitive
use RCImagePrimitive
Line 1,428: Line 1,416:
Usage example excerpt (which on the test image will fill with green the inner black circle):
Usage example excerpt (which on the test image will fill with green the inner black circle):


<syntaxhighlight lang=fortran> call floodfill(animage, point(100,100), rgb(0,0,0), rgb(0,255,0))</syntaxhighlight>
<syntaxhighlight lang="fortran"> call floodfill(animage, point(100,100), rgb(0,0,0), rgb(0,255,0))</syntaxhighlight>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<syntaxhighlight lang=freebasic>' version 04-11-2016
<syntaxhighlight lang="freebasic">' version 04-11-2016
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,487: Line 1,474:
If InKey <> "" OrElse InKey = Chr(255) + "k" Then End
If InKey <> "" OrElse InKey = Chr(255) + "k" Then End
Loop</syntaxhighlight>
Loop</syntaxhighlight>

=={{header|Go}}==
=={{header|Go}}==
An addition to code from the bitmap task:
An addition to code from the bitmap task:
<syntaxhighlight lang=go>package raster
<syntaxhighlight lang="go">package raster


func (b *Bitmap) Flood(x, y int, repl Pixel) {
func (b *Bitmap) Flood(x, y int, repl Pixel) {
Line 1,509: Line 1,495:
And a test program. Works with code from read ppm and write ppm to pipe tasks. For input, it uses a version of the test file converted by the Go solution to "Read an image through a pipe". For output it uses the trick from "PPM conversion through a pipe" to write the .png suitable for uploading to RC.
And a test program. Works with code from read ppm and write ppm to pipe tasks. For input, it uses a version of the test file converted by the Go solution to "Read an image through a pipe". For output it uses the trick from "PPM conversion through a pipe" to write the .png suitable for uploading to RC.
[[File:Go_flood.png|right]]
[[File:Go_flood.png|right]]
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,538: Line 1,524:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Haskell}}==
=={{header|Haskell}}==
This code uses the Bitmap and Bitmap.RGB modules defined [[Bitmap#Haskell|here]].
This code uses the Bitmap and Bitmap.RGB modules defined [[Bitmap#Haskell|here]].
<syntaxhighlight lang=Haskell>import Data.Array.ST
<syntaxhighlight lang="haskell">import Data.Array.ST
import Data.STRef
import Data.STRef
import Control.Monad
import Control.Monad
Line 1,652: Line 1,637:
scanWhileX b st p oldC newC (w, h) (Pixel (x, y + 1))
scanWhileX b st p oldC newC (w, h) (Pixel (x, y + 1))
</syntaxhighlight>
</syntaxhighlight>

=={{header|HicEst}}==
=={{header|HicEst}}==
HicEst color fill is via the [http://www.HicEst.com/DeCoRation.htm decoration option of WRITE()]
HicEst color fill is via the [http://www.HicEst.com/DeCoRation.htm decoration option of WRITE()]
<syntaxhighlight lang=HicEst>WINDOW(WINdowhandle=wh, BaCkcolor=0, TItle="Rosetta test image")
<syntaxhighlight lang="hicest">WINDOW(WINdowhandle=wh, BaCkcolor=0, TItle="Rosetta test image")


WRITE(WIN=wh, DeCoRation="EL=14, BC=14") ! color 14 == bright yellow
WRITE(WIN=wh, DeCoRation="EL=14, BC=14") ! color 14 == bright yellow
Line 1,663: Line 1,647:


WINDOW(Kill=wh)</syntaxhighlight>
WINDOW(Kill=wh)</syntaxhighlight>

=={{header|J}}==
=={{header|J}}==
'''Solution:'''<br>
'''Solution:'''<br>
Uses <code>getPixels</code> and <code>setPixels</code> from [[Basic bitmap storage#J|Basic bitmap storage]].
Uses <code>getPixels</code> and <code>setPixels</code> from [[Basic bitmap storage#J|Basic bitmap storage]].
<syntaxhighlight lang=j>NB. finds and labels contiguous areas with the same numbers
<syntaxhighlight lang="j">NB. finds and labels contiguous areas with the same numbers
NB. ref: http://www.jsoftware.com/pipermail/general/2005-August/023886.html
NB. ref: http://www.jsoftware.com/pipermail/general/2005-August/023886.html
findcontig=: (|."1@|:@:>. (* * 1&(|.!.0)))^:4^:_@(* >:@i.@$)
findcontig=: (|."1@|:@:>. (* * 1&(|.!.0)))^:4^:_@(* >:@i.@$)
Line 1,681: Line 1,664:
The following draws the same image as for the [[Flood fill#Tcl|Tcl example image]] below.<br>
The following draws the same image as for the [[Flood fill#Tcl|Tcl example image]] below.<br>
Uses definitions from [[Basic bitmap storage#J|Basic bitmap storage]], [[Bresenham's line algorithm#J|Bresenham's line algorithm]] and [[Midpoint circle algorithm#J|Midpoint circle algorithm]].
Uses definitions from [[Basic bitmap storage#J|Basic bitmap storage]], [[Bresenham's line algorithm#J|Bresenham's line algorithm]] and [[Midpoint circle algorithm#J|Midpoint circle algorithm]].
<syntaxhighlight lang=j>'white blue yellow black orange red'=: 255 255 255,0 0 255,255 255 0,0 0 0,255 165 0,:255 0 0
<syntaxhighlight lang="j">'white blue yellow black orange red'=: 255 255 255,0 0 255,255 255 0,0 0 0,255 165 0,:255 0 0
myimg=: white makeRGB 50 70
myimg=: white makeRGB 50 70
lines=: _2]\^:2 ] 0 0 25 0 , 25 0 25 35 , 25 35 0 35 , 0 35 0 0
lines=: _2]\^:2 ] 0 0 25 0 , 25 0 25 35 , 25 35 0 35 , 0 35 0 0
Line 1,693: Line 1,676:
'''Alternative findcontig:'''<br>
'''Alternative findcontig:'''<br>
The following alternative version of <code>findcontig</code> is less concise but is leaner, faster, works for n-dimensions and is not restricted to numerical arrays.
The following alternative version of <code>findcontig</code> is less concise but is leaner, faster, works for n-dimensions and is not restricted to numerical arrays.
<syntaxhighlight lang=j>NB. ref: http://www.jsoftware.com/pipermail/general/2005-August/024174.html
<syntaxhighlight lang="j">NB. ref: http://www.jsoftware.com/pipermail/general/2005-August/024174.html
eq=:[:}:"1 [:($$[:([:+/\1:,}:~:}.),) ,&_"1 NB. equal numbers for atoms of y connected in first direction
eq=:[:}:"1 [:($$[:([:+/\1:,}:~:}.),) ,&_"1 NB. equal numbers for atoms of y connected in first direction
eq_nd=: i.@#@$(<"0@[([:, |:^:_1"0 _)&> [:EQ&.> <@|:"0 _)] NB. n-dimensional eq, gives an #@$,*/@$ shaped matrix
eq_nd=: i.@#@$(<"0@[([:, |:^:_1"0 _)&> [:EQ&.> <@|:"0 _)] NB. n-dimensional eq, gives an #@$,*/@$ shaped matrix
Line 1,700: Line 1,683:


findcontig_nd=: 3 : '($y)${. ([:({.,~}:) ([ repl cnnct)/\.)^:([:+./@(~:/)2&{.)^:_ (,{.) eq_nd (i.~ ~.@,) y'</syntaxhighlight>
findcontig_nd=: 3 : '($y)${. ([:({.,~}:) ([ repl cnnct)/\.)^:([:+./@(~:/)2&{.)^:_ (,{.) eq_nd (i.~ ~.@,) y'</syntaxhighlight>

=={{header|Java}}==
=={{header|Java}}==
Input is the image, the starting node (x, y), the target color we want to fill, and the replacement color that will replace the target color. It implements a 4-way flood fill algorithm. For large images, the performance can be improved by drawing the scanlines instead of setting each pixel to the replacement color, or by working directly on the databuffer.
Input is the image, the starting node (x, y), the target color we want to fill, and the replacement color that will replace the target color. It implements a 4-way flood fill algorithm. For large images, the performance can be improved by drawing the scanlines instead of setting each pixel to the replacement color, or by working directly on the databuffer.
<syntaxhighlight lang=java>import java.awt.Color;
<syntaxhighlight lang="java">import java.awt.Color;
import java.awt.Point;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImage;
Line 1,746: Line 1,728:
}</syntaxhighlight>
}</syntaxhighlight>
And here is an example of how to replace the white color with red from the sample image (with starting node (50, 50)):
And here is an example of how to replace the white color with red from the sample image (with starting node (50, 50)):
<syntaxhighlight lang=java>import java.io.IOException;
<syntaxhighlight lang="java">import java.io.IOException;
import java.awt.Color;
import java.awt.Color;
import java.awt.Point;
import java.awt.Point;
Line 1,764: Line 1,746:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Julia}}==
=={{header|Julia}}==
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
Inspired to [[#Python | Python]] version.
Inspired to [[#Python | Python]] version.


<syntaxhighlight lang=julia>using Images, FileIO
<syntaxhighlight lang="julia">using Images, FileIO


function floodfill!(img::Matrix{<:Color}, initnode::CartesianIndex{2}, target::Color, replace::Color)
function floodfill!(img::Matrix{<:Color}, initnode::CartesianIndex{2}, target::Color, replace::Color)
Line 1,815: Line 1,796:
floodfill!(img, CartesianIndex(100, 100), Gray(false), Gray(true))
floodfill!(img, CartesianIndex(100, 100), Gray(false), Gray(true))
save("data/filledcircle.png", img)</syntaxhighlight>
save("data/filledcircle.png", img)</syntaxhighlight>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=scala>// version 1.1.4-3
<syntaxhighlight lang="scala">// version 1.1.4-3


import java.awt.Color
import java.awt.Color
Line 1,878: Line 1,858:
JOptionPane.showMessageDialog(null, JLabel(ImageIcon(image)), title, JOptionPane.PLAIN_MESSAGE)
JOptionPane.showMessageDialog(null, JLabel(ImageIcon(image)), title, JOptionPane.PLAIN_MESSAGE)
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang=lb>'This example requires the Windows API
<syntaxhighlight lang="lb">'This example requires the Windows API
NoMainWin
NoMainWin
WindowWidth = 267.5
WindowWidth = 267.5
Line 1,969: Line 1,948:
End If
End If
End Function</syntaxhighlight>
End Function</syntaxhighlight>

=={{header|Lingo}}==
=={{header|Lingo}}==
Lingo has built-in flood fill for image objects, so a custom implementation would be pointless:
Lingo has built-in flood fill for image objects, so a custom implementation would be pointless:
<syntaxhighlight lang=lingo>img.floodFill(x, y, rgb(r,g,b))</syntaxhighlight>
<syntaxhighlight lang="lingo">img.floodFill(x, y, rgb(r,g,b))</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Uses Bitmap class [[Bitmap#Lua|here]], with an RGB tuple pixel representation, then extending..
Uses Bitmap class [[Bitmap#Lua|here]], with an RGB tuple pixel representation, then extending..


Preprocess with ImageMagick to simplify loading:
Preprocess with ImageMagick to simplify loading:
<syntaxhighlight lang=lua>$ magick unfilledcirc.png -depth 8 unfilledcirc.ppm</syntaxhighlight>
<syntaxhighlight lang="lua">$ magick unfilledcirc.png -depth 8 unfilledcirc.ppm</syntaxhighlight>
Some rudimentary PPM support:
Some rudimentary PPM support:
<syntaxhighlight lang=lua>function Bitmap:loadPPM(filename)
<syntaxhighlight lang="lua">function Bitmap:loadPPM(filename)
local fp = io.open( filename, "rb" )
local fp = io.open( filename, "rb" )
if fp == nil then return false end
if fp == nil then return false end
Line 2,008: Line 1,984:
end</syntaxhighlight>
end</syntaxhighlight>
The task itself:
The task itself:
<syntaxhighlight lang=lua>function Bitmap:floodfill(x, y, c)
<syntaxhighlight lang="lua">function Bitmap:floodfill(x, y, c)
local b = self:get(x, y)
local b = self:get(x, y)
if not b then return end
if not b then return end
Line 2,027: Line 2,003:
end</syntaxhighlight>
end</syntaxhighlight>
Demo:
Demo:
<syntaxhighlight lang=lua>bitmap = Bitmap(0, 0)
<syntaxhighlight lang="lua">bitmap = Bitmap(0, 0)
bitmap:loadPPM("unfilledcirc.ppm")
bitmap:loadPPM("unfilledcirc.ppm")
bitmap:floodfill( 1, 1, { 255,0,0 }) -- fill exterior (except bottom right) with red
bitmap:floodfill( 1, 1, { 255,0,0 }) -- fill exterior (except bottom right) with red
Line 2,033: Line 2,009:
bitmap:floodfill( 100, 100, { 0,0,255 })-- fill smaller circle with blue
bitmap:floodfill( 100, 100, { 0,0,255 })-- fill smaller circle with blue
bitmap:savePPM("filledcirc.ppm")</syntaxhighlight>
bitmap:savePPM("filledcirc.ppm")</syntaxhighlight>

=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>createMask[img_, pos_, tol_] :=
<syntaxhighlight lang="mathematica">createMask[img_, pos_, tol_] :=
RegionBinarize[img, Image[SparseArray[pos -> 1, ImageDimensions[img]]], tol];
RegionBinarize[img, Image[SparseArray[pos -> 1, ImageDimensions[img]]], tol];
floodFill[img_Image, pos_List, tol_Real, color_List] :=
floodFill[img_Image, pos_List, tol_Real, color_List] :=
Line 2,048: Line 2,023:
Import the test image and fill the region containing the pixel at coordinate 100,100 with red (RGB 100%,0%,0%) using a tolerance of 1%
Import the test image and fill the region containing the pixel at coordinate 100,100 with red (RGB 100%,0%,0%) using a tolerance of 1%
<pre>floodFill[Import["http://rosettacode.org/mw/images/0/0f/Unfilledcirc.png"], {100, 100}, 0.01, {1, 0, 0}]</pre>
<pre>floodFill[Import["http://rosettacode.org/mw/images/0/0f/Unfilledcirc.png"], {100, 100}, 0.01, {1, 0, 0}]</pre>

=={{header|Nim}}==
=={{header|Nim}}==
{{Trans|Python}}
{{Trans|Python}}
<syntaxhighlight lang=Nim>import bitmap
<syntaxhighlight lang="nim">import bitmap


proc floodFill*(img: Image; initPoint: Point; targetColor, replaceColor: Color) =
proc floodFill*(img: Image; initPoint: Point; targetColor, replaceColor: Color) =
Line 2,100: Line 2,074:
img.floodFill((30, 122), White, color(255, 0, 0))
img.floodFill((30, 122), White, color(255, 0, 0))
img.writePPM("Unfilledcirc_red.ppm")</syntaxhighlight>
img.writePPM("Unfilledcirc_red.ppm")</syntaxhighlight>

=={{header|OCaml}}==
=={{header|OCaml}}==
{{Trans|C}}
{{Trans|C}}
<syntaxhighlight lang=ocaml>
<syntaxhighlight lang="ocaml">
let floodFill ~img (i, j) newColor =
let floodFill ~img (i, j) newColor =
let oldColor = get_pixel ~img ~pt:(i, j) in
let oldColor = get_pixel ~img ~pt:(i, j) in
Line 2,121: Line 2,094:
in
in
aux (i, j)</syntaxhighlight>
aux (i, j)</syntaxhighlight>

=={{header|Pascal}}==
=={{header|Pascal}}==
{{trans|C#}}
{{trans|C#}}
<syntaxhighlight lang=Pascal>
<syntaxhighlight lang="pascal">


program FloodFillTest;
program FloodFillTest;
Line 2,196: Line 2,168:
end.
end.
</syntaxhighlight>
</syntaxhighlight>

=={{header|Perl}}==
=={{header|Perl}}==


Line 2,203: Line 2,174:
The <tt>fill</tt> of the Perl package Image::Imlib2 is a flood fill (so the documentatin of Image::Imlib2 says). The target colour is the one of the starting point pixel; the color set with <tt>set_color</tt> is the fill colour.
The <tt>fill</tt> of the Perl package Image::Imlib2 is a flood fill (so the documentatin of Image::Imlib2 says). The target colour is the one of the starting point pixel; the color set with <tt>set_color</tt> is the fill colour.


<syntaxhighlight lang=perl>#! /usr/bin/perl
<syntaxhighlight lang="perl">#! /usr/bin/perl


use strict;
use strict;
Line 2,216: Line 2,187:
A homemade implementation can be:
A homemade implementation can be:


<syntaxhighlight lang=perl>use strict;
<syntaxhighlight lang="perl">use strict;
use Image::Imlib2;
use Image::Imlib2;


Line 2,266: Line 2,237:


This fills better than the Image::Imlib2 <tt>fill</tt> function the inner circle, since because of JPG compression and thanks to the <tt>$distparameter</tt>, it "sees" as black also pixel that are no more exactly black.
This fills better than the Image::Imlib2 <tt>fill</tt> function the inner circle, since because of JPG compression and thanks to the <tt>$distparameter</tt>, it "sees" as black also pixel that are no more exactly black.

=={{header|Phix}}==
=={{header|Phix}}==
{{Trans|Go}}
{{Trans|Go}}
Requires read_ppm() from [[Bitmap/Read_a_PPM_file#Phix|Read a PPM file]], write_ppm() from [[Bitmap/Write_a_PPM_file#Phix|Write a PPM file]]. <br>
Requires read_ppm() from [[Bitmap/Read_a_PPM_file#Phix|Read a PPM file]], write_ppm() from [[Bitmap/Write_a_PPM_file#Phix|Write a PPM file]]. <br>
Uses the output of [[Bitmap/Midpoint_circle_algorithm#Phix|Midpoint circle algorithm]] (Circle.ppm), results may be verified with demo\rosetta\viewppm.exw
Uses the output of [[Bitmap/Midpoint_circle_algorithm#Phix|Midpoint circle algorithm]] (Circle.ppm), results may be verified with demo\rosetta\viewppm.exw
<syntaxhighlight lang=Phix>-- demo\rosetta\Bitmap_FloodFill.exw (runnable version)
<syntaxhighlight lang="phix">-- demo\rosetta\Bitmap_FloodFill.exw (runnable version)
include ppm.e -- blue, green, read_ppm(), write_ppm() (covers above requirements)
include ppm.e -- blue, green, read_ppm(), write_ppm() (covers above requirements)


Line 2,297: Line 2,267:
img = FloodFill(img, 10, 10, green)
img = FloodFill(img, 10, 10, green)
write_ppm("FloodOut.ppm",img)</syntaxhighlight>
write_ppm("FloodOut.ppm",img)</syntaxhighlight>

=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Using the format of [[Bitmap#PicoLisp|Bitmap]], a minimal recursive solution:
Using the format of [[Bitmap#PicoLisp|Bitmap]], a minimal recursive solution:
<syntaxhighlight lang=PicoLisp>(de ppmFloodFill (Ppm X Y Color)
<syntaxhighlight lang="picolisp">(de ppmFloodFill (Ppm X Y Color)
(let Target (get Ppm Y X)
(let Target (get Ppm Y X)
(recur (X Y)
(recur (X Y)
Line 2,314: Line 2,283:
(ppmFloodFill (ppmRead "Unfilledcirc.ppm") 192 128 (255 0 0))
(ppmFloodFill (ppmRead "Unfilledcirc.ppm") 192 128 (255 0 0))
"Filledcirc.ppm" )</pre>
"Filledcirc.ppm" )</pre>

=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=PL/I>fill: procedure (x, y, fill_color) recursive; /* 12 May 2010 */
<syntaxhighlight lang="pl/i">fill: procedure (x, y, fill_color) recursive; /* 12 May 2010 */
declare (x, y) fixed binary;
declare (x, y) fixed binary;
declare fill_color bit (24) aligned;
declare fill_color bit (24) aligned;
Line 2,344: Line 2,312:
The following PL/I statements change the color of the white area
The following PL/I statements change the color of the white area
of the sample image to red, and the central orb to green.
of the sample image to red, and the central orb to green.
<syntaxhighlight lang=text>
<syntaxhighlight lang="text">
/* Fill the white area of the suggested image with red color. */
/* Fill the white area of the suggested image with red color. */
area_color = (24)'1'b;
area_color = (24)'1'b;
Line 2,353: Line 2,321:
call fill (125, 125, '000000001111111100000000'b );
call fill (125, 125, '000000001111111100000000'b );
</syntaxhighlight>
</syntaxhighlight>

=={{header|Processing}}==
=={{header|Processing}}==
<syntaxhighlight lang=java>import java.awt.Point;
<syntaxhighlight lang="java">import java.awt.Point;
import java.util.Queue;
import java.util.Queue;
import java.util.LinkedList;
import java.util.LinkedList;
Line 2,437: Line 2,404:


==={{header|Processing Python mode}}===
==={{header|Processing Python mode}}===
<syntaxhighlight lang=Python>from collections import deque
<syntaxhighlight lang="python">from collections import deque


image_file = "image.png"
image_file = "image.png"
Line 2,511: Line 2,478:
img.pixels[pixel_position(x, y)] = fill_color
img.pixels[pixel_position(x, y)] = fill_color
return True</syntaxhighlight>
return True</syntaxhighlight>

=={{header|PureBasic}}==
=={{header|PureBasic}}==
=== built-in ===
=== built-in ===
<syntaxhighlight lang=PureBasic>FillArea(0,0,-1,$ff)
<syntaxhighlight lang="purebasic">FillArea(0,0,-1,$ff)
; Fills an Area in red</syntaxhighlight>
; Fills an Area in red</syntaxhighlight>


=== Iterative ===
=== Iterative ===
<syntaxhighlight lang=PureBasic> Procedure Floodfill(x,y,new_color)
<syntaxhighlight lang="purebasic"> Procedure Floodfill(x,y,new_color)
old_color = Point(x,y)
old_color = Point(x,y)
NewList stack.POINT()
NewList stack.POINT()
Line 2,548: Line 2,514:
Until Event = #PB_Event_CloseWindow
Until Event = #PB_Event_CloseWindow
EndIf</syntaxhighlight>
EndIf</syntaxhighlight>

=={{header|Python}}==
=={{header|Python}}==
<syntaxhighlight lang=python>
<syntaxhighlight lang="python">
import Image
import Image
def FloodFill( fileName, initNode, targetColor, replaceColor ):
def FloodFill( fileName, initNode, targetColor, replaceColor ):
Line 2,598: Line 2,563:


===Usage example===
===Usage example===
<syntaxhighlight lang=python>
<syntaxhighlight lang="python">
# "FloodFillClean.png" is name of input file
# "FloodFillClean.png" is name of input file
# [55,55] the x,y coordinate where fill starts
# [55,55] the x,y coordinate where fill starts
Line 2,607: Line 2,572:
img.save( "Filled.png" )
img.save( "Filled.png" )
</syntaxhighlight>
</syntaxhighlight>

=={{header|R}}==
=={{header|R}}==
'''Stack-based recursive version'''
'''Stack-based recursive version'''
<syntaxhighlight lang=R>
<syntaxhighlight lang="r">
library(png)
library(png)
img <- readPNG("Unfilledcirc.png")
img <- readPNG("Unfilledcirc.png")
Line 2,636: Line 2,600:
</syntaxhighlight>
</syntaxhighlight>
'''Queue-based version (Forest Fire algorithm)'''
'''Queue-based version (Forest Fire algorithm)'''
<syntaxhighlight lang=R>
<syntaxhighlight lang="r">
library(png)
library(png)
img <- readPNG("Unfilledcirc.png")
img <- readPNG("Unfilledcirc.png")
Line 2,675: Line 2,639:
image(M, col = c(1, 0, 2, 3))
image(M, col = c(1, 0, 2, 3))
</syntaxhighlight>
</syntaxhighlight>

=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,761: Line 2,724:
bm
bm
</syntaxhighlight>
</syntaxhighlight>

=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Line 2,767: Line 2,729:
Using bits and pieces from various other bitmap tasks.
Using bits and pieces from various other bitmap tasks.


<syntaxhighlight lang=raku line>class Pixel { has Int ($.R, $.G, $.B) }
<syntaxhighlight lang="raku" line>class Pixel { has Int ($.R, $.G, $.B) }
class Bitmap {
class Bitmap {
has Int ($.width, $.height);
has Int ($.width, $.height);
Line 2,842: Line 2,804:


See output image [https://github.com/thundergnat/rc/blob/master/img/Bitmap-flood-perl6.png Bitmap-flood-perl6 ] (offsite image file, converted to PNG for ease of viewing)
See output image [https://github.com/thundergnat/rc/blob/master/img/Bitmap-flood-perl6.png Bitmap-flood-perl6 ] (offsite image file, converted to PNG for ease of viewing)

=={{header|REXX}}==
=={{header|REXX}}==
{{trans|PL/I}}
{{trans|PL/I}}
<syntaxhighlight lang=rexx>/*REXX program demonstrates a method to perform a flood fill of an area. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates a method to perform a flood fill of an area. */
black= '000000000000000000000000'b /*define the black color (using bits).*/
black= '000000000000000000000000'b /*define the black color (using bits).*/
red = '000000000000000011111111'b /* " " red " " " */
red = '000000000000000011111111'b /* " " red " " " */
Line 2,871: Line 2,832:
@: parse arg $x,$y; return image.$x.$y /*return with color of the X,Y pixel.*/</syntaxhighlight>
@: parse arg $x,$y; return image.$x.$y /*return with color of the X,Y pixel.*/</syntaxhighlight>
<br><br>
<br><br>

=={{header|Ruby}}==
=={{header|Ruby}}==


Uses [[Raster graphics operations/Ruby]]
Uses [[Raster graphics operations/Ruby]]


<syntaxhighlight lang=ruby># frozen_string_literal: true
<syntaxhighlight lang="ruby"># frozen_string_literal: true


require_relative 'raster_graphics'
require_relative 'raster_graphics'
Line 2,938: Line 2,898:
JRubyArt is a port of Processing to the ruby language
JRubyArt is a port of Processing to the ruby language


<syntaxhighlight lang=ruby># holder for pixel coords
<syntaxhighlight lang="ruby"># holder for pixel coords
Pixel = Struct.new(:x, :y)
Pixel = Struct.new(:x, :y)


Line 2,991: Line 2,951:
end
end
</syntaxhighlight>
</syntaxhighlight>

=={{header|Rust}}==
=={{header|Rust}}==


<syntaxhighlight lang=rust>
<syntaxhighlight lang="rust">
/* Naive Rust implementation of RosettaCode's Bitmap/Flood fill excercise.
/* Naive Rust implementation of RosettaCode's Bitmap/Flood fill excercise.
*
*
Line 3,083: Line 3,042:


}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Scala}}==
=={{header|Scala}}==


Line 3,090: Line 3,048:
See [[Basic_bitmap_storage#Scala|Basic Bitmap Storage]] for RgbBitmap class.
See [[Basic_bitmap_storage#Scala|Basic Bitmap Storage]] for RgbBitmap class.


<syntaxhighlight lang=scala>import java.awt.Color
<syntaxhighlight lang="scala">import java.awt.Color
import scala.collection.mutable
import scala.collection.mutable


Line 3,133: Line 3,091:
}
}
}</syntaxhighlight>
}</syntaxhighlight>

=={{header|Standard ML}}==
=={{header|Standard ML}}==
This implementation is imperative, updating the pixels of the image as it goes.
This implementation is imperative, updating the pixels of the image as it goes.
Line 3,139: Line 3,096:
data structures instead.
data structures instead.


<syntaxhighlight lang=sml>(* For simplicity, we're going to fill black-and-white images. Nothing
<syntaxhighlight lang="sml">(* For simplicity, we're going to fill black-and-white images. Nothing
* fundamental would change if we used more colors. *)
* fundamental would change if we used more colors. *)
datatype color = Black | White
datatype color = Black | White
Line 3,188: Line 3,145:
(* Fill the image with black starting at the center. *)
(* Fill the image with black starting at the center. *)
val () = fill test Black (3,3)</syntaxhighlight>
val () = fill test Black (3,3)</syntaxhighlight>

=={{header|Tcl}}==
=={{header|Tcl}}==
{{libheader|Tk}}
{{libheader|Tk}}
{{tcllib|struct::queue}}
{{tcllib|struct::queue}}
Using code from [[Basic bitmap storage#Tcl|Basic bitmap storage]], [[Bresenham's line algorithm#Tcl|Bresenham's line algorithm]] and [[Midpoint circle algorithm#Tcl|Midpoint circle algorithm]]
Using code from [[Basic bitmap storage#Tcl|Basic bitmap storage]], [[Bresenham's line algorithm#Tcl|Bresenham's line algorithm]] and [[Midpoint circle algorithm#Tcl|Midpoint circle algorithm]]
<syntaxhighlight lang=tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk
package require Tk
package require struct::queue
package require struct::queue
Line 3,270: Line 3,226:


[[Image:Tcl_flood_fill.png]]
[[Image:Tcl_flood_fill.png]]

=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|DOME}}
{{libheader|DOME}}
Line 3,278: Line 3,233:


When the up arrow is pressed, the red square changes to blue and when the down arrow is pressed the blue square turns back to red.
When the up arrow is pressed, the red square changes to blue and when the down arrow is pressed the blue square turns back to red.
<syntaxhighlight lang=ecmascript>import "graphics" for Canvas, ImageData, Color
<syntaxhighlight lang="ecmascript">import "graphics" for Canvas, ImageData, Color
import "dome" for Window
import "dome" for Window
import "input" for Keyboard
import "input" for Keyboard
Line 3,349: Line 3,304:


var Game = Bitmap.new("Bitmap - flood fill", 600)</syntaxhighlight>
var Game = Bitmap.new("Bitmap - flood fill", 600)</syntaxhighlight>

=={{header|XPL0}}==
=={{header|XPL0}}==
[[File:FloodXPL0.gif|right|Output]]
[[File:FloodXPL0.gif|right|Output]]
<syntaxhighlight lang=XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;


proc Flood(X, Y, C, C0); \Fill an area of color C0 with color C
proc Flood(X, Y, C, C0); \Fill an area of color C0 with color C
Line 3,412: Line 3,366:
SetVid(3); \restore normal text mode
SetVid(3); \restore normal text mode
]</syntaxhighlight>
]</syntaxhighlight>

=={{header|zkl}}==
=={{header|zkl}}==
[[file:Flood_before.zkl.jpg|right]][[file:Flood.zkl.jpg|right]]
[[file:Flood_before.zkl.jpg|right]][[file:Flood.zkl.jpg|right]]
Line 3,418: Line 3,371:
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
Uses the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl


<syntaxhighlight lang=zkl>fcn flood(pixmap, x,y, repl){ // slow!
<syntaxhighlight lang="zkl">fcn flood(pixmap, x,y, repl){ // slow!
targ,h,w:=pixmap[x,y], pixmap.h,pixmap.w;
targ,h,w:=pixmap[x,y], pixmap.h,pixmap.w;
stack:=List(T(x,y));
stack:=List(T(x,y));
Line 3,432: Line 3,385:
}
}
}</syntaxhighlight>
}</syntaxhighlight>
<syntaxhighlight lang=zkl>pixmap:=PPM(250,302,0xFF|FF|FF);
<syntaxhighlight lang="zkl">pixmap:=PPM(250,302,0xFF|FF|FF);
pixmap.circle(101,200,100,0); pixmap.circle(75,100,25,0);
pixmap.circle(101,200,100,0); pixmap.circle(75,100,25,0);


Line 3,440: Line 3,393:


pixmap.writeJPGFile("flood.zkl.jpg");</syntaxhighlight>
pixmap.writeJPGFile("flood.zkl.jpg");</syntaxhighlight>
{{omit from|AWK}}

{{omit from|Computer/zero Assembly|this language doesn't support video output and only has 32 bytes of RAM}}
{{omit from|Computer/zero Assembly|this language doesn't support video output and only has 32 bytes of RAM}}
{{omit from|AWK}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|Lotus 123 Macro Scripting}}
{{omit from|PARI/GP}}
{{omit from|PARI/GP}}