超像素分割opencv实现_OpenCV图像处理实例:使用vlfeat的SLIC Superpixel实现图像分割...

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;

}

程序运行的结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值