1
$\begingroup$

Let me explain what I want to achieve. I'm working on the coloring book project. On the input, I'm getting transparent images with black borders (Like this). Currently, I've created the 2D Matrix with colors in points. And basing on this Matrix I want to form an array of regions.

Region:

class Region {
    var set = Set<Point>()

    func contains(_ point: Point) -> Bool {
        return set.contains(point)
    }
}

The region represents points that form bordered parts(e.g. gun barrel, button, hat). My future logic will be this:

  1. Users taps.
  2. Get point.
  3. Find the region that contains that point.
  4. Color all the points in that region.

The problem is that I don't know how to form those regions :). Can you please help me solve this problem? Maybe it's some famous algorithm but I just don't know how to google it properly.

P.S. I hope this is the correct place to ask this kind of question.

$\endgroup$
3
$\begingroup$

Once you get the point, you can use Flood Fill Algorithm to replace the current color in the region containing the point with the new color.

Basically, this algorithm starts from a specified point and then recursively(or iteratively) keep replacing the current color with the new specified color in the neighbouring points till it reaches the boundary of the region.

It detects the boundary by checking for points having different color(different from current and new color). So you don't have detect/store the regions in advance.

$\endgroup$
  • 1
    $\begingroup$ Thank you, sir :) $\endgroup$ – Bohdan Savych Sep 11 at 8:30
  • $\begingroup$ But storing region will be faster than every time calculating boundaries? $\endgroup$ – Bohdan Savych Sep 11 at 8:32
  • $\begingroup$ That depends on the data structure in which you're storing the region. Because if you're filling the color pixel-by-pixel, then storing the region would not give much advantage. But if can think of some good way of storing the regions and changing the color is just marking the color associated with it, then definitely pre-computing regions would be beneficial. $\endgroup$ – TheCommonEngineer Sep 11 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.