我正在一个图像处理项目中,其中已经充满了原始图像。
现在
127
)更改为白色。请注意,背景色应保持黑色。 这是this question的后续。使用this answer中的代码获得图像。
最佳答案
可以在your previous question中找到产生问题图像的代码。
因此,我们知道,洪水淹没的地区的值(value)为127
。
从此图像开始,您可以轻松地获得洪水泛滥区域的蒙版,如下所示:
Mat1b mask = (img == 127);
单通道掩码将具有黑色
0
或白色255
值。如果要获得彩色图像,则需要创建一个与
img
大小相同的黑色初始化图像,并根据蒙版将像素设置为您喜欢的颜色(此处为绿色):// Black initialized image, same size as img
Mat3b out(img.rows, img.cols, Vec3b(0,0,0));
Scalar some_color(0,255,0);
out.setTo(some_color, mask);
引用代码:
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
Mat1b img = imread("path_to_floodfilled_image", IMREAD_GRAYSCALE);
// 127 is the color of the floodfilled region
Mat1b mask = (img == 127);
// Black initialized image, same size as img
Mat3b out(img.rows, img.cols, Vec3b(0,0,0));
Scalar some_color(0,255,0);
out.setTo(some_color, mask);
// Show results
imshow("Flood filled image", img);
imshow("Mask", mask);
imshow("Colored mask", out);
waitKey();
return 0;
}