opencv超级像素示例
/* * createSuperpixelLSC(cv::InputArray img,int region_size,float ratio) 其中各个参数意义如下: image:输入图像 region_size :平均超像素大小,默认10 ratio:超像素紧凑度因子,默认0.075 */ void superpixelLSC(const Mat& img) { cv::Ptr<cv::ximgproc::SuperpixelLSC> lsc=cv::ximgproc::createSuperpixelLSC(img); lsc->iterate(10); Mat labels; lsc->enforceLabelConnectivity(); // int numOfSuperpixels=lsc->getNumberOfSuperpixels(); // cout<<"numOfSuperpixels="<<numOfSuperpixels<<endl; lsc->getLabels(labels); Mat mask_lsc; lsc->getLabelContourMask(mask_lsc);//获取像素分割边界映射图,该图与原图像一样尺寸 Mat mask_inv_lsc; cv::bitwise_not(mask_lsc,mask_inv_lsc);//将分割边界映射图按位取反 Mat imgSeg; cv::bitwise_and(img,img,imgSeg,mask_inv_lsc);//将边界映射图叠加到原图像上 imshow(" segmentation",imgSeg); } /* * ximgproc::createSuperpixelSLIC(cv::inputArray image, int algorithm=SLICO, int region_size,float ruler ) 其中各个参数意义如下: image :输入图像 algorithm:选择要使用的算法变体:SLIC、SLICO(默认)和MSLIC三种可选 region_size:平均超像素大小,默认10 ruler:超像素平滑度,默认10 */ void superpixelSLIC(const Mat&img) { //初始化slic项,超像素平均尺寸20(默认为10),平滑因子20 Mat imgLab; cvtColor(img,imgLab,COLOR_BGR2Lab); cv::Ptr<cv::ximgproc::SuperpixelSLIC> slic=cv::ximgproc::createSuperpixelSLIC(imgLab,cv::ximgproc::SLIC,20,20); slic->iterate(10);//迭代次数,越大效果越好 Mat mask_slic,mask_inv_slic,label_slic; slic->getLabelContourMask(mask_slic);//获取Mask,超像素边缘Mask==1 cv::bitwise_not(mask_slic,mask_inv_slic); Mat imgSeg; cv::bitwise_and(img,img,imgSeg,mask_inv_slic); slic->getLabels(label_slic);//获取超像素标签 imshow("SLIC segmentation",imgSeg); // int numOfSuperpixels=slic->getNumberOfSuperpixels(); // cout<<"numOfSuperpixels="<<numOfSuperpixels<<endl; } /* * createSuperpixelSEEDS(int image_width,int image_height, int image_channels, * int num_superpixels,int prior 其中各个参数意义如下: image_width :输入图像宽度 image_height: 输入图像高度 image_channels :输入图像通道数 num_superpixels :期望超像素数目 num_levels :块级别数,值越高,分段越准确,形状越平滑,但需要更多的内存和CPU时间。 histogram_bins: 直方图bins数,默认5 double_step: 如果为true,则每个块级别重复两次以提高准确性默认false。 原文链接:https://blog.csdn.net/qq_40268412/article/details/103915197 */ void superpixelSeeds(const Mat&img) { int num_superpixels=2000; int num_levels=3; cv::Ptr<cv::ximgproc::SuperpixelSEEDS> seeds= cv::ximgproc::createSuperpixelSEEDS(img.cols,img.rows,img.channels() ,num_superpixels,num_levels); Mat mask_seeds,mask_inv_seeds,label_seeds,img_seeds; seeds->iterate(img,10); seeds->getLabels(label_seeds); seeds->getLabelContourMask(mask_seeds); cv::bitwise_not(mask_seeds,mask_inv_seeds); cv::bitwise_and(img,img,img_seeds,mask_inv_seeds); cout<<"label_seeds.channels()="<<mask_seeds.channels()<<endl; cout<<"label_seeds.size="<<mask_seeds.size()<<endl; imshow("seeds image",img_seeds); } int main() { Mat img=imread("D:/Qt/MyImage/baboon.jpg",1); superpixelSeeds(img); // superpixelLSC(img); waitKey(); return 0; }
superPixelSeeds()方法计算的结果如下:
superpixelLSC(img)
运行结果如下:
superpixelSLIC(img);运行结果如下: