我画个图来测试一下:
我想知道黑色圆圈中有多少斑点以及每个斑点的大小是多少(所有斑点都是白色的)。
例如,在本例中我有 12 个位置:
我知道如何找到白色像素,并且很容易从左侧验证序列:
int whitePixels = 0;
for (int i = 0; i < height; ++i)
{
uchar * pixel = image.ptr<uchar>(i);
for (int j = 0; j < width; ++j)
{
if (j>0 && pixel[j-1]==0) // to group pixels for one spot
whitePixels++;
}
}
但很明显这段代码不够好(斑点可以是对角线的,等等)。
那么,底线:如何定义斑点?
以下代码查找所有白点的边界矩形(斑点)。
备注:如果我们可以假设白点确实是白色的(即灰度图像中的值为 255),则可以使用此代码片段。考虑将其放入某个类中,以避免将不必要的参数传递给函数 Traverse。虽然它有效。这个想法是基于DFS的。除了灰度图像之外,我们还有 ids 矩阵来分配并记住哪个像素属于哪个 blob(具有相同 id 的所有像素都属于同一个 blob)。
void Traverse(int xs, int ys, cv::Mat &ids,cv::Mat &image, int blobID, cv::Point &leftTop, cv::Point &rightBottom) {
std::stack<cv::Point> S;
S.push(cv::Point(xs,ys));
while (!S.empty()) {
cv::Point u = S.top();
S.pop();
int x = u.x;
int y = u.y;
if (image.at<unsigned char>(y,x) == 0 || ids.at<unsigned char>(y,x) > 0)
continue;
ids.at<unsigned char>(y,x) = blobID;
if (x < leftTop.x)
leftTop.x = x;
if (x > rightBottom.x)
rightBottom.x = x;
if (y < leftTop.y)
leftTop.y = y;
if (y > rightBottom.y)
rightBottom.y = y;
if (x > 0)
S.push(cv::Point(x-1,y));
if (x < ids.cols-1)
S.push(cv::Point(x+1,y));
if (y > 0)
S.push(cv::Point(x,y-1));
if (y < ids.rows-1)
S.push(cv::Point(x,y+1));
}
}
int FindBlobs(cv::Mat &image, std::vector<cv::Rect> &out, float minArea) {
cv::Mat ids = cv::Mat::zeros(image.rows, image.cols,CV_8UC1);
cv::Mat thresholded;
cv::cvtColor(image, thresholded, CV_RGB2GRAY);
const int thresholdLevel = 130;
cv::threshold(thresholded, thresholded, thresholdLevel, 255, CV_THRESH_BINARY);
int blobId = 1;
for (int x = 0;x<ids.cols;x++)
for (int y=0;y<ids.rows;y++){
if (thresholded.at<unsigned char>(y,x) > 0 && ids.at<unsigned char>(y,x) == 0) {
cv::Point leftTop(ids.cols-1, ids.rows-1), rightBottom(0,0);
Traverse(x,y,ids, thresholded,blobId++, leftTop, rightBottom);
cv::Rect r(leftTop, rightBottom);
if (r.area() > minArea)
out.push_back(r);
}
}
return blobId;
}
编辑:我修复了一个错误,降低了阈值级别,现在输出如下。我认为这是一个很好的起点。
编辑2:我摆脱了
Traverse()
中的递归。在更大的图像中,递归导致了 Stackoverflow。