1

我需要使用 EM 算法superpixel使用 OpenCV 的期望最大化算法将我的每个图像分成两组。

我已经初始化了第 i 个超像素的图像和掩码,我将我的超像素的像素复制到了一个新的 Mat 中,这是 EM 算法的输入,但我不明白我怎么能不考虑黑色像素的背景。

我不需要丢失每个像素/超像素的空间信息。

超像素示例

那是我现在的代码

#include <opencv2/highgui.hpp>
#include <iostream>
#include <opencv2/ximgproc/slic.hpp>
#include <opencv2/ml.hpp>
#include <opencv2/imgproc.hpp>

using namespace cv;
using namespace cv::ml;
using namespace std;


void observe_labels_and_means(const Mat& labels, const Mat& means, int h, int w){

int dimension = 3;

Mat rgb_image(h, w, CV_8UC3);
MatIterator_<Vec3b> rgb_first = rgb_image.begin<Vec3b>();
MatIterator_<Vec3b> rgb_last = rgb_image.end<Vec3b>();
MatConstIterator_<int> label_first = labels.begin<int>();

Mat means_u8;
means.convertTo(means_u8, CV_8UC1, 255.0);
Mat means_u8c3 = means_u8.reshape(dimension);

while(rgb_first != rgb_last){
    const Vec3b& rgb = means_u8c3.ptr<Vec3b>(*label_first)[0];
    *rgb_first = rgb;
    ++rgb_first;
    ++label_first;  
}

imshow("tmp", rgb_image);
waitKey();
}


int main(int argc, char** argv) {

Mat image = imread("Teddy_L.png");
const int image_rows = image.rows;
const int image_cols = image.cols;
int dimension = 3;

//VAR SUPERPIXEL
Mat labels, contour, mask;
int number_sp;
Ptr<cv::ximgproc::SuperpixelSLIC> slic = cv::ximgproc::createSuperpixelSLIC(image);

//SLIC
slic->iterate();
slic->getLabels(labels);
number_sp = slic->getNumberOfSuperpixels();

//TRY ON A SINGLE SUPERPIXEL
mask = (labels==30);
Mat temp(image_rows, image_cols, CV_64FC4);
image.copyTo(temp, mask);
imshow("superpixel", temp);

//INPUT FOR TRAINING
Mat reshaped_temp = temp.reshape(1, image_cols*image_rows);
Mat samples;
reshaped_temp.convertTo(samples, CV_64FC1, 1.0/255.0);
Mat labels_em, probs, log_likelihoods;

//EM
Ptr<EM> em_model = EM::create();
em_model->setClustersNumber(2);
em_model->setCovarianceMatrixType(EM::COV_MAT_DIAGONAL);
    em_model->setTermCriteria(TermCriteria(TermCriteria::COUNT+TermCriteria::EPS,        EM::DEFAULT_MAX_ITERS, 1e-6));

//TRAINING
em_model->trainEM(samples, log_likelihoods, labels, probs);
Mat means = em_model->getMeans();

//RESULT
observe_labels_and_means(labels, means, image_rows, image_cols);

  waitKey();
  return 0;
}

我尝试使用带有 Alpha 通道的广告图片,但仍考虑背景像素。

谢谢。

4

0 回答 0