这里实现的区域生长法,是最原始的区域生长法,基本原理是判断像素点的强度值是和种子点的强度值差是否小于阈值,如果小于阈值则被标记。
实现过程中利用了栈的先进后出的思想,将8邻域中符合生长要求的点压入栈,然后依次取出,然后在取出的点的基础上对8邻域再次进行生长。
学习部分
1、获取像素点坐标值
分成两种,第一种是利用指针来取值的,第二种是利用点来访问强度值的,可以使用pt点,也可以使用x,y的坐标访问,但是这边涉及到opencv的坐标问题,y要放在前面。
startPtValue = ((unsigned char*)(srcImg.data + pt.y*srcImg.step))[pt.x];//该像素点所在行的首地址,然后再加上该像素点所在的列
markImg.at<uchar>(pt) = 255;
markImg.at<uchar>(y, x) = 255;
2、创建一张黑色的图像
Mat img = Mat::zeros(srcImg.size(), CV_8UC1);
CV_<bit_depth>(S|U|F)C<number_of_channels> CV_8(每个像素点占8bite)U(unsigned)C(channel)1
3、修改
①生长准则是将生长点和种子点的强度值相比,而不是将8邻域的点和当前栈中取出的点的强度值相比,可以利用一个全局灰度值作为生长准则
②生长过程有很多点被重复生长(标记图中强度为0的点,不符生长准则的可能会被二次生长)
/**
*@brief 区域生长法,输入图像应为灰度图
*@para srcImg 区域生长原图像
*@para pt 种子点
*@para thre 阈值
**/
void RegionGrowing(Mat srcImg, Mat& dstImg, Point pt, int thre)
{
// Mat RegionGrowing(Mat srcImg, Point pt, int thre)
// return growImage.clone();
Point ptGrowing; //待生长点坐标
int nGrowLabel = 0; //是否被标记 markImage灰度值不为0
int startPtValue = 0; //生长起始点灰度值
int currPtValue = 0; //当前生长点灰度值
//int growPtValue = 0; //待生长点灰度值
Mat markImg = Mat::zeros(srcImg.size(), CV_8UC1);//创建一个空白区域,填充颜色为黑色
int mDir[8][2] = { { -1,-1 },{ 0,-1 },{ 1,-1 },{ -1,0 },{ 1,0 },{ -1,1 },{ 0,1 },{ 1,1 } }; //8邻域
vector<Point> growPtVec;//生长点栈
growPtVec.push_back(pt);//将初始生长点压入栈
//unsigned char *pData = (unsigned char *)(markImg.data + pt.y*markImg.step);
//pData[pt.x] = 255;//标记初始生长点
markImg.at<uchar>(pt) = 255;
//startPtValue = ((unsigned char*)(srcImg.data + pt.y*srcImg.step))[pt.x];//该像素点所在行的首地址,然后再加上该像素点所在的列
startPtValue = srcImg.at<uchar>(pt);
while (!growPtVec.empty())
{
Point currPt = growPtVec.back(); //返回当前vector最末一个元素
growPtVec.pop_back(); //弹出最后压入的数据
for (int i = 0; i < 8; i++)
{
ptGrowing.x = currPt.x + mDir[i][0];
ptGrowing.y = currPt.y + mDir[i][1];
//判断是否是边缘点
if (ptGrowing.x < 0 || ptGrowing.y < 0 || (ptGrowing.x > srcImg.cols - 1) || (ptGrowing.y > srcImg.rows - 1))
continue;//继续执行下一次循环
//判断是否已被标记
//nGrowLabel = ((unsigned char*)(markImg.data + ptGrowing.y*markImg.step))[ptGrowing.x];
nGrowLabel = markImg.at<uchar>(ptGrowing);
if (nGrowLabel == 0) //没有被标记
{
//currPtValue = ((unsigned char*)(srcImg.data + ptGrowing.y*srcImg.step))[ptGrowing.x];
//currPtValue = srcImg.at<uchar>(currPt.y, currPt.x);
currPtValue = srcImg.at<uchar>(ptGrowing);
if (abs(currPtValue - startPtValue) <= thre)
{
//((unsigned char*)(markImg.data + ptGrowing.y*markImg.step))[ptGrowing.x] = 255;
markImg.at<uchar>(ptGrowing) = 255;
growPtVec.push_back(ptGrowing);
}
}
}
}
markImg.copyTo(dstImg);
}
int main()
{
Mat srcImg = imread("2.png",0);
imshow("orig", srcImg);
if (srcImg.empty())
printf("image read error");
Mat srcImg1 = srcImg.clone();
Mat outImg1, outImg2;
RegionGrowing(srcImg1, outImg1, Point(342, 321), 20); //241, 258
//RegionGrowing(srcImg1, outImg2, Point(302, 118), 80);
//add(outImg1, outImg2, outImg1);
imshow("p1p2", outImg1);
//Mat resultImg;
//srcImg.copyTo(resultImg, ~outImg1);
//imshow("outImg", resultImg);
//waitKey(0);
imshow("result", srcImg1);
waitKey(0);
return 0;
}