int label = 1; for (int i = 1; i < inputImg.rows - 1; i++) for (int j = 1; j < inputImg.cols - 1; j++) { if (inputImg.at<uchar>(i, j) == 255) { cv::Point currentPoint(j, i); std::vector<cv::Point> neighborPoints; neighborPoints.push_back(cv::Point(j - 1, i - 1)); neighborPoints.push_back(cv::Point(j, i - 1)); neighborPoints.push_back(cv::Point(j + 1, i - 1)); neighborPoints.push_back(cv::Point(j - 1, i)); int minLabel = 255; for (std::vector<cv::Point>::iterator it = neighborPoints.begin(); it != neighborPoints.end(); it++) { int neighborLabel = labelImg.at<int>(it->y, it->x); if (neighborLabel > 0 && neighborLabel < minLabel) minLabel = neighborLabel; } if (minLabel == 255) { labelImg.at<int>(i, j) = label; label++; } else { labelImg.at<int>(i, j) = minLabel; for (std::vector<cv::Point>::iterator it = neighborPoints.begin(); it != neighborPoints.end(); it++) if (labelImg.at<int>(it->y, it->x) > 0 && labelImg.at<int>(it->y, it->x) != minLabel) { int tempLabel = labelImg.at<int>(it->y, it->x); cv::Mat mask = (labelImg == tempLabel); labelImg.setTo(minLabel, mask); } } } }如何让标记的不同区域数值不一样,不再是每个区域都是1,而是不同区域可以有1 2 3之类的
时间: 2023-06-23 11:09:34 浏览: 125
可以在代码中增加一个变量来记录当前已经标记的区域数,初始值为1,每当发现一个新的区域时,将该变量的值加1并赋给该区域的标记值。例如:
```cpp
int label = 1;
int numRegions = 1; // 记录当前已经标记的区域数
for (int i = 1; i < inputImg.rows - 1; i++)
for (int j = 1; j < inputImg.cols - 1; j++)
{
if (inputImg.at<uchar>(i, j) == 255)
{
cv::Point currentPoint(j, i);
std::vector<cv::Point> neighborPoints;
neighborPoints.push_back(cv::Point(j - 1, i - 1));
neighborPoints.push_back(cv::Point(j, i - 1));
neighborPoints.push_back(cv::Point(j + 1, i - 1));
neighborPoints.push_back(cv::Point(j - 1, i));
int minLabel = 255;
for (std::vector<cv::Point>::iterator it = neighborPoints.begin(); it != neighborPoints.end(); it++)
{
int neighborLabel = labelImg.at<int>(it->y, it->x);
if (neighborLabel > 0 && neighborLabel < minLabel)
minLabel = neighborLabel;
}
if (minLabel == 255)
{
labelImg.at<int>(i, j) = numRegions;
numRegions++; // 新区域的标记值为当前已经标记的区域数
}
else
{
labelImg.at<int>(i, j) = minLabel;
for (std::vector<cv::Point>::iterator it = neighborPoints.begin(); it != neighborPoints.end(); it++)
if (labelImg.at<int>(it->y, it->x) > 0 && labelImg.at<int>(it->y, it->x) != minLabel)
{
int tempLabel = labelImg.at<int>(it->y, it->x);
cv::Mat mask = (labelImg == tempLabel);
labelImg.setTo(minLabel, mask);
}
}
}
}
```
这样就可以实现不同区域的标记值不同。
阅读全文