Bitmap/Flood fill: Difference between revisions

m
Add a C++ flood fill implementation
m (Add a C++ flood fill implementation)
Line 527:
return 0;
}</lang>
 
=={{header|C++}}==
{{libheader|OpenCV}}
 
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.
 
'''Interface'''
<lang cpp>#ifndef PROCESSING_FLOODFILLALGORITHM_H_
#define PROCESSING_FLOODFILLALGORITHM_H_
 
#include <opencv2/opencv.hpp>
#include <string.h>
#include <queue>
 
using namespace cv;
using namespace std;
 
class FloodFillAlgorithm {
public:
FloodFillAlgorithm(Mat* image) :
image(image) {
}
virtual ~FloodFillAlgorithm();
 
void flood(Point startPoint, Scalar tgtColor, Scalar loDiff);
void flood(Point startPoint, Mat* tgtMat);
 
protected:
Mat* image;
private:
bool insideImage(Point p);
};
 
#endif /* PROCESSING_FLOODFILLALGORITHM_H_ */
</lang>
'''Implementation'''
<lang cpp>#include "FloodFillAlgorithm.h"
 
FloodFillAlgorithm::~FloodFillAlgorithm() {
}
 
void FloodFillAlgorithm::flood(Point startPoint, Scalar tgtColor, Scalar loDiff) {
floodFill(*image, startPoint, tgtColor, 0, loDiff);
}
 
void FloodFillAlgorithm::flood(Point startPoint, Mat* tgtMat) {
if (!insideImage(startPoint))
return;
 
Vec3b srcColor = image->at<Vec3b>(startPoint);
 
if (image->at<Vec3b>(startPoint) == srcColor) {
 
queue<Point> pointQueue;
pointQueue.push(startPoint);
 
while (!pointQueue.empty()) {
Point p = pointQueue.front();
pointQueue.pop();
 
if (insideImage(p)) {
 
if ((image->at<Vec3b>(p) == srcColor)) {
image->at<Vec3b>(p) = tgtMat->at<Vec3b>(p);
 
pointQueue.push(Point(p.x + 1, p.y));
pointQueue.push(Point(p.x - 1, p.y));
pointQueue.push(Point(p.x, p.y + 1));
pointQueue.push(Point(p.x, p.y - 1));
}
}
 
}
}
}
 
bool FloodFillAlgorithm::insideImage(Point p) {
return (p.x >= 0) && (p.x < image->size().width) && (p.y >= 0) && (p.y < image->size().height);
}
 
</lang>
 
=={{header|C sharp|C#}}==