0

I am trying to use opencv EM algorithm library.

I tried some example about EM algorithm such like this and this first, but I got the same problem in these code. It take me lots of time in EM training step.

This is my testing code for image segmentation from this website:

#include <opencv2/opencv.hpp>
#include <opencv2/legacy/legacy.hpp>
using namespace std;
using namespace cv;
Mat asSamplesVectors(Mat& img);
/** @function main */
int main(int argc, char** argv)
{
    Mat image; int no_of_clusters = 2;
    image = imread("images/flower.jpg");
    Mat samples = asSamplesVectors(image);

    cout << "Starting EM training" << endl;
    EM em(no_of_clusters);
    em.train(samples);
    cout << "Finished training EM" << endl;

    vector<Mat> segmented;
    for (int i = 0; i < no_of_clusters; i++)
        segmented.push_back(Mat::zeros(image.rows, image.cols, CV_8UC3));

    int index = 0;
    for (int y = 0; y < image.rows; y++) {
        for (int x = 0; x < image.cols; x++) {
            int result = em.predict(samples.row(index++))[1];
            segmented[result].at<Point3i>(y, x, 0) = image.at<Point3i>(y, x, 0);
        }
    }
    imshow("result", samples);
    return(0);
}

Mat asSamplesVectors(Mat& img) {
    Mat float_img;
    img.convertTo(float_img, CV_32F);

    Mat samples(img.rows * img.cols, 3, CV_32FC1);

    /* Flatten  */
    int index = 0;
    for (int y = 0; y < img.rows; y++) {
        Vec3f* row = float_img.ptr<Vec3f>(y);
        for (int x = 0; x < img.cols; x++)
            samples.at<Vec3f>(index++, 0) = row[x];
    }
    return samples;
}

I test in VS2013, opencv 2.4.9 and opencv 2.4.11.

This is my testing image.

In this code, it show me the error message.

The error step is segmented[result].at<Point3i>(y, x, 0) = image.at<Point3i>(y, x, 0);

My first question is: why the EM training so slowly. Is it normally?

Second question is: what's wrong with my code error and is there any better example to let me know the usage of EM?

Community
  • 1
  • 1
Min Mun
  • 81
  • 8

1 Answers1

1

I found the answer of first problem, my testing image is too large to training. The size of training image is need to scale smaller.

I use this article to modify pixel and it works.

Community
  • 1
  • 1
Min Mun
  • 81
  • 8