SLIC Superpixel算法可以参考:https://www.cnblogs.com/supersponge/p/6546082.html
#include
#include
extern "C" {
#include "vlfeat/generic.h"
#include "vlfeat/slic.h"
}
int main() {
//读取图像
cv::Mat mat = cv::imread("../../datas/images/bird.jpg", CV_LOAD_IMAGE_COLOR);
if(mat.empty()){
std::cout << "cannot read images.\n";
return 0;
}
assert(mat.depth() == 3);
//将图像转换成一维数组
float* image = new float[mat.rows*mat.cols*mat.channels()];
for (int i = 0; i < mat.rows; ++i) {
for (int j = 0; j < mat.cols; ++j) {
image[j + mat.cols*i + mat.cols*mat.rows*0] = mat.at<:vec3b>(i, j)[0];
image[j + mat.cols*i + mat.cols*mat.rows*1] = mat.at<:vec3b>(i, j)[1];
image[j + mat.cols*i + mat.cols*mat.rows*2] = mat.at<:vec3b>(i, j)[2];
}
}
//图像分割结果储存为一维数组
vl_uint32* segmentation = new vl_uint32[mat.rows*mat.cols];
vl_size height = mat.rows;
vl_size width = mat.cols;
vl_size channels = mat.channels();
//定义超像素区域的大小
vl_size region = 30;
float regularization = 1000.;
vl_size minRegion = 10;
vl_slic_segment(segmentation, image, width, height, channels, region, regularization, minRegion);
// 转换分割结果
int** labels = new int*[mat.rows];
for (int i = 0; i < mat.rows; ++i) {
labels[i] = new int[mat.cols];
for (int j = 0; j < mat.cols; ++j) {
labels[i][j] = (int) segmentation[j + mat.cols*i];
}
}
int label = 0;
int labelTop = -1;
int labelBottom = -1;
int labelLeft = -1;
int labelRight = -1;
//绘制结果
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
label = labels[i][j];
labelTop = label;
if (i > 0) {
labelTop = labels[i - 1][j];
}
labelBottom = label;
if (i < mat.rows - 1) {
labelBottom = labels[i + 1][j];
}
labelLeft = label;
if (j > 0) {
labelLeft = labels[i][j - 1];
}
labelRight = label;
if (j < mat.cols - 1) {
labelRight = labels[i][j + 1];
}
if (label != labelTop || label != labelBottom || label!= labelLeft || label != labelRight) {
mat.at<:vec3b>(i, j)[0] = 0;
mat.at<:vec3b>(i, j)[1] = 0;
mat.at<:vec3b>(i, j)[2] = 255;
}
}
}
cv::imwrite("result.png", mat);
cv::imshow("result",mat);
cv::waitKey();
cv::destroyAllWindows();
return 0;
}
程序运行的结果如下: