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);運行結果如下:


浙公網安備 33010602011771號