我正在使用cv :: ximgproc :: SuperpixelSLIC opencv c ++来生成图像片段。我希望每个细分标签都是唯一的。这是我的代码。
Function WhereAmI()
WhereAmI = Application.Caller.Parent.Name
End Function
在label.txt文件中,我观察到标签0已被赋予两个片段(即片段包括像素(0,0)和像素(692,442)。这两个片段距离很远。
这是正常的事情还是我的代码不正确。请帮我找到每个细分的唯一标签。
答案 0 :(得分:1)
您基本上需要的是连接组件算法。在不知道您使用的确切SLIC实现的情况下,SLIC通常倾向于产生断开的超像素,即具有相同标签的断开的段。我使用的一个简单解决方案是此处的连通组件算法表单:https://github.com/davidstutz/matlab-multi-label-connected-components(最初来自此处:http://xenia.media.mit.edu/~rahimi/connected/)。请注意,此存储库包含MatLab包装器。在您的情况下,您只需要connected_components.h
以及以下代码:
#include "connected_components.h"
// ...
void relabelSuperpixels(cv::Mat &labels) {
int max_label = 0;
for (int i = 0; i < labels.rows; i++) {
for (int j = 0; j < labels.cols; j++) {
if (labels.at<int>(i, j) > max_label) {
max_label = labels.at<int>(i, j);
}
}
}
int current_label = 0;
std::vector<int> label_correspondence(max_label + 1, -1);
for (int i = 0; i < labels.rows; i++) {
for (int j = 0; j < labels.cols; j++) {
int label = labels.at<int>(i, j);
if (label_correspondence[label] < 0) {
label_correspondence[label] = current_label++;
}
labels.at<int>(i, j) = label_correspondence[label];
}
}
}
int relabelConnectedSuperpixels(cv::Mat &labels) {
relabelSuperpixels(labels);
int max = 0;
for (int i = 0; i < labels.rows; ++i) {
for (int j = 0; j < labels.cols; ++j) {
if (labels.at<int>(i, j) > max) {
max = labels.at<int>(i, j);
}
}
}
ConnectedComponents cc(2*max);
cv::Mat components(labels.rows, labels.cols, CV_32SC1, cv::Scalar(0));
int component_count = cc.connected<int, int, std::equal_to<int>, bool>((int*) labels.data, (int*) components.data, labels.cols,
labels.rows, std::equal_to<int>(), false);
for (int i = 0; i < labels.rows; i++) {
for (int j = 0; j < labels.cols; j++) {
labels.at<int>(i, j) = components.at<int>(i, j);
}
}
// component_count would be the NEXT label index, max is the current highest!
return component_count - max - 1;
}
在获得的标签上,运行relabelConnectedSuperpixels
。