什么是洪水填充算法 ?如何用C++代码实现
作者:野牛程序员:2023-05-06 17:12:49 C++阅读 3510
洪水填充算法(Flood Fill Algorithm)是一种图像处理算法,它用于将一个特定的颜色区域内的所有像素点替换为另一个颜色。它的原理是从指定的种子像素点开始,扩散到它周围的像素点,将相邻的像素点替换为目标颜色,然后再对相邻像素点进行同样的操作,直到填充完整个区域。
下面是一个简单的C++代码实现洪水填充算法的示例:
#include <iostream>
#include <queue>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
// 洪水填充算法
void floodFill(Mat& image, Point seedPoint, Scalar newColor) {
Scalar oldColor = image.at<Vec3b>(seedPoint)[0]; // 获取种子像素点的颜色
queue<Point> pointsQueue;
pointsQueue.push(seedPoint);
while (!pointsQueue.empty()) {
Point currentPoint = pointsQueue.front();
pointsQueue.pop();
if (currentPoint.x < 0 || currentPoint.x >= image.cols || currentPoint.y < 0 || currentPoint.y >= image.rows) {
continue; // 超出图像边界
}
Vec3b& color = image.at<Vec3b>(currentPoint);
if (color[0] != oldColor) {
continue; // 颜色不匹配
}
color = newColor; // 替换颜色
// 将相邻的像素点加入队列
pointsQueue.push(Point(currentPoint.x + 1, currentPoint.y));
pointsQueue.push(Point(currentPoint.x - 1, currentPoint.y));
pointsQueue.push(Point(currentPoint.x, currentPoint.y + 1));
pointsQueue.push(Point(currentPoint.x, currentPoint.y - 1));
}
}
int main() {
Mat image = imread("test.png"); // 加载图像
if (image.empty()) {
cerr << "Failed to load image!" << endl;
return -1;
}
Point seedPoint(100, 100); // 种子像素点
Scalar newColor(0, 0, 255); // 目标颜色
floodFill(image, seedPoint, newColor); // 执行洪水填充算法
imshow("Filled Image", image); // 显示结果
waitKey(0);
return 0;
}在上面的示例代码中,我们使用了OpenCV库来加载和显示图像。在函数floodFill中,我们使用一个队列来存储待处理的像素点,并不断从队列中取出像素点进行处理,直到队列为空。在处理每个像素点时,我们检查它的颜色是否与种子像素点的颜色相同,如果相同,则将其替换为目标颜色,并将相邻的像素点加入队列中。最终,整个区域内的像素点都将被替换为目标颜色。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

