PaintBucket is pretty literally what its title suggests. It is an implementation of Scanline Flood Fill in Swift, more commonly known as the algorithm that the paint bucket tool in MS Paint uses under the hood (well, it uses something like it, anyway).
This might, for example, be useful if you have a bunch of product photos shot against a uniformly-colored background and you want to remove said background. Or not, who knows.
This library exposes a single new category method on
let image = UIImage(named: "something")! let imageWithoutBackground = image.pbk_imageByReplacingColorAt((0, 0), withColor: UIColor.clearColor(), tolerance: 10)
Its parameters should be self-explanatory.
This is decently fast! That is to say, I was able to speed it up ~100x from my initial implementation (which admittedly was pretty slow). That said, it's not, like, instantaneous. You should probably do this on a background thread unless your images are tiny. (For reference, the 2000x1566 benchmark PNG takes like 3 seconds to process in the simulator on a MacBook pro).
Thanks to the always-amazing Mike Ash for the idea to use an
NSIndexSet for temporary storage, and thanks to this random website I found for some implementation ideas for the scanline optimization. That said, this can almost certainly be faster, and I'd welcome a PR that made it so. There's a benchmark in the test suite you can run to see if your code helps.
PRs welcome - I'd ask that you open an issue before blindly sending PRs my way just to make sure we agree that your idea is a Good Thing. To get you started, if someone wants to add some kind of clever anti-aliasing to this, I'd sure love that.
github "jflinter/PaintBucket", ~> 0.1 to your Cartfile.
pod 'PaintBucket', '~> 0.1' to your Podfile.